/**
* 判断给定的设备mac地址是否已连接经典蓝牙
*
* @param macAddress 设备mac地址,例如"78:02:B7:01:01:16"
* @return
*/
public static boolean isConnectClassicBT(String macAddress) {
if (TextUtils.isEmpty(macAddress)) {
return false;
}
final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Class bluetoothAdapterClass = BluetoothAdapter.class;//得到BluetoothAdapter的Class对象
try {
//是否存在连接的蓝牙设备
Method method = bluetoothAdapterClass.getDeclaredMethod("getConnectionState", (Class[]) null);
//打开权限
method.setAccessible(true);
int state = (int) method.invoke(bluetoothAdapter, (Object[]) null);
if (state == BluetoothAdapter.STATE_CONNECTED) {
Log.d("test", "BluetoothAdapter.STATE_CONNECTED");
Set devices = bluetoothAdapter.getBondedDevices();
Log.d("test", "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) {
{
return macAddress.contains(device.getAddress());
}
} else {
Log.d("test", device.getName() + " connect false(" + device.getAddress() + ")");
}
}
}
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}