安卓获取手机本身的蓝牙MAC地址

一、安卓6.0之前的版本

获取蓝牙适配器BluetoothAdpater
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
或者
BluetoothAdapter adapter = (BluetoothAdapter) getApplicationContext().getSystemService(BLUETOOTH_SERVICE);
//安卓6以后的版本使用此方法拿不到真实的MAC地址
String macAddr = adapter.getAddress();

二、安卓6.0之后的版本

打开蓝牙才能获得
 /**
 * 获取本机蓝牙地址
 */
  private String getBluetoothAddress() {
  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 (Exception e) {
    e.printStackTrace();
  }
  return null;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。