- 核心:提供一個定義了客戶端到服務端交互編程接口的IBinder
- 定義接口的三條途徑:
-- 擴展Binder類
> 服務歸應用私有,且跑在同一個進程
> 實例由onBind()返回
> 若服務僅僅爲本應用的後臺工作,那麼推薦使用
> 除非服務被其它應用或進程調用
-- 使用Messenger
> 接口需要跨進程工作
>
Handler:定義在服務中,Messenger基於之而向客戶端分享IBinder,使客戶端能鉤運用消息對象向服務發送命令
> 客戶端亦可自定義一個Messenger,這樣服務可以回傳消息
>
這是IPC的最簡便途徑。Messenger將所有請求排隊到同一個線程——這樣就無需考慮線程安全問題。
> 基於AIDL實現
-- 使用AIDL
> AIDL: Android Interface Definition
Language
> 將對象解構爲操作系統識別的原始類型,跨進成傳送、重組以執行IPC
> 同時處理多個請求應處理線程安全問題
>
創建.aidl文件以定義接口,安卓SDK工具生成一個實現該接口的抽象類來處理IPC。
> 多數應用無必要使用。
擴展Binder類
- 如何創建?
1. 在服務中創建一個Binder類的實例,以下任一方式皆可:
>
包含供客戶端調用的公共方法
>
返回當前服務的實例,它包含客戶端可以調用的公共方法
>
返回一個服務包含的內部類的實例,由它提供客戶端調用的方法
2. 從onBinder()方法返回這個Binder實例
public class LocalService extends Service {
// Binder given to clients
private final IBinder mBinder = new LocalBinder();
// Random number generator
private final Random mGenerator = new Random();
public class LocalBinder extends Binder {
LocalService getService() {
// Return this instance of LocalService so clients can call public methods
return LocalService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public int getRandomNumber() {
return mGenerator.nextInt(100);
}
}
3.
在客戶端,從oonServiceConnected()方法接收到Binder,
然後根據需要調用方法。
public class BindingActivity extends Activity {
LocalService mService;
boolean mBound = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
protected void onStart() {
super.onStart();
// Bind to LocalService
Intent intent = new Intent(this, LocalService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
// Unbind from the service
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
public void onButtonClick(View v) {
if (mBound) {
// Call a method from the LocalService.
// However, if this call were something that might hang, then this request should
// occur in a separate thread to avoid slowing down the activity performance.
int num = mService.getRandomNumber();
Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show();
}
}
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
}
- 關鍵組件:Service, Binder, ServiceConnection
使用Messenger
- 如何運用Messenger?
1. 服務實現一個Handler來接收從客戶端來的回調
2. Handler被用來創建Messenger對象(Handler的引用)
3. Messenger創建onBind()方法返回的IBinder
public class MessengerService extends Service {
static final int MSG_SAY_HELLO = 1;
class IncomingHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_SAY_HELLO:
Toast.makeText(getApplicationContext(), "hello!", Toast.LENGTH_SHORT).show();
break;
default:
super.handleMessage(msg);
}
}
}
final Messenger mMessenger = new Messenger(new IncomingHandler());
@Override
public IBinder onBind(Intent intent) {
Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT).show();
return mMessenger.getBinder();
}
}
4. 客戶端使用IBinder來實例化Messenger,用它來向服務發送消息對象
5. 服務的Handler接收到各個消息對象,具體地說,在handleMessage()方法中
- 此方法中,沒有供客戶端調用的“方法”。取而代之的是由客戶端傳遞消息給服務進行處理
public class ActivityMessenger extends Activity {
Messenger mService = null;
boolean mBound;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the object we can use to
// interact with the service. We are communicating with the
// service using a Messenger, so here we get a client-side
// representation of that from the raw IBinder object.
mService = new Messenger(service);
mBound = true;
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
mService = null;
mBound = false;
}
};
public void sayHello(View v) {
if (!mBound) return;
// Create and send a message to the service, using a supported 'what' value
Message msg = Message.obtain(null, MessengerService.MSG_SAY_HELLO, 0, 0);
try {
mService.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
protected void onStart() {
super.onStart();
// Bind to the service
bindService(new Intent(this, MessengerService.class), mConnection,
Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
// Unbind from the service
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
}
-
注意,本例中沒有展示服務器如何響應客戶端。你需要在客戶端中也穿件Messenger。當客戶端收到onServiceConnected()回調時,向服務端發送一條消息,將客戶端的Messenger作爲send()方法的replyTo參數