获取设备的mac地址

2021-12-22  本文已影响0人  shawnleng

Android 6.0以下

  
// Android 6.0之前的版本可以用的方法(模拟器可以使用)  
public String getLocalMacAddress() {  
    WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);  
    //  WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);  
 WifiInfo info = wifi.getConnectionInfo();  
    return info.getMacAddress();  
}

Android 6.0以上


public String getWifiMacAddress(Context context) {  
    String ret = "";  
    try {  
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {  
            String interfaceName = "wlan0";  
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();  
            NetworkInterface intf = null;  
            while (interfaces.hasMoreElements()) {  
                intf = interfaces.nextElement();  
                if (!intf.getName().equalsIgnoreCase(interfaceName)) {  
                    continue;  
                }  
                byte[] mac = intf.getHardwareAddress();  
                if (mac != null) {  
                    StringBuilder buf = new StringBuilder();  
                    for (byte aMac : mac) {  
                        buf.append(String.format("%02X:", aMac));  
                    }  
                    if (buf.length() > 0) {  
                        buf.deleteCharAt(buf.length() - 1);  
                    }  
                    ret = buf.toString();  
                }  
                break;  
            }  
        } else {  
            WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);  
            if (wifi != null) {  
                WifiInfo wifiInfo = wifi.getConnectionInfo();  
                if (wifiInfo != null) {  
                    ret = wifiInfo.getMacAddress();  
                }  
            }  
        }  
        return ret;  
    } catch (Throwable e) {  
        e.printStackTrace();  
    }  
    return ret;  
}

定制的安卓一体机

以上两种方法可能都获取不到,可能需要厂商的api

上一篇 下一篇

猜你喜欢

热点阅读