功能:通过反射获取Android蓝牙的地址
问题:异常问题未知,待详细测试
/**
* 获取蓝牙地址
*
* @return
*/
public static String getBluetoothAddress() {
// BluetoothAdapter bluetoothAdapter = BluetoothAdapter
// .getDefaultAdapter();
// String bluetooth = bluetoothAdapter.getAddress();
// return bluetooth;
// --------
// BluetoothAdapter bluetoothAdapter =
// BluetoothAdapter.getDefaultAdapter();
// Object bluetoothManagerService = new
// Mirror().on(bluetoothAdapter).get().field("mService");
// if (bluetoothManagerService == null) {
//
// return null;
// }
// Object address = new
// Mirror().on(bluetoothManagerService).invoke().method("getAddress").withoutArgs();
// if (address != null && address instanceof String) {
//
// return (String) address;
// } else {
// return null;
// }
try {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Field field = bluetoothAdapter.getClass().getDeclaredField("mService");
// 参数值为true,禁用访问控制检查
field.setAccessible(true);
Object bluetoothManagerService = field.get(bluetoothAdapter);
if (bluetoothManagerService == null) {
return null;
}
Method method = bluetoothManagerService.getClass().getMethod("getAddress");
Object address = method.invoke(bluetoothManagerService);
if (address != null && address instanceof String) {
return (String) address;
} else {
return null;
}
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}