Crash on getSystemService(Context.CAMERA_SERVICE)



我有一个小部件,它带有一个启用相机服务的按钮。

它运行得很好,但过了一段时间(可能是主屏幕应用程序退出(,它就失去了状态(打开或关闭(。

我和Context.CAMERA_SERVICENullPointerException发生了碰撞。这真的很难复制,到目前为止,我还没有找到导致崩溃的序列。

Caused by: 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:714)
at com.widget.tst.Widget.CallbackWidgetService.isCameraInUse(CallbackWidgetService.java:163)
at com.widget.tst.Widget.CallbackWidgetService.startCameraInUse(CallbackWidgetService.java:242)
//** button click--> 
at com.widget.tst.Widget.CameraWidgetReceiver.updateWidgetButton(CameraWidgetReceiver.java:55)
at com.widget.tst.Widget.CameraWidgetReceiver.onReceive(CameraWidgetReceiver.java:32)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3632)
at android.app.ActivityThread.-wrap18(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1975) 
at android.os.Handler.dispatchMessage(Handler.java:109) 
at android.os.Looper.loop(Looper.java:166) 
at android.app.ActivityThread.main(ActivityThread.java:7367) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:469) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:963)

Context.CAMERA_SERVICE怎么可能为空?

private void isCameraInUse(){
if(context == null) return;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
-->  line 163       mCameraManager = (CameraManager)getSystemService(Context.CAMERA_SERVICE);
}
else{
Toast.makeText(context, "You need to run Android version "+
Build.VERSION_CODES.M+" or above",
Toast.LENGTH_SHORT).show();
return;
}

看起来在当前类(this(中的某个地方,它自己的上下文被清空了,这就是为什么你得到了NPE。

但是既然在一个变量(if(context == null) return;(中有一个100%非空的上下文,为什么不呢;您不使用它来代替this自己的上下文吗?:

mCameraManager = (CameraManager)context.getSystemService(Context.CAMERA_SERVICE);

最新更新