[英]Android bluetooth: Paired devices list
我有一個帶SPP配置文件和藍牙版本2.1的藍牙設備。
我有一個連接到該設備並與之通信的應用程序。 該設備使用“Just Works”配對技術。
我在某些手機上遇到問題,如三星Galaxy平板電腦,Galaxy S.
問題是在用戶退出應用程序后,我正在關閉套接字並斷開與設備的連接。 成功斷開連接后,會發現設備的條目已從配對設備列表中刪除。
我沒有使用平板電腦,但我確實編寫了一個使用SPP for Android手機的應用程序。 我發現,為了使藍牙穩定,我必須手動綁定我想要與之通信的設備。 我們使用下面的代碼從應用程序中啟動綁定,它應該保留綁定,就像您通過設置菜單手動配對一樣。
以下是一般流程:1)注冊BroadcastReceiver以監聽BluetoothDevice.ACTION_BOND_STATE_CHANGED
2)設備發現后,您應該有一個BluetoothDevice對象。
3)使用反射在BluetoothDeviceObject上調用'createBond'方法
3a)在打開插座之前等待粘合狀態改變事件
BluetoothDevice device = {obtained from device discovery};
Method m = device.getClass().getMethod("createBond", (Class[])null);
m.invoke(device, (Object[])null);
int bondState = device.getBondState();
if (bondState == BluetoothDevice.BOND_NONE || bondState == BluetoothDevice.BOND_BONDING)
{
waitingForBonding = true; // Class variable used later in the broadcast receiver
// Also...I have the whole bluetooth session running on a thread. This was a key point for me. If the bond state is not BOND_BONDED, I wait here. Then see the snippets below
synchronized(this)
{
wait();
}
}
4)等待債券狀態從BOND_BONDING變為BOND_BONDED
在BroadcastReciever中:
public void onReceive(Context context, Intent intent)
{
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(intent.getAction()))
{
int prevBondState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, -1);
int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1);
if (waitingForBonding)
{
if (prevBondState == BluetoothDevice.BOND_BONDING)
{
// check for both BONDED and NONE here because in some error cases the bonding fails and we need to fail gracefully.
if (bondState == BluetoothDevice.BOND_BONDED || bondState == BluetoothDevice.BOND_NONE)
{
// safely notify your thread to continue
}
}
}
}
}
5)打開插座並進行通信
你也可以通過反射'removeBond'方法從配對列表中刪除你的設備。
希望這可以幫助!
如果由於您的應用程序連接而發生配對,我猜測某些設備會將其視為臨時配對,並且在斷開連接后不會將設備保留在配對列表中。 要將設備保留在配對列表中,您應手動配對藍牙設置菜單。 配對后,您的程序可以連接/斷開連接,設備將保留在配對列表中。
我也遇到了與索尼Xperia X10相同的問題。 我設法通過改變藍牙設備端的安全級別設置來“記住”配對(因為我也正在開發設備)。
我不確定“臨時配對”的解釋,這將取決於制造商,不同的是,不同的手機對同一設備的連接會有不同的反應。
然而,對我來說,這是一個無問題的部分。 通常,當用戶在后台連接應用程序時取消配對設備時,藍牙堆棧似乎會崩潰。 我還沒弄清楚如何正確管理ACTION_BOND_STATE_CHANGED事件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.