獲取wifimac的幾種方式
阿新 • • 發佈:2021-06-28
1. 通過WifiManager進行獲取
@RequiresPermission(Manifest.permission.ACCESS_WIFI_STATE) public static String getWifiMacForWifiManager(Context context) { WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); if (null == wifiInfo) { return "02:00:00:00:00:00"; } String mac = wifiInfo.getMacAddress(); if (null == mac || mac.length() == 0) { return "02:00:00:00:00:00"; } return mac; }
2. 通過讀取wlan0獲取
@RequiresPermission(Manifest.permission.READ_EXTERNAL_STORAGE) public static String getWifiMacForWlan0() { String result = ""; try { File file = new File("/sys/class/net/wlan0/address"); BufferedReader reader = new BufferedReader(new FileReader(file)); result = reader.readLine(); reader.close(); } catch (Exception e) { e.printStackTrace(); } return result; }
3. 通過NetworkInterface獲取
public static String getWifiMacForNetworkInterface() { String result = ""; try { Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { NetworkInterface networkInterface = networkInterfaces.nextElement(); if (TextUtils.equals("wlan0", networkInterface.getName())) { byte[] buffer = networkInterface.getHardwareAddress(); StringBuilder address = new StringBuilder(); for (byte b : buffer) { address.append(String.format("%02X:", b)); } address.deleteCharAt(address.lastIndexOf(":")); result = address.toString().toLowerCase(); } } } catch (Exception e) { e.printStackTrace(); } return result; }