У меня есть служба, проверяющая, имеет ли устройство 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)