我正在开发一个能够检查所有蓝牙设备的应用程序,并且需要在加载应用程序时将其显示在回收器视图上。我使用
Broadcastreceiver
来搜索设备。但显然,onReceive()
方法没有触发。
我已经检查过this,但它仍然对我不起作用。
请参阅下面我的代码
广播接收器
class BluetoothBroadcastReceiver(private val listener: Listener) : BroadcastReceiver() {
constructor() : this(object : Listener {
override fun onBluetoothDeviceFound(device: BluetoothDevice) {}
override fun onGpsAction() {}
})
interface Listener {
fun onBluetoothDeviceFound(device: BluetoothDevice)
fun onGpsAction()
}
private val GPS_ACTION = "android.location.PROVIDERS_CHANGED"
override fun onReceive(context: Context, intent: Intent) {
val action = intent.action
if (BluetoothDevice.ACTION_FOUND == action) {
val btd = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
if (btd?.bondState != BluetoothDevice.BOND_BONDED) {
listener.onBluetoothDeviceFound(btd!!)
}
} else if (action == GPS_ACTION) {
listener.onGpsAction()
}
}
}
在
onResume()
上注册接收器
bluetoothBroadcastReceiver = BluetoothBroadcastReceiver(this)
val intentFilter = IntentFilter().apply {
addAction(BluetoothDevice.ACTION_FOUND)
addAction(GPS_ACTION)
}
try{
LocalBroadcastManager.getInstance(requireContext()).registerReceiver(bluetoothBroadcastReceiver,intentFilter)
Log.e("intent","register")
}catch(e: Throwable){
e.printStackTrace()
}
在我的片段上实现的监听器
override fun onBluetoothDeviceFound(device: BluetoothDevice) {
if (!deviceIsExist(device.address)) {
val name = device.name
datas.add(BluetoothDeviceDetails(name, device.address, false))
binding.rvPrinterSettingsList.adapter?.notifyItemChanged(datas.size - 1)
}
}
override fun onGpsAction() {
if (isGpsOpen()) {
setBluetooth()
}
}
由于您注册的广播是系统级广播(不是您的应用程序本地的广播),因此您需要全局注册
BroadcastReceiver
,而不是通过 LocalBroadcastManager
。
使用 Context.registerReceiver() 代替。