Android Question Detected if bluetooth headset is already connected

ddk1

Member
Licensed User
I have read and tested posts that use manifest and class to detect a bluetooth device being connected and disconnected, which work fine. But I want to know whether a bluetooth headset (A2DP profile) is connected when my app starts, without having to wait for a connect/disconnect.
I realise I could simply have the app be triggered on connect/disconnect, log the state, and exit again. Then when I manually run the app, I could read the last logged state, but thats rather klutzy. The app needs to know as it plays with volume at startup and that depends on whether a headset is connected. Futher I have several apps do the same.
To cut a long story short, it would be nice if my apps could simply query whether a headset is connected.
 

ddk1

Member
Licensed User
Constantly monitoring for state change isn't simple either as if I put
B4X:
AddReceiverText(BTconnect, <intent-filter>
    <action android:name="android.bluetooth.headset.profile.action.CONNECTION_STATE_CHANGED"/>
    </intent-filter>)
into the manifest, my watch and headset and car all trigger connects and disconnects so in theory I'd either have to log the state of each to know whether any one of them was connected when I want to know "is a headset connected", or predefine which one matters and only log that one.
I read that only one device can be A2DP connected at one time, but I haven't figured how to detect the A2DP profile of bluetooth yet.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Try this:
B4X:
Sub IsHeadsetConnected As Boolean
    Dim adapter As JavaObject
    adapter = adapter.InitializeStatic("android.bluetooth.BluetoothAdapter").RunMethod("getDefaultAdapter", Null)
    If adapter.IsInitialized Then
        Dim state As Int = adapter.RunMethod("getProfileConnectionState", Array(1)) 'BluetoothProfile.HEADSET
        Log("headset state: " & state)
        Return state = 2
    End If
    Return False
End Sub

Manifest editor:
B4X:
AddPermission(android.permission.BLUETOOTH)
 
Upvote 0

ddk1

Member
Licensed User
Thanks Erel, that's just the ticket. I changed it to Array(2) to check for an A2DP connection.
Very much appreciated.
 
Last edited:
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…