getSystemService(Context.CAMERA_SERVICE) 时崩溃

Crash on getSystemService(Context.CAMERA_SERVICE)

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

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

我遇到了 NullPointerException 的崩溃,我相信,Context.CAMERA_SERVICE。真的很难重现,到目前为止我还没有找到导致崩溃的序列。

    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;
            }

它看起来像是在您当前的 class (this) 中的某处,它自己的上下文被取消了,这就是您获得 NPE 的原因。

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

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