gpt4 book ai didi

android - 为什么 BluetoothGattCallback 会在几秒钟后不断断开连接?

转载 作者:行者123 更新时间:2023-11-29 18:32:29 26 4
gpt4 key购买 nike

我尝试连接到 MiBand 2 并保持连接,但几秒钟后它失败并重新连接。

我扫描可用设备并显示它们。当我点击我想连接的设备时,它会连接,但几秒钟后就会断开连接。

在连接设备上我这样做:

private void connectDevice(BluetoothDevice itemAtPosition) {
itemAtPosition.createBond();
Log.i("BOND","Created with device");
bluetoothGatt = itemAtPosition.connectGatt(getApplicationContext(), true, miBandGattCallBack);

}

并在 GattCallBack 上执行以下操作。

miBandGattCallBack = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
switch (newState) {
case BluetoothGatt.STATE_DISCONNECTED:
Log.d("Info", "Device disconnected");

break;
case BluetoothGatt.STATE_CONNECTED: {
Log.i("Infooo", "Connected with device");
Log.i("Infooo", "Discovering services");
gatt.discoverServices();
}
break;
}
}

@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {

if (!sharedPreferences.getBoolean("isAuthenticated", false)) {
authoriseMiBand();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("isAuthenticated", true);
editor.apply();
} else
Log.i("Device", "Already authenticated");
}

@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {

}

@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicWrite(gatt, characteristic, status);
}

@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {

}

@Override
public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
Log.d("Descriptor", descriptor.getUuid().toString() + " Read");
}

@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
Log.d("Descriptor", descriptor.getUuid().toString() + " Written");
}
};

}

我想尽可能长时间地保持连接,几个小时,我的意思是就像通过蓝牙将智能手环连接到手机一样,只要你有电池它就会保持连接。

最佳答案

你所做的似乎没有任何问题,事实上,如果你想尽可能长时间地保持连接而忘记处理重新连接,最好的策略是使用 autoConnect参数 trueconnectGatt方法。设置此参数将告诉 Android 在可用时立即自动连接到您的 MiBand 2。如果它断开连接,Android 会在后台为您连接到它。那里可能发生的事情不取决于您,它很可能与蓝牙设备的固件或移动设备的蓝牙堆栈有关。例如,如果连接的主设备不执行任何 Activity ,固件本身可能会在几秒钟后触发断开连接以节省一些电池。

换句话说,如果您手机的蓝牙芯片组以及外设之一足够好,并且后者的固件不确定地保持连接,您的应用程序就不会断开连接。

[提示]:如果你想达到那个目的,我建议使用一个单独的 Android 服务来处理那里的所有蓝牙内容。在官方文档中你有一个 basic example为此。

关于android - 为什么 BluetoothGattCallback 会在几秒钟后不断断开连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55656714/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com