我有一些代码,可以通过调用createBond()、注册用于android.bluetooth.device.action.PAIRING_REQUEST的广播接收器,然后手动输入PIN码来自动配对蓝牙设备。
到目前为止,这在所有测试过的设备上都非常有效,但今天我在搭载Android 4.2.1的Nexus 7上尝试了一下,结果出现了以下错误:
java.lang.noSuchMethodException: android.bluetooth.IBluetooth.createBond
他们实际上已经从库中删除了这个功能吗?
更新
实际上正在发生的是,我用于调用createBond的IBluetooth接口对象没有被初始化。在以下代码中,当此过程失败时,尝试获取名为BTBinder的IBinder的行返回null,导致在最后将BTInterface设置为null。所以,我现在的问题是,为什么在我的Android 4.2.1的Nexus 7上调用获取binder的命令返回null,但在我测试过的其他5个设备上正常工作?
public static IBluetooth getBluetoothInterface()
{
//Gets a bluetooth interface from private Android system API
IBluetooth BTInterface = null;
try
{
Class<?> ServiceManager = Class.forName("android.os.ServiceManager");
Method getService = ServiceManager.getDeclaredMethod("getService", String.class);
IBinder BTBinder = (IBinder) getService.invoke(null, "bluetooth");
Class<?> IBluetooth = Class.forName("android.bluetooth.IBluetooth");
Class<?>[] IBluetoothClasses = IBluetooth.getDeclaredClasses();
Class<?> IBluetoothClass0 = IBluetoothClasses[0];
Method asInterface = IBluetoothClass0.getDeclaredMethod("asInterface",IBinder.class);
asInterface.setAccessible(true);
BTInterface = (IBluetooth) asInterface.invoke(null, BTBinder);
}
catch (Exception e)
{
return null;
}
return BTInterface;
}