调用 getSystemService();在 CountDownTimer 构造函数中给出 NPE

Calling getSystemService(); in a CountDownTimer constructor gives NPE

我有绑定服务classTimer。我想在其中启动一个新的 CountDownTimer 来更新通知。

如果我尝试将 IntentPendingIntentNotificationManager 的声明移到 onTick() 方法主体之外,则会发生异常。如果它们在 onTick() 方法中声明和实例化,它工作正常。 谁能帮助我理解为什么会这样以及我该如何解决?在每个 tick 期间创建这些对象是可行的,但似乎是在浪费资源。

private CountDownTimer newDownTimer() {
    return new CountDownTimer(millisInFuture, countDownInterval) {

        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Intent notificationIntent = new Intent(getApplicationContext(), com.kush.app.stayput.MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        public void onTick(long millisUntilFinished) {
            //Do something in every tick
            if (isPaused || isCanceled) {
                //If user requested to pause or cancel the count down timer
                cancel();
            } else {
                tView.setText("TEXT");
                //Put count down timer remaining time in a variable
                timeRemaining = millisUntilFinished;

                //Update notification
                NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(MainActivity.getContext())
                        .setContentTitle(getText(R.string.notification_title))
                        .setContentIntent(pendingIntent)
                        .setContentText("TEXT")
                        .setSmallIcon(R.drawable.ic_stat_name);

                mNotificationManager.notify(NOTIFICATION_ID, mNotifyBuilder.build());
            }
        }

        public void onFinish() {
            //Do something when count down finished
            timer = newUpTimer();
        }
    }.start();
}

FATAL EXCEPTION: main
   Process: com.example.kush.com.kush.app.stayput, PID: 16993
   java.lang.RuntimeException: Unable to instantiate service com.kush.app.stayput.countdown.Timer: 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.app.ActivityThread.handleCreateService(ActivityThread.java:2862)
       at android.app.ActivityThread.-wrap4(ActivityThread.java)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1427)
       at android.os.Handler.dispatchMessage(Handler.java:102)
       at android.os.Looper.loop(Looper.java:148)
       at android.app.ActivityThread.main(ActivityThread.java:5417)
       at java.lang.reflect.Method.invoke(Native Method)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    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:627)
       at com.kush.app.stayput.countdown.Timer.<init>(Timer.java:156)
       at com.kush.app.stayput.countdown.Timer.newDownTimer(Timer.java:153)
       at com.kush.app.stayput.countdown.Timer.reset(Timer.java:147)
       at com.kush.app.stayput.countdown.Timer.<init>(Timer.java:85)
       at java.lang.Class.newInstance(Native Method)
       at android.app.ActivityThread.handleCreateService(ActivityThread.java:2859)
       at android.app.ActivityThread.-wrap4(ActivityThread.java) 
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1427) 
       at android.os.Handler.dispatchMessage(Handler.java:102) 
       at android.os.Looper.loop(Looper.java:148) 
       at android.app.ActivityThread.main(ActivityThread.java:5417) 
       at java.lang.reflect.Method.invoke(Native Method) 
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

getSystemServiceandroid.content.Context class 上的一种方法,您的 activity/service 继承了该方法。 CountDownTimer 然而并没有继承 class。

您可能需要将上下文传递给您的 newDownTimer 函数,并确保您仅在 Activity/Service 创建后调用它。