Android 4.2.1中找不到Android.bluetooth.IBluetooth.createBond()方法,但在早期的操作系统版本中可以使用。

10

我有一些代码,可以通过调用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;
}

1
我对这个问题非常感兴趣。如果您有任何消息,请分享给我 :p。 - castrogne
2个回答

6
在Android 4.2中,他们改变了蓝牙堆栈的实现方式。
"Android 4.2引入了一个新的蓝牙堆栈,专为与Android设备配合使用进行优化。这个由Google和Broadcom共同开发的新蓝牙堆栈取代了基于BlueZ的堆栈,并提供了更好的兼容性和可靠性。"
即使在Nexus 7上使用公共API,仍有许多与蓝牙相关的功能无法正常工作。

有人知道在哪里可以看到新的接口吗?我使用这个:http://grepcode.com/project/repository.grepcode.com/java/ext/com.google.android/android/,但它还没有4.2。 - jroal

2
 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 Galaxy Nexus上有效。虽然我还没有在Nexus 7上尝试过,但当我使用IBluetooth方法时也遇到了MethodNotFoundException的问题。因此,这个方法可能也适用于Nexus 7。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接