您的位置:

Android IPC通信方式及其实现

一、Bundle

Bundle是Android系统中最基础的IPC通信方式,可以在Activity之间传递数据。可以向Bundle中存放各种基本数据类型,如字符串、整型、布尔值等,也可以存放复杂的Parcelable对象。

示例代码如下:

``` //Activity1将数据存入Bundle并启动Activity2 Bundle bundle = new Bundle(); bundle.putInt("intData", 1); bundle.putString("stringData", "hello"); MyParcelableObject parcelableObject = new MyParcelableObject(); bundle.putParcelable("parcelableData", parcelableObject); Intent intent = new Intent(this, Activity2.class); intent.putExtras(bundle); startActivity(intent); //Activity2从Intent中获取数据 Intent intent = getIntent(); Bundle bundle = intent.getExtras(); int intData = bundle.getInt("intData"); String stringData = bundle.getString("stringData"); MyParcelableObject parcelableObject = bundle.getParcelable("parcelableData"); ```

二、AIDL

AIDL全名为Android Interface Definition Language,是Android系统中远程服务通信的一种方式,支持进程间的方法调用。通过AIDL,我们可以定义接口,并用一个服务向外提供这个接口,其他进程通过绑定服务可以获取到该接口的代理对象,进而进行方法调用。

示例代码如下:

MyInterface.aidl文件定义 ``` interface MyInterface { void sendData(in String data); String getData(); } ``` MyInterfaceImpl.java实现 ``` public class MyInterfaceImpl extends MyInterface.Stub { private String mData; @Override public void sendData(String data) { mData = data; } @Override public String getData() { return mData; } } ``` MyService.java服务定义 ``` public class MyService extends Service { private MyInterfaceImpl mBinder = new MyInterfaceImpl(); @Nullable @Override public IBinder onBind(Intent intent) { return mBinder; } } ``` Activity中调用远程接口 ``` private MyInterface mInterface; private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { mInterface = MyInterface.Stub.asInterface(service); } @Override public void onServiceDisconnected(ComponentName name) { mInterface = null; } }; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = new Intent(this, MyService.class); bindService(intent, mConnection, BIND_AUTO_CREATE); } private void sendDataToRemoteService(String data) { try { mInterface.sendData(data); } catch (RemoteException e) { e.printStackTrace(); } } private String getDataFromRemoteService() { try { return mInterface.getData(); } catch (RemoteException e) { e.printStackTrace(); } return null; } ```

三、Messenger

Messenger是AIDL的一种简化版,它是Google提供的一种轻量级IPC方式,通过Handler实现进程间的通讯。Messenger是基于AIDL实现的,但对于进程间传输数据,只能使用Bundle类型。

示例代码如下:

MyService.java定义Messenger ``` private class MyHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_SEND_DATA: Bundle bundle = msg.getData(); String data = bundle.getString("data"); mData = data; Messenger clientMessenger = msg.replyTo; Message replyMsg = Message.obtain(null, MSG_REPLY_DATA); replyMsg.getData().putString("reply_data", "reply " + mData); try { clientMessenger.send(replyMsg); } catch (RemoteException e) { e.printStackTrace(); } break; default: super.handleMessage(msg); } } } private Messenger mMessenger = new Messenger(new MyHandler()); @Nullable @Override public IBinder onBind(Intent intent) { return mMessenger.getBinder(); } ``` Activity中与远程进程通讯 ``` private Messenger mMessenger; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = new Intent(this, MyService.class); Messenger messenger = new Messenger(new MyHandler()); intent.putExtra("messenger", messenger); bindService(intent, mConnection, BIND_AUTO_CREATE); } private void sendDataToRemoteService(String data) { Message msg = Message.obtain(null, MSG_SEND_DATA); Bundle bundle = new Bundle(); bundle.putString("data", data); msg.setData(bundle); msg.replyTo = mMessenger; try { mService.send(msg); } catch (RemoteException e) { e.printStackTrace(); } } private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_REPLY_DATA: String replyData = msg.getData().getString("reply_data"); break; default: super.handleMessage(msg); } } }; private Messenger mClientMessenger = new Messenger(mHandler); private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { mMessenger = new Messenger(service); } @Override public void onServiceDisconnected(ComponentName name) { mMessenger = null; } }; ```

四、ContentProvider

ContentProvider是Android系统中数据共享的一种方式,由一个进程提供数据,其他进程通过URI访问数据。可以用它在不同应用程序之间共享数据,而且还可以保证数据的完整性和安全性。

示例代码如下:

MyContentProvider.java ``` public class MyContentProvider extends ContentProvider { private MyDatabaseHelper mDbHelper; private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); static { sUriMatcher.addURI("com.example", "table1", 1); sUriMatcher.addURI("com.example", "table1/#", 2); } @Override public boolean onCreate() { mDbHelper = new MyDatabaseHelper(getContext()); return true; } @Nullable @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteDatabase db = mDbHelper.getReadableDatabase(); Cursor cursor; switch (sUriMatcher.match(uri)) { case 1: cursor = db.query("table1", projection, selection, selectionArgs, null, null, sortOrder); break; case 2: String id = uri.getPathSegments().get(1); cursor = db.query("table1", projection, "_id = ?", new String[]{id}, null, null, sortOrder); break; default: throw new IllegalArgumentException("Unknown URI: " + uri); } return cursor; } @Nullable @Override public String getType(Uri uri) { return null; } @Nullable @Override public Uri insert(Uri uri, ContentValues values) { SQLiteDatabase db = mDbHelper.getWritableDatabase(); long rowId = db.insert("table1", null, values); if (rowId > 0) { Uri insertUri = ContentUris.withAppendedId(uri, rowId); getContext().getContentResolver().notifyChange(insertUri, null); return insertUri; } return null; } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { SQLiteDatabase db = mDbHelper.getWritableDatabase(); int count; switch (sUriMatcher.match(uri)) { case 1: count = db.delete("table1", selection, selectionArgs); break; case 2: String id = uri.getPathSegments().get(1); count = db.delete("table1", "_id = ?", new String[]{id}); break; default: throw new IllegalArgumentException("Unknown URI: " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { SQLiteDatabase db = mDbHelper.getWritableDatabase(); int count; switch (sUriMatcher.match(uri)) { case 1: count = db.update("table1", values, selection, selectionArgs); break; case 2: String id = uri.getPathSegments().get(1); count = db.update("table1", values, "_id = ?", new String[]{id}); break; default: throw new IllegalArgumentException("Unknown URI: " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } } ``` Activity中访问数据 ``` private void accessData() { Uri uri = Uri.parse("content://com.example/table1"); String[] projection = {"_id", "name", "description"}; Cursor cursor = getContentResolver().query(uri, projection, null, null,null); while (cursor.moveToNext()) { int id = cursor.getInt(0); String name = cursor.getString(1); String description = cursor.getString(2); } cursor.close(); } ```
Android IPC通信方式及其实现

2023-05-14
Android IPC:如何实现进程间通信?

2023-05-14
Android IPC通信方式以及使用场景

2023-05-14
AIDL: 实现Android进程间通信的关键技术

2023-05-14
Android Binder:实现进程间通信的核心机制

Android系统的进程间通信(IPC)机制是整个系统中最重要的部分之一,这个机制让不同的进程之间能够交换数据和信息。在Android系统中,主要采用的IPC机制是Binder机制。Binder机制的

2023-12-08
Android Parcel:轻松实现进程间通信

2023-05-14
Android平台下的Tee读写实现方法

2023-05-14
Android共享内存实现进程间通信

一、什么是共享内存 共享内存是一种IPC(进程间通信)的方式,它可以在多个进程间共享一段地址空间,从而达到通信的目的。共享内存通信的优点是速度快,因为不需要复制数据,而是直接操作内存中的数据。共享内存

2023-12-08
Android Binder机制:实现进程间通信的核心技术

2023-05-14
解密Android Binder机制:实现进程间通信

一、前言 在Android系统中,各个应用程序之间需要进行进程间通信,以实现数据共享和交互功能。Binder机制是Android系统中最核心、最基础的进程间通信方式。本文将对Android Binde

2023-12-08
Android AIDL跨进程通信详解

2023-05-19
Python实现Android Socket通信

一、Socket通信概述 Socket,即套接字,是在网络中使用的一种通信机制,它是计算机之间通信的基石。Socket通信采用客户端/服务端的模式,客户端向服务端发出请求,服务端接收请求并返回响应结果

2023-12-08
Android 架构详解

2023-05-22
Android Ripple效果及其实现

一、什么是Ripple效果 Android Ripple效果是一种动态的交互反馈效果,当用户点击屏幕上的按钮或触摸元素时,屏幕上会泛起类似水波的涟漪效果,这种涟漪效果被称为Ripple效果。 在And

2023-12-08
用Python实现Android USB通信功能

2023-05-14
Android内核跨进程共享内存的高效实现方式:ashmem

2023-05-18
Android架构模式:MVC、MVP、MVVM,及其实现方

在Android开发中,选择合适的架构模式对于项目的开发和后期维护都是至关重要的。Android中常用的架构模式包括MVC、MVP和MVVM。本文将深入探讨这三种架构模式的原理、实现方式以及优缺点,帮

2023-12-08
Android中的HIDL:硬件抽象接口定义语言

一、为什么需要HIDL? 在Android系统中,访问硬件的方式通常是通过HAL(Hardware Abstraction Layer)来实现的。但是,HAL在某些方面存在着不足,例如:为了适配不同的

2023-12-08
Android BindService 的实现原理及用法

2023-05-14
使用Python实现Android UDP通信

2023-05-14