Android获取MAC地址

获取MAC地址

6.0之前 
public static String getMAC(Context context) {
    WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    if (manager == null) {
        return null;
    }
    WifiInfo info = manager.getConnectionInfo();
    String address = info.getMacAddress();
    return address;
}
6.0之后
public static String getHightMac() throws SocketException{
    Enumeration interfaceEnumeration = NetworkInterface.getNetworkInterfaces();
    while (interfaceEnumeration.hasMoreElements()){
        NetworkInterface networkInterface = interfaceEnumeration.nextElement();
        byte[] addr = networkInterface.getHardwareAddress();
        if (addr==null || addr.length==0){
            continue;
        }
        StringBuilder buf = new StringBuilder();
         for (byte b: addr){
             buf.append(String.format("%02X:",b));

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

         }
         return buf.toString();
    }
    return "";
}
注意:要加权限 

如果6.0之前也用第一种方法只会获取到“02:00:00:00:00:00”,第二种获取没有问题“10:D0:7A:E1:FD:22”,可能查看本机设备,字母是小写的,获取是大写,没有关系的,都可以的。

你可能感兴趣的:(Android)