
在我的应用程序中,我需要配对蓝牙设备并立即与它连接.
我有以下功能,以配对设备:
public boolean createBond(BluetoothDevice btDevice){ try { Log.d("pairDevice()","Start Pairing..."); Method m = btDevice.getClass().getmethod("createBond",(Class[]) null); Boolean returnValue = (Boolean) m.invoke(btDevice,(Object[]) null); Log.d("pairDevice()","Pairing finished."); return returnValue; } catch (Exception e) { Log.e("pairDevice()",e.getMessage()); } return false;}我用它如下:
Boolean isBonded = false;try { isBonded = createBond(bdDevice); if(isBonded) { //Connect with device }}它显示了配对设备和输入引脚的对话框.
问题是createBond函数总是返回true,它一直等到我输入引脚并与设备配对,所以我没有正确使用:
isBonded = createBond(bdDevice);if(isBonded) {...}所以问题是我如何与设备配对以及何时配对连接?
P.D我的代码基于以下主题的第一个答案:Android + Pair devices via bluetooth programmatically最佳答案我找到了解决方案.
首先,我需要一个broadcastReceiver,如:
private broadcastReceiver myReceiver = new broadcastReceiver() { @OverrIDe public voID onReceive(Context context,Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (device.getBondState() == BluetoothDevice.BOND_BONDED) { // CONNECT } } else if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // discover new device } }};然后我需要注册接收器如下:
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);context.registerReceiver(myReceiver,intentFilter);通过这种方式,接收器正在侦听ACTION_FOUND(发现新设备)和ACTION_BOND_STATE_CHANGED(设备更改其绑定状态),然后我检查新状态是否为BOND_BOUNDED以及它是否与设备连接.
现在当我调用createBond方法(在问题中描述)并输入引脚时,ACTION_BOND_STATE_CHANGED将触发,而device.getBondState()== BluetoothDevice.BOND_BONDED将为True并且它将连接.
总结以上是内存溢出为你收集整理的以编程方式配对后,Android会自动连接蓝牙设备全部内容,希望文章能够帮你解决以编程方式配对后,Android会自动连接蓝牙设备所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)