【问题标题】:Android: How to switch to Activity that has already been createdAndroid:如何切换到已经创建的Activity
【发布时间】:2019-03-03 09:42:22
【问题描述】:

我是 Android 编程新手。 我想要做的是切换到另一个已经创建的活动。 假设我启动了活动 B 并从活动 A 移动到活动 B,然后我按下返回按钮并返回到活动 A。 现在我想在倒计时结束后切换到 Activity B。

ActivityA.java

  private void startTimer() {
        ...
        @Override
        public void onFinish() {
            // force the user to move on to Activity B
            // if the user haven't started Activity B, just start it
            if (!mHasActivityBStarted) {
                Intent intent =
                        new Intent(ActivityA.this, ActivityB.class);
                startActivity(intent);
            } else {
                // how can I switch to ActivityB that has been created?
            }
        }
    }.start();
}

我该怎么做?

【问题讨论】:

  • 我建议谷歌搜索“android活动启动模式”

标签: android android-intent


【解决方案1】:

来自Android Developer 文档

FLAG_ACTIVITY_REORDER_TO_FRONT

public static final int FLAG_ACTIVITY_REORDER_TO_FRONT

如果在传递给 Context.startActivity() 的 Intent 中设置,此标志将 导致启动的活动被带到其任务的前面 历史堆栈(如果它已经在运行)。

例如,考虑一个由四个活动组成的任务:A、B、C、 D. 如果 D 调用 startActivity() 的 Intent 解析为 活动B的组件,那么B将被带到前面 历史堆栈,结果顺序为:A、C、D、B。此标志将 如果还指定了 FLAG_ACTIVITY_CLEAR_TOP,则将被忽略。

在您的情况下,您可以在 ActivityAActivityB 之间切换,而无需完成或重新创建它们。

把它放在一起。

活动A

// Call this method when users press a button on ActivityA to go to ActivityB.
public void goToActivityB(View view) {
    Intent intent = new Intent(this, ActivityB.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    startActivity(intent);
}

// When users press a button from ActivityB, ActivityA will be bring to front and this method will be called by Android.
@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    // Write your logic code here
}

活动B

// Call this method when users press on a button in ActivityB
public void backToActivityA(View view) {
    Intent intent = new Intent(this, ActivityA.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    startActivity(intent);
}

// When users press a button from ActivityA, ActivityB will be bring to front and this method will be called by Android.
@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    // Write your logic code here
}

【讨论】:

  • 谢谢 我认为它解决了我的问题,但我仍然没有得到onNewIntent onCreate 之间的区别
  • onNewIntent 当一个活动已经在后台堆栈中并且你想再次启动它而不创建它时被调用。 onCreate 仅在首次创建活动时调用一次。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-27
  • 2012-04-17
相关资源
最近更新 更多