getSerial() method on Marshmallow

别说谁变了你拦得住时间么 提交于 2020-01-01 11:47:33

问题


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


回答1:


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.




回答2:


 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.




回答3:


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



来源:https://stackoverflow.com/questions/47390216/getserial-method-on-marshmallow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!