我有 3 个组件。
Activity1 有用于连接和断开 BLE 连接的按钮
Activity2 需要从 BLE 设备获取数据。
Service 所有的连接逻辑(如 getRemoteDevice()、connectGatt 等)都属于服务。
Activity1正在通过绑定服务连接到 BLE 设备。
Intent gattServiceIntent = new Intent(mContext,BleService.class);//In Activity1 context
bindService(gattServiceIntent, mServiceConnection,BIND_AUTO_CREATE);
并在按下按钮后立即连接到 ble 设备。
现在,当我从Activity1移动到Activity2时,我正在取消绑定Activity1中的服务。
mContext.unbindService(mServiceConnection);//In Activity1 context
现在如何在Activity2中使用现有的 BLE 设备连接?
我的临时解决方案:
当通过从Activity2上下文绑定到Activity2的新服务实例移动到 Activity2 时,我正在重新连接BLE 设备。(这是我不想要的。)
在Activity2中,我正在检查我的服务是否已经在运行,如果没有运行,那么我将再次从Activity2上下文绑定服务。
if(!isMyServiceRunning(BleWrapper.class)){
Intent wrapperServiceIntent = new Intent(mContext,BleWrapper.class);
bindService(wrapperServiceIntent,mBLEWrapperServiceConnection,BIND_AUTO_CREATE);
}else{
Log.w(LOGTAG, "Service already connected. In onCreate");
}
在ServiceConnection回调下触发onServiceConnected()中的连接
@Override
public void onServiceConnected(ComponentName componentName,IBinder service) {
mBluetoothLeService = ((BleWrapper.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
showAlertDialog(getString(R.string.ble_not_supported_on_this_device));
}else {
mBluetoothLeService = BleWrapper.getInstance();
}
mBluetoothLeService.connect(/*address from shared preference*/); //Reconnecting to the same device using address stored in Shared pref
}
检查我的服务是否正在运行
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
但是函数isMyServiceRunning()总是返回 false。表示从Activity1移动到Activity2时服务断开连接
在活动中保持 ble 设备连接的任何解决方案?