android / user-interface-samples

Multiple samples showing the best practices in the user interface on Android.
Apache License 2.0
4.38k stars 1.64k forks source link

Sample Notifications - Incorrectly uses TaskStackBuilder based on the "Start an Activity from a Notification" guidelines #336

Open jkasten2 opened 2 years ago

jkasten2 commented 2 years ago

Issue

One Line Summary

The Notification sample project in this repo does NOT correctly use TaskStackBuilder based on the official Android "Start an Activity from a Notification" docs.

Details

According to the code comments in the MainActivity.java the "MESSAGING_STYLE" and "BIG_PICTURE_STYLE" (however it seems the intent was "INBOX_STYLE" should be too) should be following the "Regular activity" outlined in "Build a PendingIntent with a back stack" guide however it makes two mistakes.

  1. PendingIntent not generated from stackBuilder.getPendingIntent
    • This incorrect usage creates a bug. If the user swipes a way all tasks for the app and then the notification is opened the home screen will show instead when the user press the back button instead of the MainActivity for the app.
  2. addNextIntentWithParentStack should be used instead of addParentStack followed by addNextIntent
    • While both work as indented it would be best to show the same example code as the guide, unless there is a specific case it showing in the example.

Fix

There are 3 spots where this is wrong but the fix for inbox example:

Change From:

        // Adds the back stack.
        stackBuilder.addParentStack(InboxMainActivity.class);
        // Adds the Intent to the top of the stack.
        stackBuilder.addNextIntent(mainIntent);
        // Gets a PendingIntent containing the entire back stack.
        PendingIntent mainPendingIntent =
                PendingIntent.getActivity(
                        this,
                        0,
                        mainIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );

Change To:

        // Add the intent, which inflates the back stack
        stackBuilder.addNextIntentWithParentStack(mainIntent);
        // Gets a PendingIntent containing the entire back stack.
        PendingIntent mainPendingIntent =
            stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);