标签:
一、android 中进程间通信常用的有以下几种机制
-----------------------------------------------------------------------------------------------------------------------
名称 优点 缺点 适用场景
-----------------------------------------------------------------------------------------------------------------------
Bundle 简单易用 只能传输Bundle支持的数据类型 四大组件间的进程通信
-----------------------------------------------------------------------------------------------------------------------
文件共享 简单易用 不适合高并发场景,并且无法做到 无并发访问情形,交换简单
进程间及时通信 的数据实时性不高的场景
-----------------------------------------------------------------------------------------------------------------------
AIDL 功能强大,支持一对多并发 使用稍复杂,需要处理好线程同步 一对多通信且有RPC需求
通信,支持实时通信
-----------------------------------------------------------------------------------------------------------------------
Messenger 功能一般,支持一对多串行 不能很好处理高并发情形,不支持 低并发的一对多即时通
通信,支持实时通信 RPC, 数据通过Message进行传输 信,无RPC需求 或者无需
只能传输Bundle支持的数据 类型 返回结果的RPC需求
----------------------------------------------------------------------------------------------------------------------
ContentProvider 在数据源访问页面功能强大, 可以理解为受约束的AIDL, 一对多的进程间的数据共享
支持一对多并发数据共享, 主要提 供数据源的CRUD操作
可通过Call方法扩展其他操作
----------------------------------------------------------------------------------------------------------------------
Socket 功能强大,可以通过网络数 实现细节有点繁琐 网络数据交换
字传输 节流,支持一对多 ,不支持直接的RPC
并发实时通信
---------------------------------------------------------------------------------------------------------------------
二、 Bundle
Bundle实现了Parcelable接口,所以可以方便的在不同进程间传输,当在一个进程中启动了另外一个进程的Activity、Service、Receiver,可以在Bundle中附加需要传输给远程进程的信息并通过Intent发送出去。
三、文件共享
Activity1:----------------- private void persistToFile() { new Thread(new Runnable() { @Override public void run() { User user = new User(1, "hello world", false); File dir = new File(MyConstants.CHAPTER_2_PATH); if (!dir.exists()) { dir.mkdirs(); } File cachedFile = new File(MyConstants.CACHE_FILE_PATH); ObjectOutputStream objectOutputStream = null; try { objectOutputStream = new ObjectOutputStream( new FileOutputStream(cachedFile)); objectOutputStream.writeObject(user);//利用Serializable序列化的过程 Log.d(TAG, "persist user:" + user); } catch (IOException e) { e.printStackTrace(); } finally { MyUtils.close(objectOutputStream); } } }).start(); } Activity2:---------------- private void recoverFromFile() { new Thread(new Runnable() { @Override public void run() { User user = null; File cachedFile = new File(MyConstants.CACHE_FILE_PATH); if (cachedFile.exists()) { //对MainActivity中user对象反序列化的过程(Serializable), //得到的是一个新的对象 ObjectInputStream objectInputStream = null; try { objectInputStream = new ObjectInputStream( new FileInputStream(cachedFile)); user = (User) objectInputStream.readObject(); Log.d(TAG, "recover user:" + user); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { MyUtils.close(objectInputStream); } } } }).start(); }
四、Messenger
4.1 server端
public class MessengerService extends Service { private static final String TAG = "MessengerService"; private static class MessengerHandler extends Handler {//1.创建一个Handler @Override public void handleMessage(Message msg) { switch (msg.what) { case MyConstants.MSG_FROM_CLIENT: Log.i(TAG, "receive msg from Client:" + msg.getData().getString("msg")); Messenger client = msg.replyTo;//这里是:客户端接收服务端的Messenger Message relpyMessage = Message.obtain(null, MyConstants.MSG_FROM_SERVICE); Bundle bundle = new Bundle(); bundle.putString("reply", "嗯,你的消息我已经收到,稍后会回复你。"); relpyMessage.setData(bundle); try { client.send(relpyMessage);//<----- } catch (RemoteException e) { e.printStackTrace(); } break; default: super.handleMessage(msg); } } } //2.通过handlercg创建一个Messenger对象 private final Messenger mMessenger = new Messenger(new MessengerHandler()); @Override public IBinder onBind(Intent intent) { return mMessenger.getBinder();//返回底层的Binder }
4.2 Client端
public class MessengerActivity extends Activity { private static final String TAG = "MessengerActivity"; private Messenger mService; private Messenger mGetReplyMessenger = new Messenger(new MessengerHandler()); private static class MessengerHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case MyConstants.MSG_FROM_SERVICE: Log.i(TAG, "receive msg from Service:" + msg.getData().getString("reply")); break; default: super.handleMessage(msg); } } } private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { mService = new Messenger(service);//服务端接收客户端的Messenger Log.d(TAG, "bind service"); Message msg = Message.obtain(null, MyConstants.MSG_FROM_CLIENT); Bundle data = new Bundle(); data.putString("msg", "hello, this is client."); msg.setData(data); msg.replyTo = mGetReplyMessenger;//客户端接收服务端的Messenger try { mService.send(msg);//<----- } catch (RemoteException e) { e.printStackTrace(); } } public void onServiceDisconnected(ComponentName className) { } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_messenger); Intent intent = new Intent("com.ryg.MessengerService.launch"); bindService(intent, mConnection, Context.BIND_AUTO_CREATE);//1.绑定service } @Override protected void onDestroy() { unbindService(mConnection); super.onDestroy(); } }
五、AIDL
5.1远端service实现
AIDL接口实现:
//IBookManager.aidl interface IBookManager { //声明暴露给客户端的接口 List<Book> getBookList(); void addBook(in Book book); }
public class BookManagerService extends Service {//1.创建service用来监听客户端连接请求 private static final String TAG = "BMS"; private AtomicBoolean mIsServiceDestoryed = new AtomicBoolean(false); private CopyOnWriteArrayList<Book> mBookList = new CopyOnWriteArrayList<Book>(); private Binder mBinder = new IBookManager.Stub() {//实现aidl接口 @Override public List<Book> getBookList() throws RemoteException { return mBookList; } @Override public void addBook(Book book) throws RemoteException { mBookList.add(book); } @Override public void onCreate() { super.onCreate(); mBookList.add(new Book(1, "Android")); mBookList.add(new Book(2, "Ios")); } @Override public IBinder onBind(Intent intent) { return mBinder; } }
5.2 客户端实现(简单理解篇,可能有ANR)
public class BookManagerActivity extends Activity { private static final String TAG = "BookManagerActivity"; private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { IBookManager bookManager = IBookManager.Stub.asInterface(service); try { List<Book> list = bookManager.getBookList(); Log.i(TAG, "query book list, list type:" + list.getClass().getCanonicalName()); Log.i(TAG, "query book list:" + list.toString()); } catch (RemoteException e) { e.printStackTrace(); } } public void onServiceDisconnected(ComponentName className) { } }; private IOnNewBookArrivedListener mOnNewBookArrivedListener = new IOnNewBookArrivedListener.Stub() { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_book_manager); Intent intent = new Intent(this, BookManagerService.class); bindService(intent, mConnection, Context.BIND_AUTO_CREATE);//1.绑定服务 } @Override protected void onDestroy() { unbindService(mConnection); super.onDestroy(); } }
标签:
原文地址:http://my.oschina.net/shieh/blog/524791