mardi 3 juillet 2018

Disconnect from an active A2dpSink Profile Bluetooth connection - Android

My custom Android device is using the A2dpSink profile for the Bluetooth connection. I have been trying to find ways on how to disconnect from a connected device programatically (without disabling Bluetooth) and feel that i am close to doing that using reflection since the BluetoothA2dpSink class is hidden in the Android system.

Here is my implementation

Class<?> a2dpSink = Class.forName("android.bluetooth.BluetoothA2dpSink");
a2dpSink.cast(a2dpProfile); 
//a2dpProfile is object obtained from bluetoothAdapter.getProfileProxy(...)

Method method = a2dpSink.getMethod("disconnect", BluetoothDevice.class);
method.invoke(a2dpSink, connectedDevice);

However, I get this exception ->

W/System.err: java.lang.IllegalArgumentException: 
Expected receiver of type android.bluetooth.BluetoothA2dpSink, but got java.lang.Class<android.bluetooth.BluetoothA2dpSink>
        at java.lang.reflect.Method.invoke(Native Method)

how i get the a2dpProfile object

private BluetoothProfile.ServiceListener serviceListener = new BluetoothProfile.ServiceListener() {
        @Override
        public void onServiceDisconnected(int profile) {
            sendBroadcast(new Intent(Constants.INTENT_BLUETOOTH_DISCONNECTED));
            ToastDialogHelper.makeText(String.format(getString(R.string.bluetooth_disconnected_toast), bluetoothConnectedDevice.getName()), Toast.LENGTH_LONG).show();
            mBtAdapter.closeProfileProxy(profile, a2dpProfile);
            bluetoothConnectedDevice = null;
            a2dpProfile = null;
        }

        @Override
        public void onServiceConnected(int profile, BluetoothProfile proxy) {
            a2dpProfile = proxy;

            for (BluetoothDevice device : proxy.getConnectedDevices()) {
                DebugLog.d("onServiceConnected", "|" + device.getName() + " | " + device.getAddress() + " | " + proxy.getConnectionState(device) + "(connected = "
                        + BluetoothProfile.STATE_CONNECTED + ")");
                bluetoothConnectedDevice = device;
            }

            if (bluetoothConnectedDevice != null) {
                ToastDialogHelper.makeText(String.format(getString(R.string.bluetooth_connected_toast), bluetoothConnectedDevice.getName()), Toast.LENGTH_LONG).show();
            }
        }
    };


// profile 11 is for a2dp_sink
mBtAdapter.getProfileProxy(this, serviceListener, 11);





Aucun commentaire:

Enregistrer un commentaire