在Android中獲取MAC地址可以通過以下幾種方法:
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
String macAddress = wifiManager.getConnectionInfo().getMacAddress();
try {
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
if (intf.getName().equalsIgnoreCase("wlan0")) {
byte[] mac = intf.getHardwareAddress();
if (mac == null) {
macAddress = "";
} else {
StringBuilder buf = new StringBuilder();
for (byte aMac : mac) {
buf.append(String.format("%02X:", aMac));
}
if (buf.length() > 0) {
buf.deleteCharAt(buf.length() - 1);
}
macAddress = buf.toString();
}
break;
}
}
} catch (SocketException e) {
e.printStackTrace();
}
請注意,獲取MAC地址可能需要權限,如ACCESS_WIFI_STATE和INTERNET。另外,Android 6.0及以上版本需要動態請求權限。