Android 获取mac地址方法

 /**
     * 通过网络接口获取MAC地址
     *type = eth0,获取有线mac
     * type=wlan0,获取无线mac
     * @return
     */
    public static String getMac(String type) {
        try {
            List all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                Log.d(TAG,"nif==" + nif.getName());
                if (!nif.getName().equalsIgnoreCase(type)) {
                    continue;
                }
                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null) {
                    return null;
                }

                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02X:", b));
                }

                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                Log.i(TAG, "MAC==" + res1.toString());
                return res1.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

你可能感兴趣的:(Android)