Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

android - Back to main activity from notification-created activity

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...