欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2024-03-06 19:20:20
不需要aidl也不需要复杂的contentprovider,也不需要sharedpreferences或者共享存储文件! 只需要简单易懂的messenger,它也称为...

不需要aidl也不需要复杂的contentprovider,也不需要sharedpreferences或者共享存储文件!

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

首先是服务端:

public class ser extends service{
@override
public ibinder onbind(intent intent) {
return messenger.getbinder();
}
@override
public int onstartcommand(intent intent, int flags, int startid) {
// todo auto-generated method stub
log.i("service", "onstartcommand()");
return super.onstartcommand(intent, flags, startid);
}
public messenger messenger = new messenger(new myhandler());
public class myhandler extends handler{
@override
public 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);
@override
public ibinder onbind(intent intent) {
return null;
}
@override
public 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);
}
@override
public void ondestroy() {
super.ondestroy();
unbindservice(mbindservice);
}
private serviceconnection mbindservice = new serviceconnection(){
@override
public 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();
}
}
@override
public void onservicedisconnected(componentname name) {
// todo auto-generated method stub
}
};
}

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

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

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

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

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