Search code examples
androidandroid-activityandroid-pendingintent

Opening application from notification


Let's say that we have Activity which displays funny picture and name it FunnyActivity. This Activity can be launched from MainActivity, which is base Activity in out application, after clicking button. We want also to push some notifications sometimes and when user clicks on notification this FunnyActivity should be launched. So we add this part of code:

    Intent notificationIntent = new Intent(this, FunnyActivity.class);
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    PendingIntent intent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), notificationIntent, 0);

and this PendingIntent is using in notification builder

setContentIntent(intent)

Of course FunnyActivity is beautifully launching, but we want to open MainActivity when user clicks back button on FunnyActivity.

How can we achieve that? Please remember that when user came back to MainActivity he can open FunnyActivity again from button.


Solution

  • Try this:

    // Intent for the activity to open when user selects the notification
    Intent detailsIntent = new Intent(this, DetailsActivity.class);
    
    // Use TaskStackBuilder to build the back stack and get the PendingIntent
    PendingIntent pendingIntent =
            TaskStackBuilder.create(this)
                            // add all of DetailsActivity's parents to the stack,
                            // followed by DetailsActivity itself
                            .addNextIntentWithParentStack(upIntent)
                            .addNextIntent(detailsIntent);
                            .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setContentIntent(pendingIntent);
    

    Source: Create back stack when starting the activity