不需要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 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,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!" 这是客户端发给服务端的,证明服务端已经收到!
"嗯,稍后回复你!" 这是服务端返回给客户端的,证明客户端也收到了,并且还是实时通讯哦,到此我们的跨进程传递数据通讯完整结束啦,是不是很简单!
以上是内存溢出为你收集整理的Android 跨进程通Messenger(简单易懂)全部内容,希望文章能够帮你解决Android 跨进程通Messenger(简单易懂)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)