Android 对蓝牙配对对话框输入的反应
我正在开发一款通过蓝牙将android设备与其他设备(CAN模块)连接起来的应用程序 我将以前未配对的设备配对如下:Android 对蓝牙配对对话框输入的反应,android,bluetooth,Android,Bluetooth,我正在开发一款通过蓝牙将android设备与其他设备(CAN模块)连接起来的应用程序 我将以前未配对的设备配对如下: Method m = device.getClass().getMethod("createBond", (Class[]) null); m.invoke(device, (Object[]) null); 这就像一个符咒 不过有一个问题。CAN模块的设置方式使您不需要pin码或任何其他形式的配对确认,您只需说您想与设备配对,它就会这样做。现在,如果我的应用程序尝试连接到一个
Method m = device.getClass().getMethod("createBond", (Class[]) null);
m.invoke(device, (Object[]) null);
这就像一个符咒
不过有一个问题。CAN模块的设置方式使您不需要pin码或任何其他形式的配对确认,您只需说您想与设备配对,它就会这样做。现在,如果我的应用程序尝试连接到一个不是CAN模块的蓝牙设备,比如手机,会发生什么
在这种情况下,会出现一个对话框,要求用户确认配对。我不介意这个对话框,但我想以某种方式对“取消”按钮做出反应
总而言之:
当用户按下蓝牙配对确认对话框上的
Cancel
时,我想调用方法doSomething()
。这可能吗?我找到了一个解决方案
要响应用户取消配对请求的请求,我们需要查找以下操作:BluetoothDevice.action\u BOND\u STATE\u CHANGED
以及器件通过额外的键合状态的键合状态
下面是一个例子:
private void pairDevice(BluetoothDevice device){
try{
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
ctx.registerReceiver(receiver, filter);
Method m = device.getClass().getMethod("createBond", (Class[]) null);
m.invoke(device, (Object[]) null);
}catch(Exception e){
e.printStackTrace();
}
}
在你的收音机里
public void onReceive(Context context, Intent intent){
String action = intent.getAction();
if(action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED){
int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1);
if(state < 0){
//we should never get here
}
else if(state == BluetoothDevice.BOND_BONDING){
//bonding process is still working
//essentially this means that the Confirmation Dialog is still visible
}
else if(state == BluetoothDevice.BOND_BONDED){
//bonding process was successful
//also means that the user pressed OK on the Dialog
}
else if(state == BluetoothDevice.BOND_NONE){
//bonding process failed
//which also means that the user pressed CANCEL on the Dialog
doSomething(); //we can finally call the method
}
}
}
public void onReceive(上下文、意图){
String action=intent.getAction();
if(action.equals(BluetoothDevice.action\u BOND\u STATE\u CHANGED){
int state=intent.getIntExtra(BluetoothDevice.EXTRA\u BOND\u state,-1);
如果(状态<0){
//我们不应该到这里
}
else if(state==BluetoothDevice.BOND\u BONDING){
//粘合过程仍在进行中
//本质上这意味着确认对话框仍然可见
}
else if(state==BluetoothDevice.BOND\u BOND){
//粘接过程是成功的
//也意味着用户在对话框上按了OK
}
else if(state==BluetoothDevice.BOND\u NONE){
//粘合过程失败
//这也意味着用户在对话框上按了“取消”
doSomething();//我们终于可以调用该方法了
}
}
}
您应该倾听意图(我希望您知道如何注册广播接收器并使用它们)
上述操作由系统(BluetoothService)广播,它还包含当前绑定状态
和以前的绑定状态
有三种键态
BOND\u BOND表示远程设备已绑定(配对)
BOND\u BONDING表示正在与远程设备进行绑定(配对)
BOND_NONE表示远程设备未绑定(配对)
在您的情况下,如果密码对话框上有取消按钮,您将收到
BOND\u BONDING>>BOND\u NONE
,如果密码对话框上有结对按钮,您将收到BOND\u BONDING
非常好,我自己找到了,但这是一个很好的答案。@DodgerThud是的,我在下面看到了您的答案,很抱歉,我花了时间写了一个回答并提供链接,回答问题。有了BOND_NONE,我们是否能够区分用户何时按下cancel键,何时用户输入了错误的pin码或发生了其他故障?