解决方案为在Manifest文件中添加ACCESS_BACKGROUND_LOCATION权限,打开targetSdkVersion为31的增强权限。示例代码如下:
在AndroidManifest.xml文件中添加以下权限:
在build.gradle中的android部分增加以下代码:
compileSdkVersion 31 buildToolsVersion "31.0.0" targetSdkVersion 31
并在代码中请求ACCESS_FINE_LOCATION权限:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION); }
同时保证应用已经打开蓝牙开关:
final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (!bluetoothAdapter.isEnabled()) { bluetoothAdapter.enable(); }
最后,使用以下代码扫描设备:
bluetoothAdapter.startDiscovery();