如何从 Android 设备获取 MAC 地址?

Mic*_*ith 6 android mac-address

我有一个可以在一部手机上运行的 Android 应用程序。为了在单个设备上工作,我需要获取 MAC 地址或 Android ID。我决定获取 MAC 地址,因为应用程序需要连接到指定的 WiFi 网络。

如何从 Android 设备获取 MAC 地址?

WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = manager.getConnectionInfo();
String address = info.getMacAddress();
Run Code Online (Sandbox Code Playgroud)

目前我正在使用这个,但它不稳定。

当应用程序重新启动时,它会返回02:00:00:00:00:00.并崩溃。

All*_*son 7

  //getting mac address from mobile
private 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(Integer.toHexString(b & 0xFF) + ":");
                res1.append(String.format("%02X:",b));
            }

            if (res1.length() > 0) {
                res1.deleteCharAt(res1.length() - 1);
            }
            return res1.toString();
        }
    } catch (Exception ex) {
        //handle exception
    }
    return "";
}
Run Code Online (Sandbox Code Playgroud)

在清单中使用这些权限

<uses-permission android:name="android.permission.INTERNET"/>

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
Run Code Online (Sandbox Code Playgroud)

获取该方法的返回值到一个字符串变量并使用它。

String MAC = getMacAddr();

希望我有帮助


小智 0

使用它作为 Android ID

   private String deviceId() {
    return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
}
Run Code Online (Sandbox Code Playgroud)