【问题标题】:Understand FLAG_ACTIVITY_NEW_TASK and onNewIntent了解 FLAG_ACTIVITY_NEW_TASK 和 onNewIntent
【发布时间】:2015-11-29 18:10:31
【问题描述】:

我的 Android 应用程序由 2 个活动组成:A 和 B 具有不同的任务相关性。从活动 A 开始,我使用标志 FLAG_ACTIVITY_NEW_TASK 开始活动 B。同样,从活动 B 开始,我使用相同的意图标志来启动活动 A。虽然活动 A 仍然存在,但调用的是 onCreate 方法而不是 onNewIntent。此外,按下后退按钮会将我带到主屏幕。我如何理解这种行为?

【问题讨论】:

    标签: android


    【解决方案1】:

    onNewIntent 仅适用于具有singleTop 启动模式的活动,这意味着如果该活动在顶部,则不要启动新活动,而是在onNewIntent 内将此意图传递给它。如果 Activity 不在栈顶,这不会生效。

    来自文档:

    FLAG_ACTIVITY_NEW_TASK
    If set, this activity will become the start of a new task on this history stack.
    

    所以新启动的活动在这个新创建的任务中没有以前的活动,这个按下返回会把你带到主屏幕。

    如果您希望您的活动在整个应用程序中只有一个实例,那么您可以在清单中使用singleTask。来自文档:

    The system creates a new task and instantiates the activity at the
    root of the new task. However, if an instance of the activity already
    exists in a separate task, the system routes the intent to the existing
    instance through a call to its onNewIntent() method, rather than
    creating a new instance. Only one instance of the activity can exist at a time.
    

    【讨论】:

    • @Souabh 我同意这样一个事实,即如果活动存在,则不会创建活动的新实例。但是我很困惑当目标活动(发送意图的对象)低于其他活动时如何传递意图?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-05
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    相关资源
    最近更新 更多