问题描述:

I am trying to connect to Bluetooth devices using Reflections using BluetoothProfile.

Here is my method to Connect/Disconnect a Bluetooth device:

public void actionOnBTDevice(String strAction, final BluetoothDevice device, BluetoothProfile profile) {

try {

Class<?> c2 = Class.forName("android.os.ServiceManager");

Method m2 = c2.getDeclaredMethod("getService", String.class);

IBinder b = (IBinder) m2.invoke(c2.newInstance(), "bluetooth_a2dp");

if (b == null) {

// For Android 4.2 Above Devices

try {

if(strAction.equalsIgnoreCase("CONNECT")) {

//a2dp.getClass().getMethod("connect", BluetoothDevice.class).invoke(a2dp, deviceToConnect);

profile.getClass().getMethod("connect", BluetoothDevice.class).invoke(profile, device);

}

else if(strAction.equalsIgnoreCase("DISCONNECT")) {

//a2dp.getClass().getMethod("disconnect", BluetoothDevice.class).invoke(a2dp,deviceToConnect);

profile.getClass().getMethod("disconnect", BluetoothDevice.class).invoke(profile, device);

}

}

catch (Exception e) {

e.printStackTrace();

}

}

else {

// For Android below 4.2 devices

// RUNS ONLY FOR A2DP

Class<?> c3 = Class.forName("android.bluetooth.IBluetoothA2dp");

Class<?>[] s2 = c3.getDeclaredClasses();

Class<?> c = s2[0];

Method m = c.getDeclaredMethod("asInterface", IBinder.class);

m.setAccessible(true);

IBluetoothA2dp a2dp = (IBluetoothA2dp) m.invoke(null, b);

if(strAction.equalsIgnoreCase("CONNECT")) {

a2dp.connect(device);

}

else if(strAction.equalsIgnoreCase("DISCONNECT")) {

a2dp.disconnect(device);

}

}

}

catch (Exception e) {

Log.i(TAG,e.toString());

}

}

I have referenced the above code from https://derivedcode.wordpress.com/2013/10/09/connecting-to-a-bluetooth-a2dp-device-from-android/

Here is my ServiceListener:

private class BluetoothProfileServiceListener implements BluetoothProfile.ServiceListener {

private final int[] states = { BluetoothProfile.STATE_CONNECTED,

BluetoothProfile.STATE_CONNECTING};

@Override

public void onServiceConnected(int profile, BluetoothProfile bluetoothProfile) {

if(bluetoothProfile instanceof BluetoothA2dp) {

a2dp = (BluetoothA2dp) bluetoothProfile;

connectedA2DPDevices = bluetoothProfile.getDevicesMatchingConnectionStates(states);

}

else if(bluetoothProfile instanceof BluetoothHeadset) {

hs = (BluetoothHeadset) bluetoothProfile;

connectedHSDevices = bluetoothProfile.getDevicesMatchingConnectionStates(states);

}

}

@Override

public void onServiceDisconnected(int profile) {}

}

My code works fine when I try to connect to an A2DP device from my Nexus 6P (Nougat - API24). It also worked on Android Marshmallow - API23.

But the same doesn't work from Lenovo k50a40 (Android Lollipop - API21).

I have 2 questions:

  1. Is this the correct way to connect/disconnect device ?
  2. Are there separate connect/disconnect methods for different profiles (Ex: A2DP, Headset, etc.) ?

相关阅读:
Top