3


我需要通过简单的按下按钮来连接定义的 BT 设备。
要求是用户不应像使用标准套接字方法那样收到任何通知对话框。
在我的项目中,我使用了这个解决方案。接下来是代码:

/**
 * Return system service to work with A2DP
 *
 * @return bluetooth interface
 */
private static IBluetoothA2dp getIBluetoothA2dp() {
    IBluetoothA2dp ibta = null;
    try {
        final Class serviceManager = Class.forName("android.os.ServiceManager");
        final Method getService = serviceManager.getDeclaredMethod("getService", String.class);
        final IBinder iBinder = (IBinder) getService.invoke(null, "bluetooth_a2dp");
        final Class iBluetoothA2dp = Class.forName("android.bluetooth.IBluetoothA2dp");
        final Class[] declaredClasses = iBluetoothA2dp.getDeclaredClasses();
        final Class c = declaredClasses[0];
        final Method asInterface = c.getDeclaredMethod("asInterface", IBinder.class);

        asInterface.setAccessible(true);
        ibta = (IBluetoothA2dp) asInterface.invoke(null, iBinder);
    } catch (final Exception e) {
        Log.e("Error " + e.getMessage());
    }
    return ibta;
}

在我在 Android 4.2 上启动我的应用程序之前,它运行良好。现在我无法获得 IBluetoothA2dp 接口,因为 getService() 方法没有返回带有“bluetooth_a2dp”键的 IBinder。

有人能帮我吗?

提前致谢!

4

2 回答 2

1

终于在4.2上运行了。在此处查看详细信息:http ://code.google.com/p/a2dp-connect2/

它与 4.1 及之前的版本完全不同。

首先调用 connect 到这样的接口:

    public static void getIBluetoothA2dp(Context context) {

    Intent i = new Intent(IBluetoothA2dp.class.getName());

    if (context.bindService(i, mConnection, Context.BIND_AUTO_CREATE)) {

    } else {
        // Log.e(TAG, "Could not bind to Bluetooth A2DP Service");
    }

}

当接口返回时,它会回调这个:

    public static ServiceConnection mConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {

        ibta2 = IBluetoothA2dp.Stub.asInterface(service);
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        // TODO Auto-generated method stub

    }

};

上面的ibta2是IBluetoothA2dp接口。

在相关的说明中,IBluetooth 界面也发生了变化。我使用它来获取设备别名(用户可以编辑的别名)。这个 getRemoteAlias() 函数之前需要 mac 地址。现在它需要一个蓝牙设备。

请记住,使用这些隐藏的界面是有风险的,因为它们可以而且经常会随着新的 Android 版本而改变。我已经被它咬了好几次了。你真的需要保持领先。

于 2013-04-14T20:25:56.443 回答
0

如果有人需要与自动配对相关的问题的答案,可以在这里查看我的答案。 https://stackoverflow.com/a/30362554/3920157

于 2015-05-21T00:28:17.817 回答