android - 搜索 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
}
}
我错过了什么?
解决方案
是的,这是缺少请求的权限。我将以下函数插入 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()
}
它现在就像一个魅力。谢谢!
推荐阅读
- python - 删除列表中与其他列表中的匹配项相对应的每个项目
- c# - 如何将文件夹中所有文件的文件名、大小和最后修改的文件信息获取到gridview中?
- mysql - 在 mysql 中使用连接插入查询
- kubernetes - 通过查找 Ingress URL 访问 POD 的 IP 地址
- python - 如何在 Python 的密码学模块中访问私有 RSA 密钥的组件?
- python-3.x - 为什么出现 Unbound Local 错误,我希望 NameError 应该在哪里引发?
- c++ - 将设置传递给模板化函数
- python - Keras 2.2.4 fit_generator 问题。值错误,向输入层输入值时出现问题
- html - 在浏览器中加载功能不会加载资源
- mysql - SQL Workbench 中的数据库设计