Android 跨进程通Messenger(简单易懂)

时间:2021-05-21

不需要AIDL也不需要复杂的ContentProvider,也不需要SharedPreferences或者共享存储文件!

只需要简单易懂的Messenger,它也称为信使,通过它可以在不同进程中传递message对象,在message中放入我们需要传递的数据你就可以实现跨进程通讯和传递数据。废话不多说,直接上代码。

首先是服务端:

public class Ser extends Service{@Overridepublic IBinder onBind(Intent intent) {return messenger.getBinder();}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// TODO Auto-generated method stubLog.i("Service", "onStartCommand()");return super.onStartCommand(intent, flags, startId);}public Messenger messenger = new Messenger(new MyHandler());public class MyHandler extends Handler{@Overridepublic void handleMessage(Message msg) {Log.i("Ser---TAG", "msg::"+msg.arg1+"want :"+msg.getData().getString("msg"));Messenger messenger = msg.replyTo;Message message = Message.obtain(null, 0);Bundle bundle = new Bundle();bundle.putString("reply", "嗯,你的消息我已经收到,稍后回复你!");message.setData(bundle);try {messenger.send(message);} catch (RemoteException e) {e.printStackTrace();}super.handleMessage(msg);}}

我们在服务端操作了并不多,仅仅是实例化了一个Messenger,并且创建了一个handler用来接收客户端发送过来的消息

接下来看客户端:

public class Client extends Service{private static final String TAG = "Client";protected Messenger mService;public Handler handler = new Handler(){public void handleMessage(Message msg) {Log.i("client --- TAG", "msg:;"+msg.getData().getString("reply"));};};public Messenger messenger = new Messenger(handler);@Overridepublic IBinder onBind(Intent intent) {return null;}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {Intent mIntent = new Intent();mIntent.setClassName("com.example.test1", "com.example.test1.Ser");bindService(mIntent, mBindService, Context.BIND_AUTO_CREATE);return super.onStartCommand(intent, flags, startId);}@Overridepublic void onDestroy() {super.onDestroy();unbindService(mBindService);}private ServiceConnection mBindService = new ServiceConnection(){@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {mService = new Messenger(service);Message message = Message.obtain(null, 0);Bundle bundle = new Bundle();bundle.putString("msg", "hello this is client!");message.replyTo = messenger;message.setData(bundle);try {mService.send(message);} catch (RemoteException e) {e.printStackTrace();}}@Overridepublic void onServiceDisconnected(ComponentName name) {// TODO Auto-generated method stub}};}

同样客户端也需要一个handler来接收服务端返回的消息,还有很关键的一点

当客户端发送消息的时候,需要把接收服务端回复的Messenger通过Message的

replyTo参数传递给服务端,否则会报NullPointerException。然后我们在看下log

"hello this is client!" 这是客户端发给服务端的,证明服务端已经收到!

"嗯,你的消息我已经收到,稍后回复你!" 这是服务端返回给客户端的,证明客户端也收到了,并且还是实时通讯哦,到此我们的跨进程传递数据通讯完整结束啦,是不是很简单!

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章