国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統(tǒng) > Android > 正文

詳解Android MacAddress 適配心得

2019-12-12 02:11:06
字體:
供稿:網(wǎng)友

android 6.0以下mac地址獲取

我們獲取mac地址一般都是這樣寫的:

 /**   * 根據(jù)wifi信息獲取本地mac   * @param context   * @return   */  public static String getLocalMacAddressFromWifiInfo(Context context){    WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);    WifiInfo winfo = wifi.getConnectionInfo();    String mac = winfo.getMacAddress();    return mac;  }

android 6.0及以上、7.0以下

Android 6.0以后 將不再能通過 wifimanager 獲取mac,獲取到的mac將是固定的:02:00:00:00:00:00 。

然而我開發(fā)的sdk就是通過wifimanager獲取的mac。

android sdk后來做了6.0適配,通過cat /sys/class/net/wlan0/address,可以在6.0上獲取mac地址。

 /**   * 獲取mac地址   * @param context   * @return   */  public static  String getMacAddress(Context context){    //如果是6.0以下,直接通過wifimanager獲取    if(Build.VERSION.SDK_INT<Build.VERSION_CODES.M){      String macAddress0 = getMacAddress0(context);      if(!TextUtils.isEmpty(macAddress0)){        return macAddress0;      }    }    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) {      Log.e("----->" + "NetInfoManager", "getMacAddress:" + ex.toString());    }    if (macSerial == null || "".equals(macSerial)) {      try {        return loadFileAsString("/sys/class/net/eth0/address")            .toUpperCase().substring(0, 17);      } catch (Exception e) {        e.printStackTrace();        Log.e("----->" + "NetInfoManager", "getMacAddress:" + e.toString());      }    }    return macSerial;  }   private static  String getMacAddress0(Context context) {    if (isAccessWifiStateAuthorized(context)) {      WifiManager wifiMgr = (WifiManager) context          .getSystemService(Context.WIFI_SERVICE);      WifiInfo wifiInfo = null;      try {        wifiInfo = wifiMgr.getConnectionInfo();        return wifiInfo.getMacAddress();      } catch (Exception e) {        Log.e("----->" + "NetInfoManager", "getMacAddress0:" + e.toString());      }    }    return "";  }  /**   * Check whether accessing wifi state is permitted   *   * @param context   * @return   */  private static boolean isAccessWifiStateAuthorized(Context context) {    if (PackageManager.PERMISSION_GRANTED == context        .checkCallingOrSelfPermission("android.permission.ACCESS_WIFI_STATE")) {      Log.e("----->" + "NetInfoManager", "isAccessWifiStateAuthorized:" + "access wifi state is enabled");      return true;    } else      return false;  }  private static String loadFileAsString(String fileName) throws Exception {    FileReader reader = new FileReader(fileName);    String text = loadReaderAsString(reader);    reader.close();    return text;  }  private 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();  }

android 7.0及以上

android 7.0 后,通過上述適配的方法,將獲取不到mac地址。

經(jīng)過調(diào)研和測(cè)試,7.0上仍有辦法回去mac地址:

(1)通過ip地址來獲取綁定的mac地址

 /**   * 獲取移動(dòng)設(shè)備本地IP   * @return   */  private static InetAddress getLocalInetAddress() {    InetAddress ip = null;    try {      //列舉      Enumeration<NetworkInterface> en_netInterface = NetworkInterface.getNetworkInterfaces();      while (en_netInterface.hasMoreElements()) {//是否還有元素        NetworkInterface ni = (NetworkInterface) en_netInterface.nextElement();//得到下一個(gè)元素        Enumeration<InetAddress> en_ip = ni.getInetAddresses();//得到一個(gè)ip地址的列舉        while (en_ip.hasMoreElements()) {          ip = en_ip.nextElement();          if (!ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1)            break;          else            ip = null;        }        if (ip != null) {          break;        }      }    } catch (SocketException e) {      e.printStackTrace();    }    return ip;  }  /**   * 獲取本地IP   * @return   */  private static String getLocalIpAddress() {    try {      for (Enumeration<NetworkInterface> en = NetworkInterface          .getNetworkInterfaces(); en.hasMoreElements();) {        NetworkInterface intf = en.nextElement();        for (Enumeration<InetAddress> enumIpAddr = intf            .getInetAddresses(); enumIpAddr.hasMoreElements();) {          InetAddress inetAddress = enumIpAddr.nextElement();          if (!inetAddress.isLoopbackAddress()) {            return inetAddress.getHostAddress().toString();          }        }      }    } catch (SocketException ex) {      ex.printStackTrace();    }    return null;  }  /**   * 根據(jù)IP地址獲取MAC地址   * @return   */  public static String getMacAddress(){    String strMacAddr = null;    try {      //獲得IpD地址      InetAddress ip = getLocalInetAddress();      byte[] b = NetworkInterface.getByInetAddress(ip).getHardwareAddress();      StringBuffer buffer = new StringBuffer();      for (int i = 0; i < b.length; i++) {        if (i != 0) { buffer.append(':');        }        String str = Integer.toHexString(b[i] & 0xFF);        buffer.append(str.length() == 1 ? 0 + str : str);      }      strMacAddr = buffer.toString().toUpperCase();    } catch (Exception e) {    }    return strMacAddr;  }

 (2)掃描各個(gè)網(wǎng)絡(luò)接口獲取mac地址

 /**   * 獲取設(shè)備HardwareAddress地址   * @return   */  public static String getMachineHardwareAddress(){    Enumeration<NetworkInterface> interfaces = null;    try {      interfaces = NetworkInterface.getNetworkInterfaces();    } catch (SocketException e) {      e.printStackTrace();    }    String hardWareAddress = null;    NetworkInterface iF = null;    while (interfaces.hasMoreElements()) {      iF = interfaces.nextElement();      try {        hardWareAddress = bytesToString(iF.getHardwareAddress());        if(hardWareAddress != null)          break;      } catch (SocketException e) {        e.printStackTrace();      }    }    return hardWareAddress ;  }  /***   * byte轉(zhuǎn)為String   * @param bytes   * @return   */  private static String bytesToString(byte[] bytes){    if (bytes == null || bytes.length == 0) {      return null ;    }    StringBuilder buf = new StringBuilder();    for (byte b : bytes) {      buf.append(String.format("%02X:", b));    }    if (buf.length() > 0) {      buf.deleteCharAt(buf.length() - 1);    }    return buf.toString();  }

 (3)通過busybox獲取本地存儲(chǔ)的mac地址

 /**   * 根據(jù)busybox獲取本地Mac   * @return   */  public static String getLocalMacAddressFromBusybox(){    String result = "";    String Mac = "";    result = callCmd("busybox ifconfig","HWaddr");    //如果返回的result == null,則說明網(wǎng)絡(luò)不可取    if(result==null){      return "網(wǎng)絡(luò)異常";    }    //對(duì)該行數(shù)據(jù)進(jìn)行解析    //例如:eth0   Link encap:Ethernet HWaddr 00:16:E8:3E:DF:67    if(result.length()>0 && result.contains("HWaddr")==true){      Mac = result.substring(result.indexOf("HWaddr")+6, result.length()-1);      result = Mac;    }    return result;  }  private static String callCmd(String cmd,String filter) {    String result = "";    String line = "";    try {      Process proc = Runtime.getRuntime().exec(cmd);      InputStreamReader is = new InputStreamReader(proc.getInputStream());      BufferedReader br = new BufferedReader (is);      while ((line = br.readLine ()) != null && line.contains(filter)== false) {        result += line;      }      result = line;    }    catch(Exception e) {      e.printStackTrace();    }    return result;  }

 對(duì)比效果截圖

上述三種方法,對(duì)比我開發(fā)的sdk現(xiàn)在使用的方法以及通過wifimanager獲取mac地址的方法,效果如下(7.0設(shè)備有限,只覆蓋部分機(jī)型):

結(jié)論

通過上述對(duì)比,通過ip獲取mac地址和掃描網(wǎng)絡(luò)接口獲取mac結(jié)合使用,可以達(dá)到準(zhǔn)確的效果。

通過ip獲取的mac地址優(yōu)先級(jí)高,只有在它獲取不到的情況下,再使用掃描網(wǎng)絡(luò)接口獲取的mac地址。

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 普兰县| 玉林市| 萨嘎县| 专栏| 郓城县| 滨海县| 濉溪县| 裕民县| 岢岚县| 泰来县| 庐江县| 平果县| 当涂县| 呼伦贝尔市| 黄梅县| 武宁县| 监利县| 喀喇沁旗| 博野县| 闻喜县| 莫力| 崇义县| 济南市| 自治县| 宣城市| 汕头市| 会东县| 陕西省| 荔浦县| 柳江县| 丽水市| 淮阳县| 石狮市| 都匀市| 鄢陵县| 陇南市| 托克托县| 上饶县| 杨浦区| 修水县| 印江|