日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

android检测蓝牙设备连接不上,Android检查设备连接状态

發布時間:2023/11/27 生活经验 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 android检测蓝牙设备连接不上,Android检查设备连接状态 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

遇到一個檢查藍牙設備連接狀態問題,困擾許久。在網上查詢良久,嘗試了多種方案,也沒有很好的解決,最終經“高人指點”,小有所獲,在此小記。

網上查詢的主要方法為以下兩種:

1.getProfileConnectionState()

BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

int state = adapter .getProfileConnectionState(int profile)

調用BluetoothAdapter 中的,getProfileConnectionState()方法通過檢查是否有使用 HEALTH HEADSET A2DP三種profile的設備存在來判斷當前是否存在設備連接。詳細內容請參考下文

android 獲取藍牙各種連接狀態

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();

}

調用BluetoothAdapter中的getConnectionState()方法,直接檢查是否存在連接狀態的藍牙設備存在,由于getConnectionState()為 @hide 的方法,所以使用了反射的機制來調用。詳細內容請參考下文:

Android開發 獲取系統已連接藍牙設備

但是以上兩個方法讓我感覺到了淡淡的憂傷:以上兩種方法貌似只能檢查到低功耗藍牙的連接狀態,對于經典藍牙無能為力。無奈之下只能按照上面兩種思路,寫了下面這種檢查經典藍牙的方法。

3.isConnected()(檢查經典藍牙連接情況)

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 {//得到連接狀態的方法

Method method = bluetoothDeviceClass.getDeclaredMethod("isConnected", (Class[]) null);

//打開權限

method.setAccessible(true);

return (boolean) method.invoke(device, (Object[]) null);

} catch (Exception e) {

e.printStackTrace();

}

return false;

}

該方法使用了BluetoothDevice類中的isConnected()方法,同理也是使用了反射的形式。通過BluetoothAdapter獲取當前的匹配狀態的Bluetooth,檢查對應MAC地址的設備是為連接狀態(PS:將檢查寫在循環內可以形成以上兩篇文章類似的效果)。

總結

以上是生活随笔為你收集整理的android检测蓝牙设备连接不上,Android检查设备连接状态的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。