獲取Android設備WIFI的MAC地址 「MAC地址」

須要指出的是:wifi狀態和wifi AP狀態是互斥的狀態;也就是一旦發現WIFI AP打開,WIFI是不能被打開的。android

獲取Android設備的WIFI MAC地址,首先須要將設備中的WIFI我的熱點(AP)關閉;WIFI狀態和WIFI AP狀態是互斥的兩種狀態。也就是說:在WIFI AP打開的狀態下,WIFI是不能被正常打開的。app

android系統獲取MAC地址的多種方式遍歷。oop

方法一:使用NetworkInterfacespa

方法二:code

private static String getIpAndMacAddress() {
        String ip = "";
        boolean isBreak = false;
        String name = "";
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                name = intf.getName();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()
                            && inetAddress instanceof Inet4Address) {
                        ip = inetAddress.getHostAddress().toString();
                        isBreak = true;
                        break;
                    }
                }
                if (isBreak) {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        String mac = "";
        if (!TextUtils.isEmpty(name)) {
            try {
                byte[] address = NetworkInterface.getByName(name)
                        .getHardwareAddress();
                if (address != null) {
                    mac = byte2hex(address, address.length);
                }
            } catch (SocketException e) {
                e.printStackTrace();
            }
        }
        if (!TextUtils.isEmpty(mac) && !TextUtils.isEmpty(ip)) {
            return ip + "_" + mac;
        }
        return "";
    }
    private static String byte2hex(byte[] b, int length) {
        StringBuffer hs = new StringBuffer(length);
        String stmp = "";
        int len = length;
        for (int n = 0; n < len; n++) {
            stmp = Integer.toHexString(b[n] & 0xFF);
            if (stmp.length() == 1)
                hs = hs.append("0").append(stmp);
            else {
                hs = hs.append(stmp);
            }
            if (n != len - 1) {
                hs.append(":");
            }
        }
        return String.valueOf(hs);
    }

 

疑問:blog

1. 上述兩種方式哪一種更加高效?ip

2. 兩種方式是否都有侷限?get

3. 留個將來…io

相關文章
相關標籤/搜索