Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you build an Android back stack when an activity is started directly from a notification?

Tags:

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?

like image 436
Andrew C Avatar asked Aug 18 '11 20:08

Andrew C


People also ask

How do I start activity and clear back stack?

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.

What happens to the back stack when you switch between activities?

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.

When an activity is at the top of the stack it is the activity that is receiving user input?

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.

How do I get my activity back on Android?

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.


1 Answers

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();     }       } 
like image 104
Dan J Avatar answered Nov 04 '22 16:11

Dan J