0

Im implementing a simple blutooth classic scan from the official docs on my Redmi Note 4 (Bluetooth 4.1).

However I am not seeing a toast that should appear when the onReceive function on the broadcast receiver is called.

What could be wrong here?


class MainActivity : AppCompatActivity() {

 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        defaultAdapter = BluetoothAdapter.getDefaultAdapter()
        if (defaultAdapter == null) {
            toast("no adapter")
            return
        }
        if (!defaultAdapter!!.isEnabled) {
            val enableBluetoothIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            startActivityForResult(enableBluetoothIntent, REQUEST_ENABLE_BLUETOOTH)
        }
        searchButton.setOnClickListener { newDevicesList() }

        val filter = IntentFilter(BluetoothDevice.ACTION_FOUND)
        Log.i("receiver", "registering receiver")
        registerReceiver(receiver, filter)

    }

private val receiver = object : BroadcastReceiver() {

        override fun onReceive(context: Context, intent: Intent) {
            toast("maybe i find new device who know")
            when (intent.action) {
                BluetoothDevice.ACTION_FOUND -> {
                    // Discovery has found a device. Get the BluetoothDevice
                    // object and its info from the Intent.
                    val device: BluetoothDevice? =
                            intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
                    val deviceName = device?.name
                    val deviceHardwareAddress = device?.address // MAC address
                    toast("device $deviceName was found")
                }
                BluetoothAdapter.ACTION_DISCOVERY_FINISHED -> {
                    context.unregisterReceiver(this)
                }
            }

        if (defaultAdapter!!.isDiscovering) {
            toast("scan already in progress")
        } else {
            toast("starting discovery")
            defaultAdapter!!.startDiscovery();
        }
    }

How do i know that the onReceive function never gets called? cause this toast toast("maybe i find new device who know") never appears.

BEvo
  • 357
  • 6
  • 18
  • Are you sure that the other devices that you are looking for are in discoverable mode? – Reaz Murshed Apr 21 '20 at 16:16
  • I would recommend seeing my answer here - https://stackoverflow.com/q/35239880/3145960 – Reaz Murshed Apr 21 '20 at 16:17
  • 1
    Thankyou for the comment, and the detailed post on the link. My problem was a bit different. It is now solved, and I'll update the answet ASAP. – BEvo Apr 21 '20 at 16:25

0 Answers0