Service与Activity通信方式之Messenger(信使)
Service与Activity通信方式之Messenger(信使)
Messenger 通信内在也是用的AIDL
service 端
public class MyService extends Service { private Handler mHandler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case 0: cMessenger = msg.replyTo; send(); break; default: break; } } }; private Messenger mMessenger = new Messenger(mHandler); private Messenger cMessenger; //客户端的Messenger @Override public IBinder onBind(Intent intent) { return mMessenger.getBinder(); } protected void send() { Message message = Message.obtain(null, 1, 0, 1); try { cMessenger.send(message); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
activity
public class MainActivity extends Activity { private Messenger mMessenger; //客户端信使 private Messenger rMessenger; //service端信使 private Handler mHandler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case 1: Toast.makeText(MainActivity.this, "收到消息", 0).show(); break; default: break; } } }; private MyConn mConn; //ServiceConnection的子类 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btn = (Button) this.findViewById(R.id.test); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent service = new Intent(MainActivity.this, MyService.class); mConn = new MyConn(); //利用bindService 启动service bindService(service, mConn, Context.BIND_AUTO_CREATE); } }); } private void sendMessage() { Message message = Message.obtain(null, 0); //第一次给service发送消息时要把自己的Messenger给带过去 message.replyTo = mMessenger; try { rMessenger.send(message); } catch (RemoteException e) { e.printStackTrace(); } } class MyConn implements ServiceConnection { @Override public void onServiceConnected(ComponentName name, IBinder service) { rMessenger = new Messenger(service); //通过IBinder获得service的信使 mMessenger = new Messenger(mHandler); //创建客户端的信使 sendMessage(); } @Override public void onServiceDisconnected(ComponentName name) { rMessenger = null; } }
}