Android Fragments BroadcastReceiver onReceive()不适用于使用KotlinMVVM结构的片段

5jvtdoz2  于 2023-10-19  发布在  Android
关注(0)|答案(1)|浏览(134)

我正在研究一个应用程序,能够检查所有蓝牙设备,并需要在应用程序的加载上显示它的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>
kzmpq1sx

kzmpq1sx1#

由于您要注册的广播是系统级广播(不是应用程序本地的广播),因此需要全局注册BroadcastReceiver,而不是通过LocalBroadcastManager
使用Context.registerReceiver()。

相关问题