How to use Android Back Stack Navigate
Navigate Android
Sample Scenario
You have sent a product notification to the user. When the user clicks notification A, they are directed directly to the Product Details page. When the user is finished pressing back on the page and you want to redirect the user to the home page of the application. If you are not making any additional improvement, pressing back for this scenario will close the application. Because there’s no screen to go back to. The details page has been opened directly.
Solution
First, we have to do manifest.specify parentActivityName where we define DetailActivity in the XML file. In other words, if you press the backspace key, we write this activity to the parentActivityName field, whichever activity we want to open.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <application ... > ... <!-- The main/home activity (it has no parent activity) --> <activity android:name="com.example.myfirstapp.MainActivity" ...> ... </activity> <!-- A child of the main activity --> <activity android:name="com.example.myfirstapp.DetailActivity" android:label="@string/title_activity_display_message" android:parentActivityName="com.example.myfirstapp.MainActivity" > <!-- .--> <meta-data android:name="android.support.PARENT_ACTIVITY" android:value="com.example.myfirstapp.MainActivity" /> </activity> </application> |
Then we edit the code that we prepared for the notification demonstration as follows.
1 2 3 4 5 6 7 8 9 10 | // 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(detailsIntent) .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder builder = new NotificationCompat.Builder(this); builder.setContentIntent(pendingIntent); |
The Mainactivity page will now open when the user presses back on the DetailsActivity page that is opened with notification.