我正在使用BLE设备开发应用程序。一切都工作正常,除了我在应用程序关闭后维护 BLE 连接时遇到问题。
我正在使用绑定服务 + 启动粘性与前台服务和通知。当我打开应用程序时,我打电话给bindService()
。
问题是如果我不打电话disconnect()
和gatt.close()
,第二次打开应用程序时,由于onAutoConnectionStatusCb()status =10
,我无法访问BLE设备 由于我已经运行了该服务,因此我不需要再次调用bindService()
,但在这种情况下,我不再具有该服务的实例,因此不会调用我的 BroadcastReceiver。
我该如何解决这个问题?
这是我开始服务的方式:
private final Runnable mStartGattRunnable = new Runnable() {
@Override
public void run() {
Intent gattServiceIntent = new Intent(mContext, BluetoothLeService.class);
gattServiceIntent.putExtra(Consts.DEVICE_ADDRESS, mDeviceAddress);
gattServiceIntent.setAction(Consts.STARTFOREGROUND_ACTION);
mContext.startService(gattServiceIntent);
if (mContext.bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE))
CONNECTED = true;
}
};
这是我获取服务实例的方式:
@Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
Log.d(TAG, "onServiceConnected()");
mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
Log.e(TAG, "Unable to initialize Bluetooth");
}
// Automatically connects to the device upon successful start-up initialization.
mBluetoothLeService.connect(mDeviceAddress);
swipeContainer.setRefreshing(true);
}
当我关闭我的应用程序时,我不会断开或关闭任何连接。
在应用程序的第二次启动时,如果我再次呼叫bindService()
,BLE就会卡住。我无法再次访问mBluetoothLeService
...
显然,问题在于我如何连接到 GATT 服务。我有自动连接的false
。我更改了它,它现在可以工作了:
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
mBluetoothGatt = device.connectGatt(this, true, mGattCallback, 2);
else
mBluetoothGatt = device.connectGatt(this, true, mGattCallback);