在應用開發中有時會碰到操作藍牙設備的需求,這時就需要獲取手機已連接的藍牙設備,其中"已連接"是廣泛含義,其實藍牙設備分爲可鏈接設備(比如:藍牙音箱 藍牙耳機) 和可綁定設備(比如:手機 藍牙自拍杆 藍牙手錶 藍牙鍵盤等設備) 其中的區別就是connected狀態,用int表示其區別共有三個值 10表示無綁定也無鏈接 11表示綁定 12表示鏈接。
如果通過標準協議api獲取已連接的設備由於其實現機制返回結果會比較慢,可通過如下反射方式來獲取:
//獲取已連接的藍牙設備
private void getConnectedBtDevice(){
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
Class<BluetoothAdapter> bluetoothAdapterClass = BluetoothAdapter.class;//得到BluetoothAdapter的Class對象
try {
//得到連接狀態的方法
Method method = bluetoothAdapterClass.getDeclaredMethod("getConnectionState", (Class[]) null);
//打開權限
method.setAccessible(true);
int state = (int) method.invoke(adapter, (Object[]) null);
if(state == BluetoothAdapter.STATE_CONNECTED){
Log.i("BLUETOOTH","BluetoothAdapter.STATE_CONNECTED");
Set<BluetoothDevice> devices = adapter.getBondedDevices(); //集合裏面包括已綁定的設備和已連接的設備
Log.i("BLUETOOTH","devices:"+devices.size());
for(BluetoothDevice device : devices){
Method isConnectedMethod = BluetoothDevice.class.getDeclaredMethod("isConnected", (Class[]) null);
method.setAccessible(true);
boolean isConnected = (boolean) isConnectedMethod.invoke(device, (Object[]) null);
if(isConnected){ //根據狀態來區分是已連接的還是已綁定的,isConnected爲true表示是已連接狀態。
Log.i("BLUETOOTH-dh","connected:"+device.getName());
//deviceList.add(device);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}