Why and How to use TaskStackBuilder in Android?

Q: Why?

A: To provide proper navigation.

  1. When the app is launched by App icon (Normal Flow)

2) When the app is launched by some Notification

The general flow of navigation in your app is MainActivity->DetailActivity

But sometimes a Notification might directly open the DetailActivity. In this case, pressing the back button will not lead you to the `MainActivity. It's an EXPECTED BEHAVIOR. However, you can modify this if you want to navigate back to MainActivity.


  1. Declare Parent of DetailActivity.

android:parentActivityName=".Activities.MainActivity" add this in Manifest file.

So it will look like this.

<activity android:name=".Activities.DetailActivity"

But! this feature was added in Android 4.1. So if you want to target older devices. Add a meta-tag as well.

<activity android:name=".Activities.DetailActivity"
android:value=".Activities.MainActivity" />

2) Use TaskStackBuilder to create a Pending Intent.

public PendingIntent getPendingIntent(Intent intent){

TaskStackBuilder taskStackBuilder = TaskStackBuilder
PendingIntent pendingIntent = taskStackBuilder


You are all set. Now just pass this Pending intent to create Notifications.

Putting up content takes a lot of time and effort 😓.
👏 clap 👏 If you think you learned something from this article.
You can find me on Stackoverflow,Github,and,on Linkedin.
Give feedback and feel free to correct mistakes.

Read More:

What is addToBackStack in Fragment




Android Developer | Arizona State University | NASA Psyche Research Aide

Love podcasts or audiobooks? Learn on the go with our new app.

How we accidentally developed a meditation app during this lockdown time

Make Your Own Voice Control Appliances using the HC-05 Bluetooth Module.

Get Started Your First Mobile Top Down Shooting Game Development With Unity Visual Scripting Part 1

Part-time Dev Advocacy?


4 Reasons why SaaS Startups should not consider Microservices for their product development

Sharing the Fun of LHD: Share 2021

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Rohit Singh

Rohit Singh

Android Developer | Arizona State University | NASA Psyche Research Aide

More from Medium

Android Development Internship LGM-VIP(MARCH-2022)

MVP vs MVVM on Android

What is Mavia, how to play it and how to get into the whitelist

Does Android Need Antivirus?