安卓官方文档建议使用的是BluetoothAdapter.LeScanCallBack,但目前的SDK版本已经不建议使用这种方法,而是支持使用BluetoothAdapter.getDefaultAdapter.BluetoothLeScanner。然而更换之后仍然发现蓝牙不扫描且log中看不到有用的信息,这是因为应用没有获取位置权限,而google目前规定蓝牙扫描的使用必须需要位置权限。
解决方法:
在manifest.xml中加入
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-feature
android:name="android.hardware.bluetooth_le"
android:required="true" />
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val hasLocationPermission = checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
if (hasLocationPermission != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION),
LOCATION_PERMISSION)
}
}else{}
或者你可以手动到应用程序那里为手机申请权限,来判断是否是权限的问题。