以编程方式连接到已配对的蓝牙设备 [英] Programmatically connect to paired Bluetooth device
问题描述
有没有一种方法,使用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?
推荐答案
好了,因为这是推动我疯了,我做了一些挖到源$ C $ C,我已经找到了一个100%可靠的(至少在我的Nexus 4,机器人4.3)溶液到连接配对A2DP装置(诸如耳机或蓝牙音频设备)。我已经发布了一个有效的样本项目(易建成与Android工作室),你可以找到 在这里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:
- Get an instance of the
BluetoothAdapter
- Using this instance, get a profile proxy for A2DP:
adapter.getProfileProxy(背景下,监听器,BluetoothProfile.A2DP);
其中,监听器
是的ServiceListener
将获得 BluetoothProfile
在 onServiceConnected()
回调(可转换为 BluetoothA2dp
实例)
where listener
is a ServiceListener
that will receive a BluetoothProfile
in its onServiceConnected()
callback (which can be cast to a BluetoothA2dp
instance)
- 使用反射来获取
连接(BluetoothDevice类)
上的代理方法:
- Use reflection to acquire the
connect(BluetoothDevice)
method on the proxy:
方法连接= BluetoothA2dp.class.getDeclaredMethod(连接,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;
}
}
}
- 并调用
连接()
方法: - And invoke the
connect()
method:
connect.invoke(代理,结果);
其中,至少对我来说,造成该设备的直接连接。
Which, at least for me, caused an immediate connection of the device.
这篇关于以编程方式连接到已配对的蓝牙设备的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!