我听说外设停止广告是一种很好的做法,因为它不再需要新的连接,以节省电池电量 .

那么,在我的外围 onConnectionStateChange 中,我这样称为 advertiser.stopAdvertising(advertiseCallback)

private final BluetoothGattServerCallback bluetoothServerCallback = new BluetoothGattServerCallback()  {

    @Override
    public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {
        Log.d(TAG, String.format("onConnectionStateChange status=%d, newState=%d", status, newState));
        super.onConnectionStateChange(device, status, newState);

        // advertiser should be turned off when connection state changes
        // but the problem is - this breaks the client side service discovery
        // so, I'm not sure what would be the right moment to stop advertising

        advertiser.stopAdvertising(advertiseCallback);
    }

在我连接并使用 BluetoothProfile.STATE_CONNECTED 接收 onConnectionStateChange 之后的客户端,我打电话

connectedPeripheralGatt.discoverServices()

并等待 onServicesDiscovered 回调 .

问题是,如果外围设备已停止广告, onServicesDiscovered 接收状态代码257(这是通用模糊GATT_FAILURE的常量),并且不会发现任何服务 .

如果我注释 stopAdvertising ,客户端 onServicesDiscovered 按预期工作,但外围设备继续广告,虽然我不再需要它 .

How then it should work? How do I stop advertising when it is no longer needed?

两个设备都没有配对/绑定 . 我不确定配对设备会发生什么 - 即使由于真实的MAC地址而停止广告,也可能 onServicesDiscovered 也能正常工作,但我想让它在没有配对的情况下工作 .