Getting MAC address in Android 6.0

2019-01-07 11:04发布

I'm developing an app that gets the MAC address of the device, but since Android 6.0 my code doesn't work, giving me an incorrect value.

Here's my code...

    public String ObtenMAC()
{
    WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    WifiInfo info = manager.getConnectionInfo();

    return(info.getMacAddress().toUpperCase());
}

Instead of the real MAC address, it returns an strange code: "02:00:00:00:00:00".

Can anybody help me to solve it?.

Thanks in advance.

9条回答
Root(大扎)
2楼-- · 2019-01-07 11:55

The answers are mostly correct, but keep care, that there is a change in android 7. You will need to use the

DevicePolicyManager and the Method getWifiMacAddress. The official docs has a typo, which means that you shouldnt copy/paste it from there.

DevicePolicyManager.getWifiMacAddress()

Refs: https://developer.android.com/about/versions/nougat/android-7.0-changes.html

Get Device mac adress in Android Nougat and O programmatically

查看更多
对你真心纯属浪费
3楼-- · 2019-01-07 11:57

I didn't get the above answer to work, but stumbled upon another answer.

Here is a complete and simple method on getting the IPv6 address and then getting the mac address from it.

How to get Wi-Fi Mac address in Android Marshmallow

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(String.format("%02X:",b));
            }

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

Tested it already and it works. Many thanks to Rob Anderson!

查看更多
时光不老,我们不散
4楼-- · 2019-01-07 12:01

Please refer to Android 6.0 Changes.

To provide users with greater data protection, starting in this release, Android removes programmatic access to the device’s local hardware identifier for apps using the Wi-Fi and Bluetooth APIs. The WifiInfo.getMacAddress() and the BluetoothAdapter.getAddress() methods now return a constant value of 02:00:00:00:00:00.

To access the hardware identifiers of nearby external devices via Bluetooth and Wi-Fi scans, your app must now have the ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION permissions.

查看更多
登录 后发表回答