我正在研究一个应用程序,能够检查所有蓝牙设备,并需要在应用程序的加载上显示它的Clerview。我使用BroadcastReceiver
搜索设备。但显然onReceive()
方法没有触发。
我已经检查了this,但它仍然不适合我。
请看下面的代码
BroadcastReceiver
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()
}
}
清单
<receiver
android:name=".broadcastreceiver.BluetoothBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.bluetooth.device.action.FOUND" />
<action android:name="android.location.PROVIDERS_CHANGED"/>
</intent-filter>
</receiver>
1条答案
按热度按时间kzmpq1sx1#
由于您要注册的广播是系统级广播(不是应用程序本地的广播),因此需要全局注册
BroadcastReceiver
,而不是通过LocalBroadcastManager
。使用Context.registerReceiver()。