AndroidでbindServiceを複数回呼び出す方法を教えてください。
Android では bindService の複数回呼び出しは以下手順により実現できます:
- サービスへの接続状態をリッスンしてコールバックを受け取る ServiceConnection オブジェクトを作成する
- ServiceをバインドするIntentオブジェクトを作成
- bindServiceメソッドを呼び出し、IntentオブジェクトとServiceConnectionオブジェクトを渡します。これにより、サービスとの接続がトリガーされます。
- ServiceConnectionのonServiceConnectedメソッドで、Serviceとの通信インターフェースを取得し、このインターフェースを使ってServiceと通信できます。
- サービスとの通信が必要なくなったら、unbindServiceメソッドを呼び出してサービスのバインド解除をする。
これはサンプルコードです:
public class MainActivity extends AppCompatActivity {
private MyServiceConnection mServiceConnection;
private MyServiceInterface mServiceInterface;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mServiceConnection = new MyServiceConnection();
// 第一次绑定Service
Intent intent = new Intent(this, MyService.class);
bindService(intent, mServiceConnection, BIND_AUTO_CREATE);
// 第二次绑定Service
Intent intent2 = new Intent(this, MyService.class);
bindService(intent2, mServiceConnection, BIND_AUTO_CREATE);
}
@Override
protected void onDestroy() {
super.onDestroy();
// 解除与Service的绑定
unbindService(mServiceConnection);
}
private class MyServiceConnection implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
// 获取到与Service的通信接口
mServiceInterface = (MyServiceInterface) iBinder;
// 调用Service中的方法
mServiceInterface.doSomething();
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
// Service连接断开时的回调
mServiceInterface = null;
}
}
}
サービスでは、バインダー経由でActivityから呼び出せる通信インターフェースを提供できる:
public class MyService extends Service {
private MyBinder mBinder = new MyBinder();
@Nullable
@Override
public IBinder onBind(Intent intent) {
// 返回与Service的通信接口
return mBinder;
}
public class MyBinder extends Binder implements MyServiceInterface {
@Override
public void doSomething() {
// Service中的方法
}
}
public interface MyServiceInterface {
void doSomething();
}
}
これにより、ActivityでbindServiceメソッドを複数回呼び出して、Serviceと複数回バインドして通信することが可能になります。