1、跨進(jìn)程Messager 多應(yīng)用間單線程
把Messenger比喻為一個(gè)信使岛马,信使的作用是派信;那么Message就比喻為信件桥滨、信封摆碉,即信使派的東西;那么Bundle是什么呢顾画?Message里面保存了Bundle取劫,那么bundle可以比喻為信紙,信紙上寫滿了各種我們要傳遞的信息研侣。讀到這里谱邪,讀者應(yīng)該明白了這三者在Messenger通訊方式內(nèi)所扮演的角色了。簡(jiǎn)單來(lái)說(shuō):Messenger把裝有Bundle的Message發(fā)送到別的進(jìn)程庶诡。
###客戶端
private Messenger clientMessenger = new Messenger(handler);
private Handler handler = new Handler(Looper.getMainLooper()){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
Bundle bundle = msg.getData();
Log.i(TAG,"收到遠(yuǎn)程服務(wù)數(shù)據(jù):"+bundle.getString("service"));
}
};
private void bindRemoteService(){
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.example.xxx",
"com.example.xxx.MessengerService"));
boolean isBind = bindService(intent,conn, Service.BIND_AUTO_CREATE);
Log.i(TAG,"bindRemoteService isBind="+isBind);
}
private Messenger messengerProxy;
ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder iBinder) {
Log.i(TAG,"onServiceConnected:");
messengerProxy = new Messenger(iBinder);
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.i(TAG,"onServiceDisconnected:");
}
};
private void sendData(){
if (messengerProxy == null) return;
Message message = new Message();
message.replyTo = clientMessenger;
Bundle bundle = new Bundle();
bundle.putString("client","這是客戶端發(fā)送數(shù)據(jù):"+messageid);
message.setData(bundle);
messengerProxy.send(message);
}
###服務(wù)端
//創(chuàng)建服務(wù)端Messenger
private final Messenger mMessenger = new Messenger(messengerHandler);
@Override
public IBinder onBind(Intent intent) {
//向客戶端返回IBinder對(duì)象惦银,客戶端利用該對(duì)象訪問(wèn)服務(wù)端
return mMessenger.getBinder();
}
//拿到客戶端的message 發(fā)送消息
private Handler messengerHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
//取出客戶端的消息內(nèi)容
Bundle bundle = msg.getData();
String clientMsg = bundle.getString("client");
Log.i(TAG, "來(lái)自客戶端的消息:" + clientMsg);
//新建一個(gè)Message對(duì)象,作為回復(fù)客戶端的對(duì)象
Message message = Message.obtain();
Bundle bundle1 = new Bundle();
bundle1.putString("service", clientMsg+",服務(wù)端收到");
message.setData(bundle1);
try {
msg.replyTo.send(message);
} catch (RemoteException e) {
e.printStackTrace();
}
}
};
2末誓、AIDL 多應(yīng)用間多線程
參數(shù)定向tag
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者