Android開發獲取手機Mac地址適配所有Android版本
阿新 • • 發佈:2020-03-20
最近由於專案需要MAC地址的記錄,搞了一個通用的適配類,目前經過測試可以適配Android所有版本,我測試過的裝置系統Android 4 5 6 7 7+都可以獲取到,廢話不多說直接上程式碼,簡潔:
該類分為三類:Android6.0以下、6.0以上7.0以下、7.0以上
首先是獲取MAC的整合方法:
public static String getMac(Context context) { String strMac = null; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { Log.e("=====","6.0以下"); Toast.makeText(context,"6.0以下",Toast.LENGTH_SHORT).show(); strMac = getLocalMacAddressFromWifiInfo(context); return strMac; } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { Log.e("=====","6.0以上7.0以下"); Toast.makeText(context,"6.0以上7.0以下",Toast.LENGTH_SHORT).show(); strMac = getMacAddress(context); return strMac; } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Log.e("=====","7.0以上"); if (!TextUtils.isEmpty(getMacAddress())) { Log.e("=====","7.0以上1"); Toast.makeText(context,"7.0以上1",Toast.LENGTH_SHORT).show(); strMac = getMacAddress(); return strMac; } else if (!TextUtils.isEmpty(getMachineHardwareAddress())) { Log.e("=====","7.0以上2"); Toast.makeText(context,"7.0以上2",Toast.LENGTH_SHORT).show(); strMac = getMachineHardwareAddress(); return strMac; } else { Log.e("=====","7.0以上3"); Toast.makeText(context,"7.0以上3",Toast.LENGTH_SHORT).show(); strMac = getLocalMacAddressFromBusybox(); return strMac; } } return "02:00:00:00:00:00"; }
6.0以下方法,Google提供的公有方法,需要許可權
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
/** * 根據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 。
然而我開發的sdk就是通過wifimanager獲取的mac。
android sdk後來做了6.0適配,通過cat /sys/class/net/wlan0/address,可以在6.0上獲取mac地址。
/** * android 6.0及以上、7.0以下 獲取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,readLength); readLength = reader.read(buffer); } return builder.toString(); }
android 7.0及以上
android 7.0 後,通過上述適配的方法,將獲取不到mac地址。
經過調研和測試,7.0上仍有辦法回去mac地址:
總共分為三種方式:
- 通過ip地址來獲取繫結的mac地址
- 掃描各個網路介面獲取mac地址
- 通過busybox獲取本地儲存的mac地址
程式碼如下:
/** * 根據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; } /** * 獲取移動裝置本地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();// 得到下一個元素 Enumeration<InetAddress> en_ip = ni.getInetAddresses();// 得到一個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; }
/** * android 7.0及以上 (2)掃描各個網路介面獲取mac地址 * */ /** * 獲取裝置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; if (interfaces == null) { return null; } while (interfaces.hasMoreElements()) { iF = interfaces.nextElement(); try { hardWareAddress = bytesToString(iF.getHardwareAddress()); if (hardWareAddress != null) break; } catch (SocketException e) { e.printStackTrace(); } } return hardWareAddress; } /*** * byte轉為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(); }
/** * android 7.0及以上 (3)通過busybox獲取本地儲存的mac地址 * */ /** * 根據busybox獲取本地Mac * * @return */ public static String getLocalMacAddressFromBusybox() { String result = ""; String Mac = ""; result = callCmd("busybox ifconfig","HWaddr"); // 如果返回的result == null,則說明網路不可取 if (result == null) { return "網路異常"; } // 對該行資料進行解析 // 例如: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; }
本文主要講解了Android獲取手機Mac地址的例項原始碼,更多關於Android獲取手機Mac地址的技巧請檢視下面的相關連結