Android获取Mac地址-兼容6.0及以上系统

来源:互联网 发布:单片机延时时间计算 编辑:程序博客网 时间:2024/06/04 08:34

在网上找了好久如何获取Android mac地址,最后还是在大谷歌上找到的,经测试,4.0一直到6.0,7.0系统都可以获取得到Mac地址

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

<uses-permission android:name="android.permission.INTERNET" />
然后写一个工具类:

[html] view plain copy
print?
  1. package cn.sss60;  
  2.   
  3. import java.net.NetworkInterface;  
  4. import java.util.Collections;  
  5. import java.util.List;  
  6.   
  7. /**  
  8.  * 获取Mac地址  
  9.  */  
  10. public class MacUtils {  
  11.   
  12.     public static String getMacAddr() {  
  13.         try {  
  14.             List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());  
  15.             for (NetworkInterface nif : all) {  
  16.                 if (!nif.getName().equalsIgnoreCase(“wlan0”)) continue;  
  17.   
  18.                 byte[] macBytes = nif.getHardwareAddress();  
  19.                 if (macBytes == null) {  
  20.                     return ”“;  
  21.                 }  
  22.   
  23.                 StringBuilder res1 = new StringBuilder();  
  24.                 for (byte b : macBytes) {  
  25.                     res1.append(String.format(“%02X:”,b));  
  26.                 }  
  27.   
  28.                 if (res1.length() > 0) {  
  29.                     res1.deleteCharAt(res1.length() - 1);  
  30.                 }  
  31.                 return res1.toString();  
  32.             }  
  33.         } catch (Exception ex) {  
  34.         }  
  35.         return “02:00:00:00:00:00”;  
  36.     }   
  37.   
  38. }  
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";    } }

最后使用这个工具类即可。

原创粉丝点击