Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12111

Detect bluetooth pairing on Android

$
0
0

I am trying to make a feature that detects if your phone has connected to another device via Bluetooth, be it headphones, a car, another phone, etc. And if a device is detected there should be a response.

I have made a separate Bluetooth receiver class that checks for BluetoothDevice.ACTION_ACL_CONNECTED and based on that I should receive a message in the logs, though I do not. All the needed permissions are included, the receiver class is properly initiated in the MainActivity, and yet no response. What could be the issue?

class BluetoothReceiver(    private val onBluetoothConnected: () -> Unit,    private val onBluetoothDisconnected: () -> Unit,) : BroadcastReceiver() {    override fun onReceive(context: Context, intent: Intent) {        Log.d("BluetoothReceiver", "Received intent: ${intent.action}")        when (intent.action) {            BluetoothDevice.ACTION_ACL_CONNECTED -> {                Log.d("BluetoothReceiver", "Bluetooth device connected")                onBluetoothConnected()            }            BluetoothDevice.ACTION_ACL_DISCONNECTED -> {                Log.d("BluetoothReceiver", "Bluetooth device disconnected")                onBluetoothDisconnected()            }        }    }}

And this is how I handle it in my main activity;

override fun onStart() {    super.onStart()    val filter = IntentFilter().apply {        addAction(BluetoothDevice.ACTION_ACL_CONNECTED)        addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED)    }    registerReceiver(bluetoothReceiver, filter)}override fun onStop() {    super.onStop()    unregisterReceiver(bluetoothReceiver)}private fun setupBluetoothReceiver(): BluetoothReceiver {    return BluetoothReceiver(        onBluetoothConnected = { toggleSilentMode(true) },        onBluetoothDisconnected = { toggleSilentMode(false) }    )}

For context toggleSilentMode is a method that enables DND on the smartphone and does some other visual changes.


Viewing all articles
Browse latest Browse all 12111

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>