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

来源:互联网 发布:图像算法教程 编辑:程序博客网 时间:2024/06/10 00:10

帖子原地址: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" />  
阅读全文
0 0
原创粉丝点击