在Android 10及以上版本中,Android Open Source项目中的.disconnect方法和BluetoothHeadsetClient类都被隐藏了,这个问题可以通过使用Java的反射机制来解决。以下是一个代码示例:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
public class MyBluetoothProfile implements BluetoothProfile {
private BluetoothHeadset mService;
private Method disconnectMethod;
public MyBluetoothProfile(BluetoothHeadset service) {
mService = service;
try {
disconnectMethod = mService.getClass().getMethod("disconnect",
BluetoothDevice.class);
} catch (NoSuchMethodException ex) {
ex.printStackTrace();
disconnectMethod = null;
}
}
// This method is hidden in Android 10, so we use reflection to call it
public boolean disconnect(BluetoothDevice device) {
if (disconnectMethod != null) {
try {
return (Boolean)disconnectMethod.invoke(mService, device);
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InvocationTargetException ex) {
ex.printStackTrace();
}
}
return false;
}
// Rest of the BluetoothProfile implementation goes here...
}