I have two activities:
Activity A - list of items
Activity B - detail view of an item
Normally, a user opens the app and Activity A is launched. A user sees a list of items, clicks one, and Activity B is started to display the item detail.
Activity B can also be started directly from clicking on a notification. In this case there is no back stack.
How can I make it so that when Activity B is started directly from a notification, the user can click the Back button and go to Activity A?
Declare Activity A as SingleTop by using [android:launchMode="singleTop"] in Android manifest. Now add the following flags while launching A from anywhere. It will clear the stack.
If the user presses or gestures Back, the current activity is popped from the stack and destroyed. The previous activity in the stack is resumed. When an activity is destroyed, the system does not retain the activity's state.
onResume() At this point, the activity is at the top of the activity stack, with the user input going to it. It is always followed by the onPause() method.
You opened the new activity from another activity with startActivityForResult. In that case you can just call the finishActivity() function from your code and it'll take you back to the previous activity.
You can add an Extra into the Intent launched by the notification to detect when the app has been launched in that way.
Then you can override the onBackPressed()
Activity method and handle that scenario, e.g.
@Override public void onBackPressed() { Bundle extras = getIntent().getExtras(); boolean launchedFromNotif = false; if (extras.containsKey("EXTRA_LAUNCHED_BY_NOTIFICATION")) { launchedFromNotif = extras.getBoolean("EXTRA_LAUNCHED_BY_NOTIFICATION"); } if (launchedFromNotif) { // Launched from notification, handle as special case Intent intent = new Intent(this, ActivityA.class); intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); mActivity.startActivity(intent); finish(); } else { super.onBackPressed(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With