不需要AIDL也不需要複雜的ContentProvider,也不需要SharedPreferences或者共用存儲文件! 只需要簡單易懂的Messenger,它也稱為信使,通過它可以在不同進程中傳遞message對象,在message中放入我們需要傳遞的數據你就可以實現跨進程通訊和傳遞數據。廢話不多 ...
不需要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!" 這是客戶端發給服務端的,證明服務端已經收到!
"嗯,你的消息我已經收到,稍後回覆你!" 這是服務端返回給客戶端的,證明客戶端也收到了,並且還是實時通訊哦,到此我們的跨進程傳遞數據通訊完整結束啦,是不是很簡單!