3

I am working on A2DP connection with headset and other Bluetooth device but when I connect Bluetooth device but when I Disconnect but It didn't disconnect with it. My code is:

try {    
    Method connect = mA2dpService.getClass().getDeclaredMethod("disconnect", BluetoothDevice.class);
    connect.invoke(device);
} catch (Exception e) {
     e.printStackTrace();
}
Andrii Omelchenko
  • 13,183
  • 12
  • 43
  • 79
Bhavinkumar Patel
  • 515
  • 1
  • 12
  • 28

2 Answers2

3

Finally I found

Call getProfileProxy to get a2dp proxy

adapter.getProfileProxy(c, listner, BluetoothProfile.A2DP);

listenr should implement onA2DPProxyReceived.

Then Callback onA2DPProxyReceived will be called.

public void onA2DPProxyReceived (BluetoothA2dp proxy) {
    Method disconnect = null;
    try {
        disconnect = BluetoothA2dp.class.getDeclaredMethod("disconnect", BluetoothDevice.class);
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }
    BluetoothDevice device = findBondedDeviceByName(mBtAdapter, myDevice);
    disconnect.setAccessible(true);
    try {
        int result = disconnect.invoke(proxy,device);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
}

Refer to sites below

SJ.Je
  • 51
  • 1
  • 7
0

kotlin

   private fun disconnect(device: BluetoothDevice) {
    val serviceListener: BluetoothProfile.ServiceListener = object :
        BluetoothProfile.ServiceListener {
        override fun onServiceDisconnected(profile: Int) {}

        @SuppressLint("DiscouragedPrivateApi")
        override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
            val disconnect = BluetoothA2dp::class.java.getDeclaredMethod(
                "disconnect",
                BluetoothDevice::class.java
            )
            disconnect.isAccessible = true
            disconnect.invoke(proxy, device)
            BluetoothAdapter.getDefaultAdapter().closeProfileProxy(profile, proxy)
        }
    }
    BluetoothAdapter.getDefaultAdapter()
        .getProfileProxy(mContext, serviceListener, BluetoothProfile.A2DP)
}

(tested on android 10) reference