在 Android 11 上,Google更改了 Bluetooth 的权限模型,导致 BluetoothServerSocket 在应用程序处于后台或锁屏状态时无法接受连接。解决该问题的方法是在 AndroidManifest.xml 文件中添加以下权限:
。 代码示例如下:
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
mBluetoothAdapter.getBluetoothLeAdvertiser().setLegacyMode(true); // Enable pairing with less secure devices (pre Android 10 devices)
mBluetoothAdapter.getBluetoothLeAdvertiser().setAutoConnect(false);
mBluetoothAdapter.setName("SomeDevice");
mAdvertiseSettings = new AdvertiseSettings.Builder().setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED).setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM).setTimeout(0).setConnectable(true).build();
mAdvertiseData = new AdvertiseData.Builder().setIncludeDeviceName(false).build();
ParcelUuid pUuid = new ParcelUuid(UUID.fromString(getString(R.string.uuid)));
mAdvertiseData = new AdvertiseData.Builder().addServiceUuid(pUuid).setIncludeDeviceName(false).build();
Log.d("BLE", "Advertising started");
mBluetoothLeAdvertiser.startAdvertising(mAdvertiseSettings, mAdvertiseData, mAdvertiseCallback);
}