0

I'm working on a app that capable of checking all bluetooth device and need to display it on recyclerview on load of the app. Im using BroadcastReceiver for the searching of the devices. but apparently, the onReceive() method is not triggering.

I've already check this but still it doesnt work for me.

Please see my code below

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()
        }
    }
  }

Registering the receiver on 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()
    }

Listener that is implemented on my fragment

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()
    }
}

Manifest

<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>
FroyoDevourer
  • 129
  • 11

1 Answers1

0

Since you are registering for broadcasts that are system level broadcasts (broadcasts not local to your application), you need to register the BroadcastReceiver globally, not through the LocalBroadcastManager.

Use Context.registerReceiver() instead.

Submersed
  • 8,810
  • 2
  • 30
  • 38