This is the 13th day of my participation in the August More Text Challenge. For details, see:August is more challenging

background

Previously the unique identifier of our product was obtained by android.os.build.serial or build.getserial (), but after Android 10 this method will return unknown or empty. So after Android 10 this approach is no longer possible.

After Android P, security and data are more private on Android, so the wireless MAC address obtained through the getMacAddress() method is randomized. But our product is running in rising micro card LCD advertising machine application, is a wired network port. The MAC address of the wired network port will certainly not change, so our solution is to get the MAC address of etho (etho stands for Ethernet, wLAN0 stands for wireless card).

code

public String getSerialNumber() { String serial = ""; System.out.println("getSerialNumber Begin\n"); Try {if (build.version.sdk_int < build.version_codes.n) {//8.0- serial = execCmd("getprop ro.boot.serialno"); System.out.println("getprop.serialno:" + serial+"\n"); }else{ serial = getMacEth0(); } } catch (Exception e) { e.printStackTrace(); } if(TextUtils.isEmpty(serial)) { serial = getAndroidID(); } System.out.println("getSerialNumber end"+"\n"); return serial; } private String getMacEth0() {try {// Get all network interfaces of the machine Enumeration Enumeration = NetworkInterface.getNetworkInterfaces(); while (enumeration.hasMoreElements()) { NetworkInterface networkInterface = (NetworkInterface)enumeration.nextElement();  / / access to hardware address, usually in MAC byte [] arrayOfByte = networkInterface. GetHardwareAddress (); if (arrayOfByte == null || arrayOfByte.length == 0) { continue; } StringBuilder stringBuilder = new StringBuilder(); for (byte b : ArrayOfByte) {// Format as: Append (string. format("%02X:", new Object[] {byte.valueof (b)}))); } the if (stringBuilder. Length () > 0) {/ / delete redundant colon behind the stringBuilder. DeleteCharAt (stringBuilder. The length () - 1); } String str = stringBuilder.toString(); If (networkinterface.getName ().equals("eth0")) {return STR; } } } catch (SocketException socketException) { return ""; } return ""; }Copy the code
        private String getAndroidID()
    {
        String m_szAndroidID = Settings.Secure.getString(getApplicationContext().getContentResolver(),
                Settings.Secure.ANDROID_ID);
        return m_szAndroidID;
    }
Copy the code

The above code gives two scenarios. 1 is the optimized way to get the MAC address. The second is to use ANDROID_ID. However, AndroidID has a disadvantage, root, brush or factory reset will cause the device ANDROID_ID to change, so if there is no such scenario, actually recommend ANDROID_ID, convenient and reliable.

If you don’t have a wired network port, see the following article for a unique identifier:

Exploring the Android 10 device id acquisition scheme

Android Q (Android 10) obtain a unique ID(optimal solution)