简体   繁体   中英

Can one programmatically obtain the MAC address of a device running Android 6.0+?

Can one programmatically obtain the MAC address of a device running Android 6.0+?

According to this ,

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.

Does that mean it's impossible to get the device's MAC address in Android 6.0+? If it's possible, can you tell me how to do it in Android Studio?

Also, this answer only applies to devices with versions of Android below 6.0

You can use an alternative way to get the MAC addr on a Android 6.0 device.

First add Internet User-Permission to your AndroidManifest.xml:

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

Secondly,

try {
        // get all the interfaces
        List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
        //find network interface wlan0  
        for (NetworkInterface networkInterface : all) {
            if (!networkInterface.getName().equalsIgnoreCase("wlan0")) continue;
        //get the hardware address (MAC) of the interface    
            byte[] macBytes = networkInterface.getHardwareAddress();
            if (macBytes == null) {
                return "";
            }


            StringBuilder res1 = new StringBuilder();
            for (byte b : macBytes) {
                //gets the last byte of b
                res1.append(Integer.toHexString(b & 0xFF) + ":");
            }

            if (res1.length() > 0) {
                res1.deleteCharAt(res1.length() - 1);
            }
            return res1.toString();
        }
    } catch (Exception ex) {
           ex.printStackTrace();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM