在Android中,可以通过以下步骤实现多次调用bindService:
以下是一个示例代码:
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;
}
}
}
在Service中,可以通过Binder提供一个通信接口,供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的多次绑定和通信。