getSerial() method on Marshmallow

SoundOfThunder picture SoundOfThunder · Nov 20, 2017 · Viewed 9.9k times · Source

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

Answer

Faraz picture Faraz · Nov 20, 2017

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.