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);
        }

相关内容

热门资讯

随着!pokemmo脚本辅助下... 随着!pokemmo脚本辅助下载,微信小程序透视挂,一贯存在有辅助工具(哔哩哔哩)pokemmo脚本...
推出新举措!约局吧辅助器,潮友... 推出新举措!约局吧辅助器,潮友会鱼虾蟹破解,都是真的是有辅助技巧(哔哩哔哩)进入游戏-大厅左侧-新手...
受玩家影响!拱趴大菠萝有挂吗,... 您好,拱趴大菠萝有挂吗这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩...
近期!约局吧德州真的有透视挂吗... 近期!约局吧德州真的有透视挂吗,微信微乐小程序修改器,其实真的有辅助教程(哔哩哔哩)1、全新机制【约...
目前!wepoker私人定制透... 目前!wepoker私人定制透视,pokeplus脚本,竟然是真的有辅助工具(哔哩哔哩)1、poke...
长期以来!we poker免费... 长期以来!we poker免费辅助器,新玉海楼茶苑脚本,切实真的有辅助教程(哔哩哔哩)1、起透看视 ...
今天下午!hhpoker有没有... 今天下午!hhpoker有没有辅助,随意玩5元流量包,好像存在有辅助工具(哔哩哔哩)1、不需要AI权...
据权威媒体报道!wepoker... 据权威媒体报道!wepoker有透视功能吗,天酷辅助器,竟然是真的有辅助技巧(哔哩哔哩)1)天酷辅助...
值得注意的是!德普之星私人局辅... 值得注意的是!德普之星私人局辅助免费,赣牌圈破解器,其实有辅助攻略(哔哩哔哩)1)德普之星私人局辅助...
受玩家影响!hhpoker真能... 受玩家影响!hhpoker真能买到挂吗,潮汕来物局游戏源码,一直是真的有辅助脚本(哔哩哔哩)潮汕来物...