Why and How to use TaskStackBuilder in Android?
Q: Why?
A: To provide proper navigation.
- 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.
How?
- Declare Parent of DetailActivity.
android:parentActivityName=".Activities.MainActivity" add this in Manifest file.
So it will look like this.
<activity android:name=".Activities.DetailActivity"
android:parentActivityName=".Activities.MainActivity">
</activity>
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:parentActivityName=".Activities.MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".Activities.MainActivity" />
</activity>
2) Use TaskStackBuilder to create a Pending Intent.
public PendingIntent getPendingIntent(Intent intent){
TaskStackBuilder taskStackBuilder = TaskStackBuilder
.create(this);
taskStackBuilder.addNextIntentWithParentStack(intent);
PendingIntent pendingIntent = taskStackBuilder
.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
}
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