AndroidでバインドサービスをbindServiceによって実装する方法
Androidでバインドサービス(bindService)を実装するには、次の手順に従います。
- Serviceを継承したServiceクラスを作成し、何らかのメソッドを実装します。onBind()メソッド内では、クライアントと通信するためのIBinderオブジェクトを返します。
public class MyService extends Service {
private final IBinder mBinder = new MyBinder();
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private class MyBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
// 其他方法和逻辑
}
- アクティビティ内にてServiceConnectionオブジェクトを宣言し、そのメソッドを実装します。
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// 获取服务对象
MyService.MyBinder binder = (MyService.MyBinder) service;
MyService myService = binder.getService();
// 在此处可以调用服务中的方法
}
@Override
public void onServiceDisconnected(ComponentName name) {
// 断开与服务的连接
}
};
- アクティビティ内でバインドサービスを行うには、bindService()メソッドを使用します。
Intent intent = new Intent(this, MyService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
- サービスとの通信が不要になったら unbindService() メソッドを使ってバインドを解除できます。
unbindService(mConnection);
ご注意ください
- サービスをバインドする場合は、マニフェストファイルにServiceコンポーネントを宣言する必要があります。
- バインドサービスを使用する際は、適切なパーミッションを要求する必要があります(例: )。
- サービスを unbind する際は、事前に bind サービスのメソッドを呼び出したことを確認してください。そうでなければ例外が発生します。
- サービスバインディングのライフサイクルはアクティビティのライフサイクルとは無関係です。