android - 如何在不停止服务或断开 ble 连接的情况下建立使用服务连接的 BLE 连接以跨 Activity 使用?

标签 android android-service bluetooth-lowenergy android-ble

我有 3 个组件。

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

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

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

Activity1 正在通过绑定(bind)服务连接到 BLE 设备。

Intent gattServiceIntent = new Intent(mContext,BleService.class);//In Activity1 context
bindService(gattServiceIntent, mServiceConnection,BIND_AUTO_CREATE);

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

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

mContext.unbindService(mServiceConnection);//In Activity1 context

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

我的临时解决方案:

当从 Activity2Activity2 时,我再次重新连接 BLE 设备强>上下文。 (我不想要。)

Activity2 中,我正在检查我的服务是否已经在运行,如果没有运行,那么我会再次从 Activity2 上下文绑定(bind)服务。

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

时断开连接

有任何解决方案可以在 Activity 中保持 ble 设备连接吗?

最佳答案

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

bound service example

关于android - 如何在不停止服务或断开 ble 连接的情况下建立使用服务连接的 BLE 连接以跨 Activity 使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33581347/

相关文章:

java - Android:异常 "java.lang.IllegalStateException: Scheme ' https' 未注册”

java - 如何使用 FCM 管理聊天应用程序的推送通知

安卓摄像头在后台

android - 从相机拍照而不预览

Android BLE 连接速度问题

android - GreenDao 多对多关系

android - 如何启用 adbd 在 Android 启动时监听端口?

bluetooth - 如何获得蓝牙低功耗设备的实际名称?

android - 使用 react-native-ble-plx 避免重复的 BLE 设备

android - 使用 fakedrag 锁定 viewpager