有没有一种使用Android SDK的方法可以以编程方式连接已配对的蓝牙设备?
换句话说:我可以进入"设置"->"无线和网络"->"蓝牙设置",然后点击设备(列为“已配对但未连接”),此时它将连接。我希望能够以编程方式执行此操作,但看不到任何方法。
我看到创建RFCOMM套接字的选项,对于SPP设备,我认为那也会处理连接部分,但对于A2DP设备,实际数据传输将由操作系统而非我的应用程序处理,因此我认为这不适用?
好的,由于这件事让我抓狂了,我研究了一下源代码,并找到了一种100%可靠(至少在我的Nexus 4,Android 4.3上)连接到已配对的A2DP设备(例如耳机或蓝牙音频设备)的解决方案。我发布了一个完全可用的示例项目(使用Android Studio轻松构建),您可以在Github上找到。
基本上,你需要做的是:
BluetoothAdapter
的实例adapter.getProfileProxy (context, listener, BluetoothProfile.A2DP);
其中listener
是一个ServiceListener
,将在其onServiceConnected()
回调中接收BluetoothProfile
(可以转换为BluetoothA2dp
实例)
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);
对我来说,这至少立即连接了设备。
BluetoothHeadset
类以及一个 BluetoothProfile.HEADSET
常量。使用这些的更改应该是相当微不足道的。 - Kevin CoppockstartActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
if(device.getBondState()==device.BOND_BONDED){
Log.d(TAG,device.getName());
//BluetoothSocket mSocket=null;
try {
mSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e1) {
// TODO Auto-generated catch block
Log.d(TAG,"socket not created");
e1.printStackTrace();
}
try{
mSocket.connect();
}
catch(IOException e){
try {
mSocket.close();
Log.d(TAG,"Cannot connect");
} catch (IOException e1) {
Log.d(TAG,"Socket not closed");
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
使用MY_UUID
private static final UUID MY_UUID = UUID.fromString("0000110E-0000-1000-8000-00805F9B34FB");
以上代码片段仅用于将您的设备连接到支持A2DP的设备。希望它能够正常工作。
我在我的应用程序中使用这里的代码作为此功能的起点:http://developer.android.com/guide/topics/wireless/bluetooth.html#ConnectingDevices
一旦设备配对成功,应用程序在编程上连接两个设备没有问题。