In Android, how to get the profile of a connected bluetooth device?

后端 未结 2 813
故里飘歌
故里飘歌 2020-12-19 00:57

Following a lot of answers here, I am able to build the list of connected bluetooth devices with the help of a BroadcastReceiver. Now my question is how do I kn

2条回答
  •  情话喂你
    2020-12-19 01:50

    Looking at the Android source code, you can guess which profiles are available for a device by looking at its UUIDs, and then connect each profile one by one.

    Step 0 : Copy the _PROFILE_UUIDS constants from there : https://android.googlesource.com/platform/packages/apps/Settings/+/9ad703cdb9a8d0972c123b041d18aa7bbeb391a4/src/com/android/settings/bluetooth/LocalBluetoothProfileManager.java

    Step 1 : get your BluetoothDevice, via scanning for instance. Assure that it's properly bonded.

    Step 2 : register a BroadcastReceiver for the android.bluetooth.BluetoothDevice.ACTION_UUID action intent

    Step 3 : on your device, call the fetchUuidsWithSdp method

    Step 4 : you will recieve a ACTION_UUID broadcast : in the onReceive method you can unregister the receiver, and get the list of profiles like so :

    ArrayList profiles = new ArrayList<>();
    
    ParcelUuid[] uuids = device.getUuids();
    
    if (BluetoothUuid.containsAnyUuid(uuids, HEADSET_PROFILE_UUIDS))
    {
        profiles.add(BluetoothProfile.HEADSET);
    }
    
    if (BluetoothUuid.containsAnyUuid(uuids, A2DP_PROFILE_UUIDS))
    {
        profiles.add(BluetoothProfile.A2DP);
    }
    
    if (BluetoothUuid.containsAnyUuid(uuids, OPP_PROFILE_UUIDS))
    {
        //OPP doesn't have any BluetoothProfile value
    }
    
    if (BluetoothUuid.containsAnyUuid(uuids, HID_PROFILE_UUIDS))
    {
        //You will need system privileges in order to use this one
        profiles.add(BluetoothProfile.INPUT_DEVICE);
    }
    
    if (BluetoothUuid.containsAnyUuid(uuids, PANU_PROFILE_UUIDS))
    {
        profiles.add(BluetoothProfile.PAN);
    }
    

    Step 5 : get the proxies for the profiles, one by one :

    for (int profile : profiles)
    {
        if (!adapter.getProfileProxy(context, listener, profile))
        {
            //Do something
        }
    }
    

    Step 6 : do anything with each proxy retrieved in the onServiceConnected method of your listener. You can access the connect method using relfection.

提交回复
热议问题