咱們使用Handler都是在一個進程中使用的,如何跨進程使用Handler?android
其實這個問題不難解決,本身動手對binder進行一些封裝就能夠簡單實現。可是當你看系統源碼,就會發現,其實這些android都已經爲咱們作好了。ide
使用android系統的android.os.Messenger能夠很方便的跨進程使用Handler。下面是示例程序。函數
首先是服務端。this
public class MessengerTestService extends Service { protected static final String TAG = "MessengerTestService"; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 1: Log.d(TAG, "收到消息"); //獲取客戶端message中的Messenger,用於回調 final Messenger callback = msg.replyTo; try { // 回調 callback.send(Message.obtain(null, 0)); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; } } }; @Override public IBinder onBind(Intent intent) { return new Messenger(mHandler).getBinder(); } }
而後是客戶端spa
public class MainActivity extends Activity { protected static final String TAG = "MainActivity"; Messenger messenger; Messenger reply; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); reply = new Messenger(handler); Intent intent = new Intent(); intent.setClassName("test.messenger", "test.messenger.MessengerTestService"); // 綁定服務 bindService(intent, new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { } @Override public void onServiceConnected(ComponentName name, IBinder service) { Toast.makeText(MainActivity.this, "bind success", 0).show(); messenger = new Messenger(service); } }, Context.BIND_AUTO_CREATE); } public void sendMessage(View v) { Message msg = Message.obtain(null, 1); // 設置回調用的Messenger msg.replyTo = reply; try { messenger.send(msg); } catch (RemoteException e) { e.printStackTrace(); } } private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { Log.d(TAG, "回調成功"); } }; }
客戶端綁定服務端,獲取遠程Messenger的binder對象。調用Messenger的send函數,就能夠吧Message發送至服務端的Handler。.net
同時,若是須要服務端回調客戶端(往客戶端的Handler發消息),則能夠在send的Message中設置replyTo,服務端就能夠往客戶端發送消息了。code
下面咱們看下Messenger的源碼,仍是很簡單的。對象
構造函數進程
public Messenger(Handler target) { mTarget = target.getIMessenger(); }
Handler.getIMessenger()返回的是一個IMessenger的binder對象,它的send方法將會調用Handler的sendMessage方法。get
public void send(Message message) throws RemoteException { mTarget.send(message); }