在4.2.1中找不到Android.bluetooth.IBluetooth.createBond(),但在早期的操作系



我有一些代码可以通过调用createBond(),为android.bluetooth.device.action.PAIRING_REQUEST注册广播接收器,然后手动输入要配对的PIN码来自动与蓝牙设备配对。

到目前为止,这在Andoid 4.0之前测试的所有设备上都很有效,但今天我在安卓4.2.1的Nexus 7上尝试了这一点,结果出现了以下错误:

java.lang.noSuchMethodException:android.bluetooth.IBluetooth.createBond

他们真的从库中删除了这个函数吗?

更新

实际发生的情况是,我用来调用createBond的IBluetooth接口对象没有初始化。在下面的代码中,当这个过程失败,导致BTInterface在末尾被设置为null时,试图获取名为BTBinder的IBinder的行返回null。所以,我现在的问题是,为什么在我的Nexus 7和Android 4.2.1上,获取绑定器的调用返回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;
}

在Android 4.2中,他们改变了蓝牙堆栈的实现。

"Android 4.2引入了一种新的蓝牙堆栈,该堆栈经过优化,可用于Android设备。谷歌和博通合作开发的新蓝牙堆栈取代了基于BlueZ的堆栈,并提高了的兼容性和可靠性。">

即使在Nexus 7上使用公共api,也有很多与bt相关的事情不起作用。

public boolean createBond(BluetoothDevice btDevice)  
throws Exception  
{ 
Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
Method createBondMethod = class1.getMethod("createBond");  
Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);  
return returnValue.booleanValue();  
}

这适用于4.2.1银河天枢。我还没有在Nexus 7上尝试过,但当我使用IBluetooth方法时,我遇到了同样的MethodNotFoundException问题。因此,它也可能修复Nexus 7。

最新更新