ThirdMartian ThirdMartian - 1 year ago 45
Android Question

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

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

and this PendingIntent is using in notification builder


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.

Answer Source

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 =
                        // add all of DetailsActivity's parents to the stack,
                        // followed by DetailsActivity itself
                        .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

Source: Create back stack when starting the activity