服务调用checkSelfPermission返回nullPointerException

时间:2019-04-02 12:45:58

标签: android service permissions

我有一项服务,用于检查Android设备是否有权使用以下代码写入外部存储设备:

checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)== PackageManager.PERMISSION_GRANTED

总是返回NullPointerException

    public class Repeater extends Service {
    public Repeater() throws Exception {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
        {

 Toast.makeText(getApplicationContext(),"sasa",Toast.LENGTH_SHORT).show();
        } else {

            Log.v(TAG,"Permission is revoked");


        }
    }
    else { //permission is automatically granted on sdk<23 upon installation
        Log.v(TAG,"Permission is granted");
        }
    }

    }

完整堆栈跟踪

     java.lang.NullPointerException: Attempt to invoke virtual method 

'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
at android.content.ContextWrapper.getSystemService(ContextWrapper.java:659)
at com.presentiva.repeater.Repeater.isStoragePermissionGranted(Repeater.java:49)
at com.presentiva.repeater.Repeater.<init>(Repeater.java:30)
at java.lang.Class.newInstance(Native Method)
at android.app.ActivityThread.handleCreateService(ActivityThread.java:3173)
at android.app.ActivityThread.-wrap5(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

1 个答案:

答案 0 :(得分:0)

问题::您在服务的构造函数中检查了权限,但是那时,服务的上下文尚未初始化,因此应用程序会引发异常。

解决方案:将代码放入服务的 onCreate()方法中以检查权限。

public class Repeater extends Service {

    @Override
    public void onCreate() {
        super.onCreate();

        // Context for this service has been initialized.
        try {
            checkPermissions();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void checkPermissions() throws Exception {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(getApplicationContext(), "sasa", Toast.LENGTH_SHORT).show();
            } else {
                Log.v(TAG, "Permission is revoked");
            }
        } else { //permission is automatically granted on sdk<23 upon installation
            Log.v(TAG, "Permission is granted");
        }
    }

}