Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Back to main activity from notification-created activity

Tags:

android

I'm trying to implement the behaviour described here, where a notification (or whatever) starts an "internal" activity in your app, and then when the user pressed back it goes to my "home" activity.

The Android docs say

In the case of the Back button, you should make navigation more predictable by inserting into the task's back stack the complete upward navigation path to the app's topmost screen. This allows users who've forgotten how they entered your app to navigate to the app's topmost screen before exiting.

Is there a good way to actually do that? Other questions on Stackoverflow suggest starting the main activity with an intent that tells it to start the internal activity, but that seems like a huge hack, that I somewhat doubt Google would have used in Gmail, and I assume there is a decent method, given that they are advocating the behaviour.

So is there a non-hacky way to do this?

like image 946
Timmmm Avatar asked Dec 10 '12 12:12

Timmmm


People also ask

How do I go back to start an activity from a notification?

When you start an activity from a notification, you must preserve the user's expected navigation experience. Tapping Back should take the user back through the app's normal work flow to the Home screen, and opening the Recents screen should show the activity as a separate task.

How do I go back to previous activity 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

Aha, I simply need to use PendingIntent.getActivities() instead of getActivity(). Also worth mentioning is TaskStackBuilder

Here is some code:

    Intent backIntent = new Intent(ctx, MainActivity.class);     backIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);      Intent intent = new Intent(ctx, ConversationActivity.class);     intent.putExtra("whatever", whatever);     final PendingIntent pendingIntent = PendingIntent.getActivities(ctx, UNIQUE_REQUEST_CODE++,             new Intent[] {backIntent, intent}, PendingIntent.FLAG_ONE_SHOT); 

Just tested it. It works like a charm. I initially suspected that there might be a problem if the app is already running, and you go to a notification. I.e. say you activity stack is (topmost on the right):

[MainActivity] [SomeActivity] 

and you click a notification for ConversationActivity. Would you get:?

[MainActivity] [SomeActivity] [MainActivity] [ConversationActivity] 

Well, it turns out you magically get

[MainActivity] [SomeActivity] [ConversationActivity] 

which is what I wanted, but I have no idea how it does that. I haven't set any special options on any of the activities. Oh well!

like image 136
Timmmm Avatar answered Sep 23 '22 18:09

Timmmm