首页 > 解决方案 > 搜索 BLE 设备时不会调用 onScanResult

问题描述

我正在尝试实现最简单的应用程序来扫描 BLE 设备。我已赋予必要的权利:

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

但是,onScanResult 永远不会被调用。我的手机上启用了蓝牙并且 BLE 设备已打开,这是我的代码:

class MainActivity : AppCompatActivity() {
private val bleScanner = object :ScanCallback() {
    override fun onScanResult(callbackType: Int, result: ScanResult) {
        Log.d("DeviceListActivity", "onScanResult()")
        super.onScanResult(callbackType, result)
        val device = result.device
        Log.d("DeviceScanner", "Device found: ${device.address} - ${device.name ?: "Unknown"}")
        //Log.d("DeviceListActivity","onScanResult: ${result.device?.address} - ${result.device?.name}")
    }
}

private val bluetoothLeScanner: BluetoothLeScanner
    get()  {
        val bluetoothManager = applicationContext.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
        val bluetoothAdapter: BluetoothAdapter = bluetoothManager.adapter
        return bluetoothAdapter.bluetoothLeScanner
    }

override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
    Log.d("DeviceListActivity", "onCreate()")
    super.onCreate(savedInstanceState, persistentState)
    setContentView(R.layout.activity_device_list)
}

override fun onStart() {
    Log.d("DeviceListActivity", "onStart()")
    super.onStart()

    enableLocation()
    bluetoothLeScanner.startScan(bleScanner)
}

override fun onStop() {
    Log.d("DeviceListActivity", "onStop()")
    bluetoothLeScanner.stopScan(bleScanner)
    super.onStop()
}

private fun enableLocation(): Boolean {
    val service = applicationContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
    val enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER)
    return enabled
}
}

我错过了什么?

标签: androidkotlinbluetooth-lowenergy

解决方案


是的,这是缺少请求的权限。我将以下函数插入 onResume()

    if (ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(
            this,
            arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
            0
        )
    } else {
        leDeviceScanner.start()
    }

它现在就像一个魅力。谢谢!


推荐阅读