Created
October 12, 2016 10:27
-
-
Save unclechen/c9f2b964845e2c843b527391b9dedd31 to your computer and use it in GitHub Desktop.
Android上读取MAC地址的方法,兼容Android M
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// hacking mac | |
public static String getMacAddress(Context context) { | |
String macAddress = null; | |
try { | |
String wifiInterfaceName = "wlan0"; | |
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); | |
while (interfaces.hasMoreElements()) { | |
NetworkInterface iF = interfaces.nextElement(); | |
if (iF.getName().equalsIgnoreCase(wifiInterfaceName)) { | |
byte[] addr = iF.getHardwareAddress(); | |
if (addr == null || addr.length == 0) { | |
return null; | |
} | |
StringBuilder buf = new StringBuilder(); | |
for (byte b : addr) { | |
buf.append(String.format("%02X:", b)); | |
} | |
if (buf.length() > 0) { | |
buf.deleteCharAt(buf.length() - 1); | |
} | |
macAddress = buf.toString(); | |
break; | |
} | |
} | |
} catch (SocketException se) { | |
macAddress = null; | |
} | |
if (TextUtils.isEmpty(macAddress)) { | |
android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) context.getSystemService(Context.WIFI_SERVICE); | |
macAddress = wifi.getConnectionInfo().getMacAddress(); | |
} | |
return macAddress; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment