我有一个服务检查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)
问题:您在服务的构造函数中检查权限,但此时,服务的上下文尚未初始化,因此应用程序抛出异常的原因。
解决方案:使用您的代码检查服务的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");
}
}
}