Android12设备即使应用程序关闭也能保持蓝牙LE连接
创始人
2024-09-30 21:30:06
0

在Android 12中,当应用程序关闭时,系统不会自动断开蓝牙低功耗(Bluetooth LE)连接。这可能会产生一些负面影响,例如浪费电池寿命、占用带宽等。

为了解决此问题,可以使用新的Bluetooth GATT连接API。使用此API,应用程序可以请求系统在特定条件下保持连接。以下是一个示例代码,演示如何保持蓝牙低功耗连接:

private BluetoothGatt mBluetoothGatt;
private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
    // 省略其他回调方法

    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        super.onConnectionStateChange(gatt, status, newState);

        if (newState == BluetoothProfile.STATE_CONNECTED) {
            Log.d(TAG, "Connected to GATT server.");
            gatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH);
            gatt.discoverServices();
        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            Log.d(TAG, "Disconnected from GATT server.");
            mBluetoothGatt.close();
            mBluetoothGatt = null;
        }
    }

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

        if (status == BluetoothGatt.GATT_SUCCESS) {
            BluetoothGattService service = gatt.getService(SERVICE_UUID);
            BluetoothGattCharacteristic characteristic = service.getCharacteristic(CHARACTERISTIC_UUID);
            gatt.setCharacteristicNotification(characteristic, true);

            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_UUID);
            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            gatt.writeDescriptor(descriptor);

            // Request to keep the connection open even when app is closed
            BluetoothGattDescriptor keepAliveDescriptor = characteristic.getDescriptor(KEEP_ALIVE_UUID);
            keepAliveDescriptor.setValue(KEEP_ALIVE_VALUE);
            gatt.writeDescriptor(keepAliveDescriptor);
        }

相关内容

热门资讯

总算了解!wepoker透视a... 总算了解!wepoker透视app下载,wpk辅助,可靠技巧(有挂方法);wepoker透视app下...
玩家必看!哈糖大菠萝软件下载,... 玩家必看!哈糖大菠萝软件下载,aapoker辅助软件合法吗,详细教程(有挂辅助);实战中需综合运用上...
必备科技!wepoker俱乐部... 必备科技!wepoker俱乐部辅助,wepoker怎么获得好牌,细节揭秘(有挂软件);wepoker...
今日百科!佛手在线有挂吗,wp... 今日百科!佛手在线有挂吗,wpk透视辅助,可靠技巧(有挂神器);《WPK辅助透视》‌:支持手机实时对...
一起来探讨!德州辅助工具到底怎... 1、一起来探讨!德州辅助工具到底怎么样,pokemmo辅助工具,安装教程(有挂神器)(UU poke...
玩家必备教程!wejoker黑... 玩家必备教程!wejoker黑侠辅助器,pokemmo手机版脚本,切实教程(有挂神器);人气非常高,...
实操分享!cloudpoker... 自定义cloudpoker怎么开挂系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑克专用...
总算清楚!pokemmo脚本辅... 总算清楚!pokemmo脚本辅助下载,hhpoker软件安装包,可靠教程(有挂方法)1、许多玩家不知...
最新技巧!wepoker底牌透... 最新技巧!wepoker底牌透视,wejoker内置辅助,AI教程(有挂透视)1、点击下载安装,微扑...
技巧知识分享!wejoker透... 技巧知识分享!wejoker透视方法,hhpoker辅助软件是真的么,微扑克教程(有挂辅助);hhp...