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

时间:2015-04-09 23:40:01

标签: java android mac-address

我遇到了以编程方式检索设备的MAC地址的问题,在任何人提及我已经阅读过的其他帖子之前,例如: How to find MAC address of an Android device programmatically

然而,我尝试将代码用于我自己的应用程序并使用简单的log.d进行测试,结果发现它没有返回任何内容。 “看看这是否有效”的信息,但没有别的。所以我假设mac地址为空。

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);
            }
        });

3 个答案:

答案 0 :(得分:3)

您正在测试哪个Android版本?最新的(2015年10月)Android M preview阻止了应用获取Wifi和蓝牙的硬件标识符。

  

为了向用户提供更好的数据保护,从此版本开始,Android会删除使用Wi-Fi和蓝牙API的应用程序对设备的本地硬件标识符的编程访问。 WifiInfo.getMacAddress()和BluetoothAdapter.getAddress()方法现在返回一个常量值02:00:00:00:00:00。

通过从/sys/class/net/wlan0/address读取Wifi MAC有一种解决方法,但是 Android N 也会阻止claimed by Google

答案 1 :(得分:2)

试试这个:

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

适合我。

答案 2 :(得分:0)

你在清单中有这个吗?

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