Ответ 1
Недавно у меня возникла аналогичная проблема, пытаясь подключить Bluetooth-устройство к телефону Android. Хотя ваш профиль устройства отличается, я думаю, что решение одинаков.
Сначала вам нужно создать пакет в проекте с именем android.bluetooth
и разместить там IBluetoothA2dp.aidl:
package android.bluetooth;
import android.bluetooth.BluetoothDevice;
/**
* System private API for Bluetooth A2DP service
*
* {@hide}
*/
interface IBluetoothA2dp {
boolean connectSink(in BluetoothDevice device);
boolean disconnectSink(in BluetoothDevice device);
boolean suspendSink(in BluetoothDevice device);
boolean resumeSink(in BluetoothDevice device);
BluetoothDevice[] getConnectedSinks();
BluetoothDevice[] getNonDisconnectedSinks();
int getSinkState(in BluetoothDevice device);
boolean setSinkPriority(in BluetoothDevice device, int priority);
int getSinkPriority(in BluetoothDevice device);
boolean connectSinkInternal(in BluetoothDevice device);
boolean disconnectSinkInternal(in BluetoothDevice device);
}
Затем, чтобы получить доступ к этим функциям, поместите в свой проект следующий класс:
public class BluetoothA2dpConnection {
private IBluetoothA2dp mService = null;
public BluetoothA2dpConnection() {
try {
Class<?> classServiceManager = Class.forName("android.os.ServiceManager");
Method methodGetService = classServiceManager.getMethod("getService", String.class);
IBinder binder = (IBinder) methodGetService.invoke(null, "bluetooth_a2dp");
mService = IBluetoothA2dp.Stub.asInterface(binder);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
public boolean connect(BluetoothDevice device) {
if (mService == null || device == null) {
return false;
}
try {
mService.connectSink(device);
} catch (RemoteException e) {
e.printStackTrace();
return false;
}
return true;
}
public boolean disconnect(BluetoothDevice device) {
if (mService == null || device == null) {
return false;
}
try {
mService.disconnectSink(device);
} catch (RemoteException e) {
e.printStackTrace();
return false;
}
return true;
}
}
Наконец, чтобы подключить устройство A2dp, выберите один BluetoothDevice из списка сопряженных устройств и отправьте его как параметр метода connect
. Обязательно выберите устройство с правильным профилем, иначе у вас будет исключение.
Я тестировал это решение в телефоне с версией 2.3 и Android, и он работал нормально.
Извините, какая-либо ошибка на английском языке. Надеюсь, это поможет вам.