安卓官方文檔建議使用的是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{}
或者你可以手動到應用程序那裏爲手機申請權限,來判斷是否是權限的問題。