android检测蓝牙设备连接不上,Android检查设备连接状态
遇到一個檢查藍(lán)牙設(shè)備連接狀態(tài)問題,困擾許久。在網(wǎng)上查詢良久,嘗試了多種方案,也沒有很好的解決,最終經(jīng)“高人指點(diǎn)”,小有所獲,在此小記。
網(wǎng)上查詢的主要方法為以下兩種:
1.getProfileConnectionState()
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
int state = adapter .getProfileConnectionState(int profile)
調(diào)用BluetoothAdapter 中的,getProfileConnectionState()方法通過檢查是否有使用 HEALTH HEADSET A2DP三種profile的設(shè)備存在來判斷當(dāng)前是否存在設(shè)備連接。詳細(xì)內(nèi)容請參考下文
android 獲取藍(lán)牙各種連接狀態(tài)
2.getConnectionState()
Class bluetoothAdapterClass = BluetoothAdapter.class;
try {
Method method = bluetoothAdapterClass.getDeclaredMethod("getConnectionState", (Class[]) null);
method.setAccessible(true);
int state = (int) method.invoke(adapter, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
調(diào)用BluetoothAdapter中的getConnectionState()方法,直接檢查是否存在連接狀態(tài)的藍(lán)牙設(shè)備存在,由于getConnectionState()為 @hide 的方法,所以使用了反射的機(jī)制來調(diào)用。詳細(xì)內(nèi)容請參考下文:
Android開發(fā) 獲取系統(tǒng)已連接藍(lán)牙設(shè)備
但是以上兩個方法讓我感覺到了淡淡的憂傷:以上兩種方法貌似只能檢查到低功耗藍(lán)牙的連接狀態(tài),對于經(jīng)典藍(lán)牙無能為力。無奈之下只能按照上面兩種思路,寫了下面這種檢查經(jīng)典藍(lán)牙的方法。
3.isConnected()(檢查經(jīng)典藍(lán)牙連接情況)
public boolean isBtConDeviceByMac(String strCurBtMac) {
if (mBtAdapter == null) {
return false;
}
Set set = mBtAdapter.getBondedDevices();
BluetoothDevice device = null;
for (BluetoothDevice dev : set) {
if (dev.getAddress().equalsIgnoreCase(strCurBtMac)) {
device = dev;
break;
}
}
if (device == null) {
return false;
}
//得到BluetoothDevice的Class對象
Class bluetoothDeviceClass = BluetoothDevice.class;
try {//得到連接狀態(tài)的方法
Method method = bluetoothDeviceClass.getDeclaredMethod("isConnected", (Class[]) null);
//打開權(quán)限
method.setAccessible(true);
return (boolean) method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
該方法使用了BluetoothDevice類中的isConnected()方法,同理也是使用了反射的形式。通過BluetoothAdapter獲取當(dāng)前的匹配狀態(tài)的Bluetooth,檢查對應(yīng)MAC地址的設(shè)備是為連接狀態(tài)(PS:將檢查寫在循環(huán)內(nèi)可以形成以上兩篇文章類似的效果)。
總結(jié)
以上是生活随笔為你收集整理的android检测蓝牙设备连接不上,Android检查设备连接状态的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android打开wav格式,FileN
- 下一篇: android sdk软件开发套件,AN