Android开发

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

本文主要是介绍Android 跨进程通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!" 这是客户端发给服务端的,证明服务端已经收到!

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

这篇关于Android 跨进程通Messenger(简单易懂)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!