Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getSerial() method on Marshmallow

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

like image 435
SoundOfThunder Avatar asked Nov 20 '17 10:11

SoundOfThunder


2 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.

like image 94
Faraz Avatar answered Oct 23 '22 09:10

Faraz


 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.

like image 4
Rohan Avatar answered Oct 23 '22 08:10

Rohan