有没有办法,使用Android SDK,以编程方式连接到已配对的蓝牙设备?
换句话说:我可以进入设置 - >无线和网络 - >蓝牙设置,然后点击设备(列为“已配对但未连接”),此时它将连接 . 我希望能够以编程方式执行此操作,但是没有办法实现此目的 .
我看到了创建RFCOMM套接字的选项,对于SPP设备,我假设它也会做连接部分,但是对于A2DP设备,实际数据传输将由OS处理,而不是由我的应用程序,我认为这不适用?
好吧,因为这让我发疯,我做了一些挖掘源代码,我发布了一个完全可用的示例项目(使用Android Studio轻松构建),你可以找到here on Github .
基本上,您需要做的是:
获取 BluetoothAdapter 的实例
BluetoothAdapter
使用此实例,获取A2DP的配置文件代理:
adapter.getProfileProxy (context, listener, BluetoothProfile.A2DP);
其中 listener 是 ServiceListener ,它将在 onServiceConnected() 回调中接收 BluetoothProfile (可以强制转换为 BluetoothA2dp 实例)
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);
至少对我而言,这导致设备立即连接 .
我找到解决问题的最好方法是发现我可以创建一个按钮,显示蓝牙设置屏幕 . 我没有意识到你可以这样做,或者我从一开始就会这样做 .
startActivity(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
设备配对后,应用程序可以通过编程方式将两个设备连接在一起 .
4 回答
好吧,因为这让我发疯,我做了一些挖掘源代码,我发布了一个完全可用的示例项目(使用Android Studio轻松构建),你可以找到here on Github .
基本上,您需要做的是:
获取
BluetoothAdapter
的实例使用此实例,获取A2DP的配置文件代理:
adapter.getProfileProxy (context, listener, BluetoothProfile.A2DP);
其中
listener
是ServiceListener
,它将在onServiceConnected()
回调中接收BluetoothProfile
(可以强制转换为BluetoothA2dp
实例)connect(BluetoothDevice)
方法:Method connect = BluetoothA2dp.class.getDeclaredMethod("connect", BluetoothDevice.class);
BluetoothDevice
:connect()
方法:connect.invoke(proxy, result);
至少对我而言,这导致设备立即连接 .
我找到解决问题的最好方法是发现我可以创建一个按钮,显示蓝牙设置屏幕 . 我没有意识到你可以这样做,或者我从一开始就会这样做 .
如果设备已配对,则可以使用
用于MY_UUID使用
上面的代码段只是将您的设备连接到支持A2DP的设备 . 我希望它能奏效 .
我在这里使用代码作为我的应用程序中此功能的起点:http://developer.android.com/guide/topics/wireless/bluetooth.html#ConnectingDevices
设备配对后,应用程序可以通过编程方式将两个设备连接在一起 .