App crashes onResume when canceling Notification

蹲街弑〆低调 提交于 2020-01-16 01:55:06

问题


I try to cancel my Notification in onResume() but it crashes:

With displayNotification() i create the Notification. I also tried to set the cancelNotification() in a try catch. But this doesn't solve the problem. But without i can't even start the app to generate the Notification.

Here are my Codesnippets:

OnResume:

@Override
    protected void onResume() //activity was resumed and is visible again 
    {
        Log.d(logtag,"onResume() called");
        super.onResume();
        cancelNotification();
    }

cancelNotification():

protected void cancelNotification() 
    {
        Log.i("Cancel", "notification");
        mNotificationManager.cancel(1);
    }

displayNotification():

protected void displayNotification(String message, String ticker) 
    {
        Log.i("Start", "notification");

        /* Invoking the default notification service */
        NotificationCompat.Builder  mBuilder = 
        new NotificationCompat.Builder(this);   

        mBuilder.setContentTitle("Neue Nachricht!");
        mBuilder.setContentText(message);
        mBuilder.setTicker(ticker);
        mBuilder.setSmallIcon(R.drawable.ic_launcher);

        /* Increase notification number every time a new notification arrives */
        mBuilder.setNumber(++numMessages);

        /* Creates an explicit intent for an Activity in your app */
        Intent resultIntent = new Intent(this, MainActivity.class);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MainActivity.class);

        /* Adds the Intent that starts the Activity to the top of the stack */
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent =
        stackBuilder.getPendingIntent(
            0,
            PendingIntent.FLAG_UPDATE_CURRENT
        );

        mBuilder.setContentIntent(resultPendingIntent);

        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        /* notificationID allows you to update the notification later on. */
        mNotificationManager.notify(1, mBuilder.build());
    }

Error:

10-23 17:27:35.763: E/AndroidRuntime(349): FATAL EXCEPTION: main
10-23 17:27:35.763: E/AndroidRuntime(349): java.lang.RuntimeException: Unable to resume activity {com.example.blauzahn/com.example.blauzahn.MainActivity}: java.lang.NullPointerException
10-23 17:27:35.763: E/AndroidRuntime(349):  at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2120)
10-23 17:27:35.763: E/AndroidRuntime(349):  at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2135)
10-23 17:27:35.763: E/AndroidRuntime(349):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1668)
10-23 17:27:35.763: E/AndroidRuntime(349):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
10-23 17:27:35.763: E/AndroidRuntime(349):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
10-23 17:27:35.763: E/AndroidRuntime(349):  at android.os.Handler.dispatchMessage(Handler.java:99)
10-23 17:27:35.763: E/AndroidRuntime(349):  at android.os.Looper.loop(Looper.java:123)
10-23 17:27:35.763: E/AndroidRuntime(349):  at android.app.ActivityThread.main(ActivityThread.java:3683)
10-23 17:27:35.763: E/AndroidRuntime(349):  at java.lang.reflect.Method.invokeNative(Native Method)
10-23 17:27:35.763: E/AndroidRuntime(349):  at java.lang.reflect.Method.invoke(Method.java:507)
10-23 17:27:35.763: E/AndroidRuntime(349):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
10-23 17:27:35.763: E/AndroidRuntime(349):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
10-23 17:27:35.763: E/AndroidRuntime(349):  at dalvik.system.NativeStart.main(Native Method)
10-23 17:27:35.763: E/AndroidRuntime(349): Caused by: java.lang.NullPointerException
10-23 17:27:35.763: E/AndroidRuntime(349):  at com.example.blauzahn.MainActivity.cancelNotification(MainActivity.java:388)
10-23 17:27:35.763: E/AndroidRuntime(349):  at com.example.blauzahn.MainActivity.onResume(MainActivity.java:976)
10-23 17:27:35.763: E/AndroidRuntime(349):  at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1150)
10-23 17:27:35.763: E/AndroidRuntime(349):  at android.app.Activity.performResume(Activity.java:3832)
10-23 17:27:35.763: E/AndroidRuntime(349):  at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2110)
10-23 17:27:35.763: E/AndroidRuntime(349):  ... 12 more

Any suggestions?


回答1:


mNotificationManager is null in cancelNotification. Just reinstantiate it:

protected void cancelNotification() {
    Log.i("Cancel", "notification");
    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.cancel(1);
}



回答2:


@EgnorN's answer is right on target: mNotificationManager is null in cancelNotification().

To add some broader lessons:

  1. We can debug problems like this from the stack trace:
    Caused by: java.lang.NullPointerException
      at ...cancelNotification(MainActivity.java:388)
      at ...onResume(MainActivity.java:976)

This indicates that the program ran afoul of a null value in cancelNotification() in MainActivity.java on line 388. That must be:

    mNotificationManager.cancel(1);

mNotificationManager must be null to cause that.

If there are multiple things that could be null on the given line, one can use a debugger breakpoint to stop at that line and look at the different values. Alternatively, break it into multiple lines and run again to see which line throws the exception.

  1. If you change the code to get the NotificationManager in each method that needs it and hold it in a local variable rather than keeping it in an instance variable, that will avoid a category of similar problems where the code incorrectly assumes that the Activity's instance variables are still set.

In any case, do read up on the Activity life cycle. It's important to know when the Activity instance gets created and deleted.

  1. If you're building your project with the API 21 version of the support.v4.app library, you can make your code a little simpler, more type safe, and more backwards compatible by using the newly added method NotificationManagerCompat.from(Context) to get a NotificationManagerCompat, which is like a NotificationManager plus fallbacks for older platforms.


来源:https://stackoverflow.com/questions/26531773/app-crashes-onresume-when-canceling-notification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!