getSerial() method on Marshmallow

Viewed 11355

I'm new with Java and android and i need to basically retrieve hardware serial number from my device. I've tried the following:

import android.content.*; 
import android.os.Build;
public static String recup_android()
{
String androidid;
String SerialNumber;
androidid=android.os.Build.MODEL;
SerialNumber=android.os.Build.getserial;
return SerialNumber;
}

I'm facing the following error: java:40: error: cannot find symbol

    SerialNumber=android.os.Build.getserial;
                                 ^

symbol: variable getserial location: class Build 1 error :compileDebugJavaWithJavac FAILED

What am i missing there? If I return androidid (MODEL) it then works OK. Maybe something to have with the class declaration??

Thanks in advance for your precious help Elie

3 Answers

You are using getSerial incorrectly. Its a method not variable and available from API 26 or higher. For older versions, use Build.SERIAL

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) 
{
    // Todo Don't forget to ask the permission
    SerialNumber = Build.getSerial();
}
else
{
    SerialNumber = Build.SERIAL;    
}

Make sure you have READ_PHONE_STATE permission before calling getSerial(). Otherwise your app will crash.

Check this tutorial for asking permissions.

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && PermissionsUtility.checkPermission
(PermissionsUtility.PHONE_STATE_PERMISSION, getActivity())) {
                    SerialNumber = Build.getSerial();

            } else {
            SerialNumber = Build.SERIAL;
        }

The best way is to surround it with permission check before calling Build.getSerial() even though you have already asked permission from the user. This is the clean way to do. This will not crash and works smoothly. Make sure you have added the permission in the manifest file. Here PermissionsUtility is the utility class to check permission which returns returns

        public static final String PHONE_STATE_PERMISSION = 
Manifest.permission.READ_PHONE_STATE;

public static boolean checkPermission(String permission, Activity activity) {
    return ContextCompat.checkSelfPermission(activity, permission) == 
PackageManager.PERMISSION_GRANTED;
}

This simply checks if your app has the permission or not. In Permission pass PHONE_STATE_PERMISSION.

In Android 9, Build.SERIAL is always set to "UNKNOWN" to protect users' privacy.

If your app needs to access a device's hardware serial number, you should instead request the READ_PHONE_STATE permission, then call getSerial().

Build.getSerial() method can be used from API26 and requires READ_PHONE_STATE.

To get more information, please refer to following link:https://developer.android.com/about/versions/pie/android-9.0-changes-28

Related