[英]Reaction to Bluetooth Pairing dialog input
我正在使用通過藍牙將android設備與另一設備(CAN模塊)連接的應用程序。
我將以前未配對的設備配對如下:
Method m = device.getClass().getMethod("createBond", (Class[]) null);
m.invoke(device, (Object[]) null);
就像一個魅力。
不過有一個問題。 CAN模塊的設置方式不需要引腳,也不需要任何其他形式的配對確認,您只需要說要與設備配對就可以了。 現在,如果我的應用程序嘗試連接到非CAN模塊的藍牙設備(例如電話),會發生什么?
在這種情況下,將出現一個對話框,要求用戶確認配對。 我不在乎對話框,但是我想以某種方式對“取消”按鈕做出反應。
總結一下:當用戶在“藍牙配對確認”對話框上按“ Cancel
時,我想調用doSomething()
方法。 這可能嗎?
您應該聽ACTION_BOND_STATE_CHANGED Intent(希望您知道如何注冊BroadcastReceiver並使用它們)。
在由system(BluetoothService)廣播的動作之上,它還包含Current Bond State
和Previous Bond State
。
有三個邦聯國。
BOND_BONDED指示遠程設備已綁定(配對)。
BOND_BONDING表示正在與遠程設備進行綁定(配對)。
BOND_NONE指示遠程設備未綁定(配對)。
在您的情況下,如果在PassKey對話框上BOND_BONDING >> BOND_BONDED
取消”按鈕,您將收到BOND_BONDING >> BOND_NONE
;如果在PassKey對話框上使用“配對”按鈕,您將收到BOND_BONDING >> BOND_NONE
我找到了這個問題的解決方案/解決方法。
要對用戶取消配對請求做出反應,我們需要尋找以下操作:BluetoothDevice.ACTION_BOND_STATE_CHANGED和設備通過EXTRA_BOND_STATE的綁定狀態
這是一個例子:
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();
}
}
在您的BroadcastReceiver中
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
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.