---
title: " Android使用binder访问service的方式"
author: "abc20899"
date: "2013-08-23T09:42:58Z"
tags: []
categories: ["移动开发"]
slug: "android-binder-service"
draft: false
lastmod: "2013-08-23T09:42:58Z"
id: 1929572
url: "https://abc20899.iteye.com/blog/1929572"
---

1\. 我们先来看一个与本地service通信的例子。 \[code="java"]public class LocalService extends Service { @Override public IBinder onBind(Intent intent) { return new LocalBinder(); } public void sayHelloWorld(){ Toast.makeText(this.getApplicationContext(), "Hello World Local Service!", Toast.LENGTH\_SHORT).show(); } public class LocalBinder extends Binder { LocalService getService() { // Return this instance of LocalService so clients can call public methods return LocalService.this; } } } \[/code] local servcie 的代码如上，在onBinder方法中返回binder，binder包含了service的句柄，客户端得到句柄以后就可以调用servcie的公共方法了，这种调用方式是最常见的。 \[code="java"]public class LocalServiceTestActivity extends Activity { static final String TAG = "LocalBinderTestActivity"; ServiceConnection mSc; /\** Called when the activity is first created. \*/ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mSc = new ServiceConnection(){ @Override public void onServiceConnected(ComponentName name, IBinder service) { Log.d(TAG, "service connected"); LocalService ss = ((LocalBinder)service).getService(); ss.sayHelloWorld(); } @Override public void onServiceDisconnected(ComponentName name) { Log.d(TAG, "service disconnected"); } }; } @Override protected void onStart() { super.onStart(); Log.d(TAG, this.getApplicationContext().getPackageCodePath()); Intent service = new Intent(this.getApplicationContext(),LocalService.class); this.bindService(service, mSc, Context.BIND\_AUTO\_CREATE); } @Override protected void onStop() { super.onStop(); //must unbind the service otherwise the ServiceConnection will be leaked. this.unbindService(mSc); } } \[/code] 需要注意的是在onStop中要解绑定service, 否则会造成内存泄露的问题。 2. 我们再看一下与另外一个进程中的service进行通信的问题（跨进程通信！）。 如何将servcie运行在另外一个进程呢？在manifest 里面配置个属性就行了。 android:process=":remote" , 代表这个service运行在同一个应用程序的不同进程中。 \[code="java"] \[/code] \[code="java"]public class RemoteServiceTestActivity extends Activity { static final String TAG = "RemoteServiceTestActivity"; ServiceConnection mSc; public static final int SAY\_HELLO\_TO\_CLIENT = 0; /\** * Handler of incoming messages from service. \*/ class IncomingHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case SAY\_HELLO\_TO\_CLIENT: Toast.makeText(RemoteServiceTestActivity.this.getApplicationContext(), "Hello World Remote Client!", Toast.LENGTH\_SHORT).show(); break; default: super.handleMessage(msg); } } } Messenger messenger\_reciever = new Messenger(new IncomingHandler()); /\** Called when the activity is first created. \*/ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mSc = new ServiceConnection(){ @Override public void onServiceConnected(ComponentName name, IBinder service) { Log.d(TAG, "service connected"); Messenger messenger = new Messenger(service); Message msg = new Message(); msg.what = RemoteService.MSG\_SAY\_HELLO; msg.replyTo = messenger\_reciever; try { messenger.send(msg); } catch (RemoteException e) { e.printStackTrace(); } } @Override public void onServiceDisconnected(ComponentName name) { Log.d(TAG, "service disconnected"); } }; } @Override protected void onStart() { super.onStart(); Log.d(TAG, this.getApplicationContext().getPackageCodePath()); Intent service = new Intent(this.getApplicationContext(),RemoteService.class); this.bindService(service, mSc, Context.BIND\_AUTO\_CREATE); } @Override protected void onStop() { super.onStop(); //must unbind the service otherwise the ServiceConnection will be leaked. this.unbindService(mSc); } } \[/code] 获得service端传来的binder，用来构建一个Messenger向service发送消息。 \[code="java"]public class RemoteService extends Service { public static final int MSG\_SAY\_HELLO = 0; @Override public IBinder onBind(Intent intent) { return messager.getBinder(); } Handler IncomingHandler = new Handler() { @Override public void handleMessage(Message msg) { if(msg.replyTo != null){ Message msg\_client = this.obtainMessage(); msg.what = RemoteServiceTestActivity.SAY\_HELLO\_TO\_CLIENT; try { ((Messenger)msg.replyTo).send(msg\_client); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } } switch (msg.what) { case MSG\_SAY\_HELLO: Toast.makeText(RemoteService.this.getApplicationContext(), "Hello World Remote Service!", Toast.LENGTH\_SHORT).show(); break; default: super.handleMessage(msg); } } }; Messenger messager = new Messenger (IncomingHandler); } \[/code] 构建一个Messenger，包含一个handler，然后将messenger的binder传给客户端，客户端可以通过handler再构造一个messenger与service通信，消息在handler里面被处理。 现在是service端单向响应客户端的消息，同理可以做成双向发送消息，实现双向通信。