回到主要活动从通知创建活动创建活动、通知

2023-09-06 14:45:38 作者:酷的不着边

我想实现的行为描述这里,其中一个通知(或其他)启动一个内部的活动在您的应用程序,然后当用户pressed回到它关系到我的家的活动。

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.

Android的文档说

The Android docs say

在返回按钮的情况下,你应该让导航更   predictable的的将其插入任务的回堆栈的完整   向上导航路径到应用程序的最上面的屏幕的。这使得用户   谁已经忘记了他们是如何进入你的应用程序导航到该应用程序的   退出之前,最上面的屏幕。

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.

有没有好办法真正做到这一点?在#1的其他问题,建议起步意图,告诉它启动内部活动的主要活动,但似乎像一个巨大的黑客,我有点怀疑谷歌将在Gmail中都用过,我假设有一个体面的方法,给出他们所提倡的行为。

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?

推荐答案

啊哈,我只需要使用 PendingIntent.getActivities()而不是 getActivity()。另外值得一提的是TaskStackBuilder

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

下面是一些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]

和您单击的通知 ConversationActivity 。你会得到:?

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!