Android獲取Mac地址-兼容6.0及以上系統

在網上找了好久如何獲取Android mac地址,最後還是在大谷歌上找到的,經測試,4.0一直到6.0,7.0系統都可以獲取得到Mac地址

在AndroidManifest.xml中加入以下權限:

<uses-permission android:name="android.permission.INTERNET" />
然後寫一個工具類:

package cn.sss60;

import java.net.NetworkInterface;
import java.util.Collections;
import java.util.List;

/**
 * 獲取Mac地址
 */
public class MacUtils {

    public static String getMacAddr() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!nif.getName().equalsIgnoreCase("wlan0")) continue;

                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null) {
                    return "";
                }

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

                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                return res1.toString();
            }
        } catch (Exception ex) {
        }
        return "02:00:00:00:00:00";
    } 

}

最後使用這個工具類即可。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章