以编程方式检索MAC地址 - Android

5
我遇到了一个问题,无法通过程序检索设备的MAC地址。在有人提到我已经阅读过的其他帖子之前,比如:如何通过编程方式查找Android设备的MAC地址
然而,我尝试使用自己的应用程序和简单的log.d测试代码,只发现它没有返回任何内容。显示“看看这是否有效”的消息,但没有其他信息。因此,我假定MAC地址为null。
Log.d("seeing if this works", macAddress2);

我所写的代码如下所示:

这里是我所做的代码:

//Set onclick listener for the Get Mac Address button
        getMac.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                WifiInfo wInfo = wifiManager.getConnectionInfo();
                String macAddress2 = wInfo.getMacAddress();

                macAddress.setText(macAddress2);
            }
        });

你打电话时连接了WiFi吗?此外,你的AndroidManifest.xml文件中有什么? - Daniel Nugent
嗨,感谢您的回复,是的,我已经将它放在清单中了。 - hero8110
奇怪,我使用了你的代码,对我来说完全正常。你确定已经连接到 Wi-Fi 了吗? - Daniel Nugent
哦,真的吗?我正在通过Android Studio模拟器运行它,所以我假设它在模拟器上无法工作? - hero8110
3个回答

5
你正在测试哪个Android版本?最新的(2015年10月)Android M预览版已经阻止应用程序获取Wifi和蓝牙的硬件标识符。
为了为用户提供更大的数据保护,在此版本中开始,Android将删除使用Wi-Fi和Bluetooth API的应用程序对设备本地硬件标识符的编程访问。WifiInfo.getMacAddress()和BluetoothAdapter.getAddress()方法现在返回一个常量值02:00:00:00:00:00。
有一种解决方法是从/sys/class/net/wlan0/address读取Wifi MAC地址,但是这种方法也会在 Android N 中被 Google声称阻止。

3
尝试这个:

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(Integer.toHexString(b & 0xFF) + ":");
            }

            if (res1.length() > 0) {
                res1.deleteCharAt(res1.length() - 1);
            }
            return res1.toString();
        }
    } catch (Exception ex) {
    }
    return "02:00:00:00:00:00";
}

从这里开始:http://robinhenniges.com/en/android6-get-mac-address-programmatically。 对我来说有效。 (注:此文为英文原文,无需翻译)

0

你在清单文件中有这个吗?

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

谢谢您的回复,我已经将它放入我的清单文件中。 - hero8110

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接