Android獲取Mac地址-相容6.0及以上系統
阿新 • • 發佈:2019-02-11
在網上找了好久如何獲取Android mac地址,最後還是在大谷歌上找到的,經測試,4.0一直到6.0,7.0系統都可以獲取得到Mac地址
在AndroidManifest.xml中加入以下許可權:
<uses-permission android:name="android.permission.INTERNET" />
然後寫一個工具類:[html] view plain copy print?
- package cn.sss60;
- import java.net.NetworkInterface;
- import java.util.Collections;
- import java.util.List;
- /**
- * 獲取Mac地址
- */
- public class MacUtils {
- public static String getMacAddr() {
- try {
- List<NetworkInterface>all = Collections.list(NetworkInterface.getNetworkInterfaces());
- for (NetworkInterface nif : all) {
- if (!nif.getName().equalsIgnoreCase(“wlan0”)) continue;
- byte[] macBytes = nif.getHardwareAddress();
- if (macBytes == null) {
- return ”“;
- }
- StringBuilder res1 = new StringBuilder();
- for (byte b : macBytes) {
- res1.append(String.format(“%02X:”,b));
- }
- if (res1.length() > 0) {
- res1.deleteCharAt(res1.length() - 1);
- }
- return res1.toString();
- }
- } catch (Exception ex) {
- }
- return “02:00:00:00:00:00”;
- }
- }
package cn.sss60;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.List;
/**
* 獲取Mac地址
*/
public class MacUtils {
public static String getMacAddr() {
try {
List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nif : all) {
if (!nif.getName().equalsIgnoreCase("wlan0")) continue;
byte[] macBytes = nif.getHardwareAddress();
if (macBytes == null) {
return "";
}
StringBuilder res1 = new StringBuilder();
for (byte b : macBytes) {
res1.append(String.format("%02X:",b));
}
if (res1.length() > 0) {
res1.deleteCharAt(res1.length() - 1);
}
return res1.toString();
}
} catch (Exception ex) {
}
return "02:00:00:00:00:00";
}
}
最後使用這個工具類即可。