如何建立使用服务进行连接的BLE连接,以跨活动使用而不停止服务或断开ble?

Din*_*avi 5 android android-service bluetooth-lowenergy android-ble

我有3个组成部分。

  1. Activity1 具有用于连接和断开BLE连接的按钮

  2. Activity2 需要从BLE设备获取数据。

  3. 服务 所有连接逻辑(例如getRemoteDevice(),connectGatt等)都属于服务。

Activity1通过绑定服务连接到BLE设备。

Intent gattServiceIntent = new Intent(mContext,BleService.class);//In Activity1 context
bindService(gattServiceIntent, mServiceConnection,BIND_AUTO_CREATE);
Run Code Online (Sandbox Code Playgroud)

并在按下按钮后立即连接到ble设备。

现在,当我从Activity1移到Activity2时,我将取消绑定Activity1中的服务。

mContext.unbindService(mServiceConnection);//In Activity1 context
Run Code Online (Sandbox Code Playgroud)

现在如何在Activity2中使用现有的BLE设备连接?

我的临时解决方案:

当新的服务实例从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");
    }
Run Code Online (Sandbox Code Playgroud)

在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
}  
Run Code Online (Sandbox Code Playgroud)

用于检查我的服务是否正在运行

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;
}
Run Code Online (Sandbox Code Playgroud)

但是函数isMyServiceRunning()始终返回false。表示从Activity1移到Activity2时服务断开连接

在整个活动中保持ble设备连接的解决方案吗?

siv*_*iva 4

在您的 Service 类中创建一个 LocalBinder(扩展 Binder)。从 Activity #1 中,您可以启动服务,还可以使用bindservice 访问binder 对象并调用unbindservice 来断开与服务的连接。从 Activity #2 中,您可以简单地再次调用 bindservice 来访问活页夹对象,因为服务仍在运行。这样您就可以保持服务始终运行并访问连接的蓝牙对象。请参阅下面链接中的示例。

绑定服务示例