Android获取Mac地址(WIFI,移动网络,网线(lan))

帖子原地址:http://blog.csdn.net/zxw136511485/article/details/52161269

获取mac地址一般有3中情况:WIFI,移动网络,lan口(网线),在网上找了一圈,大多数都只支持WIFI,没有考虑移动网络和lan口的情况,也没有考虑到6.0系统的情况,终于找到一个能兼容这三种情况的方法:

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


    /** 
     * 获取手机的MAC地址 
     *  
     * @return 
     */  
    public static String getMac() {  
        String str = "";  
        String macSerial = "";  
        try {  
            Process pp = Runtime.getRuntime().exec(  
                    "cat /sys/class/net/wlan0/address ");  
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());  
            LineNumberReader input = new LineNumberReader(ir);  

            for (; null != str;) {  
                str = input.readLine();  
                if (str != null) {  
                    macSerial = str.trim();// 去空格  
                    break;  
                }  
            }  
        } catch (Exception ex) {  
            ex.printStackTrace();  
        }  
        if (macSerial == null || "".equals(macSerial)) {  
            try {  
                return loadFileAsString("/sys/class/net/eth0/address")  
                        .toUpperCase().substring(0, 17);  
            } catch (Exception e) {  
                e.printStackTrace();  

            }  

        }  
        return macSerial;  
    }  

    public static String loadFileAsString(String fileName) throws Exception {  
        FileReader reader = new FileReader(fileName);  
        String text = loadReaderAsString(reader);  
        reader.close();  
        return text;  
    }  

    public static String loadReaderAsString(Reader reader) throws Exception {  
        StringBuilder builder = new StringBuilder();  
        char[] buffer = new char[4096];  
        int readLength = reader.read(buffer);  
        while (readLength >= 0) {  
            builder.append(buffer, 0, readLength);  
            readLength = reader.read(buffer);  
        }  
        return builder.toString();  
    }     

}  

PS:在6.0上需要AndroidManifest.xml在加入以下2个权限

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />  
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />  

你可能感兴趣的:(安卓开发)