androidandroid-bluetootha2dp

Android: How to detect which Bluetooth device is currently getting audio stream?


I'm getting a list of A2DP devices like this:

bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter.getProfileProxy(context, new BluetoothProfile.ServiceListener() {

    @Override
    public void onServiceConnected(int profile, BluetoothProfile proxy) {
        List<BluetoothDevice> devices = proxy.getConnectedDevices();
    }

    @Override
    public void onServiceDisconnected(int profile) {

    }
}, BluetoothProfile.A2DP);

The problem is that sometimes, when I have more than one device connected, only one of them is getting the audio stream from my app. How can I know which device is the one getting the stream? Also I've heard that in newer Android versions you can be connected to a Bluetooth device but still playing audio in the phone itself, is there a way to know when this happens as well?


Solution

  • I finally found a solution.

        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        bluetoothAdapter.getProfileProxy(context, new BluetoothProfile.ServiceListener() {
    
        @Override
        public void onServiceConnected(int profile, BluetoothProfile proxy) {
            List<BluetoothDevice> devices = proxy.getConnectedDevices();
            BluetoothA2dp bA2dp = (BluetoothA2dp) proxy;
            for (BluetoothDevice device: devices) { 
                boolean isPlaying = bA2dp.isA2dpPlaying(device);
            }
        }
    
        @Override
        public void onServiceDisconnected(int profile) {
    
        }
    }, BluetoothProfile.A2DP);