Home > front end >  can't get mac address while targetSdkVersion is 31
can't get mac address while targetSdkVersion is 31

Time:01-04

I get mac address in my app. when targetSdkVersion is 29 everything is correct, but when update targetSdkVersion to 31, I can not get mac address.

private fun getMacAddress(): String =
    NetworkInterface.getNetworkInterfaces().toList()
        .firstOrNull { it.name.equals("wlan0", ignoreCase = true) }?.let {
            it.hardwareAddress?.let { macBytes ->
                StringBuilder().apply {
                    for (b in macBytes) {
                        append(String.format("X:", b))
                    }
                    if (isNotEmpty()) {
                        deleteCharAt(lastIndex)
                    }
                }
            }?.toString() ?: run {
                "00:00:00:00:00:00"
            }
        } ?: "00:00:00:00:00:00"

CodePudding user response:

You can't mac address in >= 31 SDK version but you can uniquely identify your device using android_id

import android.provider.Settings.Secure;

private String android_id = Secure.getString(getContext().getContentResolver(),
                                                        Secure.ANDROID_ID);

CodePudding user response:

In short, you can't.

According to Android Developers - MAC address availability changes in Android 11, they blocked the access to the MAC address if you target Android 11:

In addition, non-privileged apps can't access the device’s MAC address; only network interfaces with an IP address are visible. This impacts the getifaddrs() and NetworkInterface.getHardwareAddress() methods, as well as sending RTM_GETLINK Netlink messages.

Also, from NetworkInterface.getHardwareAddress documentation:

For example, this method will generally return null when called by non-system apps having targetSdkVersion >= android.os.Build.VERSION_CODES.R.

  •  Tags:  
  • Related