~~~
package com.example.myapplication.util;
import android.annotation.SuppressLint;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.text.TextUtils;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Locale;
public class HardwareUtil {
public static String getMacAddress(Context context) {
String macAddress = null;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
macAddress = getMacFormWifi(context);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
macAddress = getMacFromCommand();
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
macAddress = getMacFromHardware();
}
return macAddress;
}
@SuppressLint("HardwareIds")
public static String getMacFormWifi(Context context) {
if (context == null) {
return null;
}
WifiManager wifi = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo info = null;
try {
info = wifi.getConnectionInfo();
} catch (Exception e) {
e.printStackTrace();
}
if (info == null) {
return null;
}
String macAddress = info.getMacAddress();
if (!TextUtils.isEmpty(macAddress)) {
macAddress = macAddress.toUpperCase(Locale.ENGLISH);
}
return macAddress;
}
public static String getMacFromCommand() {
String macAddress = null;
String buffer = "";
try {
Process pp = Runtime.getRuntime().exec("cat/sys/class/net/wlan0/address");
InputStreamReader inputStreamReader = new InputStreamReader(pp.getInputStream());
LineNumberReader lineNumberReader = new LineNumberReader(inputStreamReader);
while (null != buffer) {
buffer = lineNumberReader.readLine();
if (buffer != null) {
macAddress = buffer.trim();
break;
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
return macAddress;
}
public static String getMacFromHardware() {
try {
ArrayList<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nif : all) {
if (!nif.getName().equals("wlan0")) {
continue;
}
byte[] macBytes = nif.getHardwareAddress();
if (macBytes == null) {
return null;
}
StringBuilder macAddress = new StringBuilder();
for (Byte b : macBytes) {
macAddress.append(String.format("%02X:", b));
}
if (!TextUtils.isEmpty(macAddress)) {
macAddress.deleteCharAt(macAddress.length() - 1);
}
return macAddress.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
~~~