【Android】獲取系統的一些mac地址

  在開發過程當中,有時咱們須要獲取系統的一些硬件信息。在這裏,介紹一些硬件信息的獲取方法,其中包括BT mac, BLE mac,WIFI mac, WIFI DIRECT mac.java

  1. BT mac

  BT mac是指設備的藍牙地址。獲取方法以下:android

BluetoothManager btManager = (BluetoothManager) getContext().getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter btAdapter = btManager.getAdapter();
String btMac;
//在6.0版本之後,獲取硬件ID變得更加嚴格,因此經過設備的地址映射獲得mac地址
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  btMac = android.provider.Settings.Secure.getString(getContext.getContentResolver(), "bluetooth_address");
}else {
  btMac = btAdapter.getAddress();
}api

private String getBluetoothMacAddress() {
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    String bluetoothMacAddress = "";
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M){
        try {
            Field mServiceField = bluetoothAdapter.getClass().getDeclaredField("mService");
            mServiceField.setAccessible(true);

            Object btManagerService = mServiceField.get(bluetoothAdapter);

            if (btManagerService != null) {
                bluetoothMacAddress = (String) btManagerService.getClass().getMethod("getAddress").invoke(btManagerService);
            }
        } catch (NoSuchFieldException e) {

        } catch (NoSuchMethodException e) {

        } catch (IllegalAccessException e) {

        } catch (InvocationTargetException e) {

        }
    } else {
        bluetoothMacAddress = bluetoothAdapter.getAddress();
    }
    return bluetoothMacAddress;
}
  1. BLE mac

  BLE mac是指設備的藍牙低能耗模塊的地址,通常來講,其值和BT mac相等app

  1. WIFI mac

  WIFI mac是指設備進行wifi鏈接時的地址,獲取方法以下:ide

WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo(); 
String wifiMac = wifiInfo.getMacAddress();
  1. WIFI DIRECT mac

  WIFI DIRECT mac是指設備進行wifi直連時自身的地址,獲取方法以下(因爲android自身的api目前尚未直接獲取的方法,因此使用java的api進行獲取):ui

public String getWFDMacAddress(){
    try {
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface ntwInterface : interfaces) {

            if (ntwInterface.getName().equalsIgnoreCase("p2p0")) {
                byte[] byteMac = ntwInterface.getHardwareAddress();
                if (byteMac==null){
                    return null;
                }
                StringBuilder strBuilder = new StringBuilder();
                for (int i=0; i<byteMac.length; i++) {
                    strBuilder.append(String.format("%02X:", byteMac[i]));
                }

                if (strBuilder.length()>0){
                    strBuilder.deleteCharAt(strBuilder.length()-1);
                }

                return strBuilder.toString();
            }

        }
    } catch (Exception e) {
        Log.d(TAG, e.getMessage());
    }
    return null;
}

參考:
How do you retrieve the WiFi Direct MAC address?--stackoverflowcode

相關文章
相關標籤/搜索