以编程方式连接到配对的蓝牙设备 [英] Programmatically connect to paired Bluetooth device

查看:55
本文介绍了以编程方式连接到配对的蓝牙设备的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法使用 Android SDK 以编程方式连接到已配对的蓝牙设备?

Is there a way, using the Android SDK, to programmatically connect to an already-paired Bluetooth device?

换句话说:我可以进入设置 -> 无线 &网络 -> 蓝牙设置,然后点击设备(列为已配对但未连接"),此时它将连接.我希望能够以编程方式执行此操作,但看不到执行此操作的方法.

In other words: I can go into Settings -> Wireless & networks -> Bluetooth settings, and tap the device (listed as "Paired but not connected"), at which point it will connect. I'd like to be able to do this programmatically, but don't see a way to do this.

我看到了创建 RFCOMM 套接字的选项,对于 SPP 设备,我假设它也会执行连接部分,但对于 A2DP 设备,实际数据传输将由操作系统处理而不是我的应用程序,我认为这不适用?

I see the options to create an RFCOMM socket, and for a SPP device, I'm assuming that'll do the connection part as well, but for an A2DP device, where the actual data transfer will be handled by the OS rather than by my app, I think that's not applicable?

推荐答案

好吧,既然这让我发疯,我对源代码进行了一些挖掘,发现 100% 可靠(至少在我的 Nexus 4 上), Android 4.3) 解决方案连接到已配对的 A2DP 设备(如耳机或蓝牙音频设备).我已经发布了一个完整的示例项目(很容易用 Android Studio 构建),你可以在在 Github 上找到.

Okay, since this was driving me crazy, I did some digging into the source code and I've found a 100% reliable (at least on my Nexus 4, Android 4.3) solution to connect to a paired A2DP device (such as a headset or Bluetooth audio device). I've published a fully working sample project (easily built with Android Studio) that you can find here on Github.

本质上,您需要做的是:

Essentially, what you need to do is:

  • 获取BluetoothAdapter
  • 的一个实例
  • 使用此实例,获取 A2DP 的配置文件代理:

adapter.getProfileProxy (context, listener, BluetoothProfile.A2DP);

其中 listener 是一个 ServiceListener,它将在其 onServiceConnected() 回调中接收一个 BluetoothProfile(它可以被转换为 BluetoothA2dp 实例)

where listener is a ServiceListener that will receive a BluetoothProfile in its onServiceConnected() callback (which can be cast to a BluetoothA2dp instance)

  • 使用反射获取代理上的connect(BluetoothDevice)方法:

Method connect = BluetoothA2dp.class.getDeclaredMethod("connect", BluetoothDevice.class);

  • 找到您的BluetoothDevice:
String deviceName = "My_Device_Name";

BluetoothDevice result = null;

Set<BluetoothDevice> devices = adapter.getBondedDevices();
if (devices != null) {
    for (BluetoothDevice device : devices) {
        if (deviceName.equals(device.getName())) {
            result = device;
            break;
        }
    }
}

<小时>

  • 并调用 connect() 方法:
  • connect.invoke(proxy, result);

    至少对我来说,这导致了设备的立即连接.

    Which, at least for me, caused an immediate connection of the device.

    这篇关于以编程方式连接到配对的蓝牙设备的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆