【问题标题】:Activity is getting created again instead of resuming and using instance from stack?Activity 再次被创建,而不是恢复并使用堆栈中的实例?
【发布时间】:2013-01-29 08:07:06
【问题描述】:

我有一个带有多个活动的 android 应用程序。每个活动在操作栏中都有应用程序图标,它可以帮助用户直接返回主活动而不是按返回按钮。我的问题是当我使用图标启动我的home Activity 它不使用堆栈中的前一个实例并重新开始创建它。

我的操作栏应用程序图标代码是:

startActivity(new Intent(this, DashBoard.class) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));

上面的代码启动仪表板活动并同时调用它的 onCreate() 和 onResume()。但是如果我使用后退按钮从任何活动返回到该活动,它只会调用 onResume()。

清单文件中的活动定义:

    <activity
        android:name=".DashBoard"
        android:configChanges="keyboardHidden"
        android:label="@string/app_name"
        android:screenOrientation="portrait" >
    </activity>

为什么会发生这种情况?我是否遗漏了一些东西以防止它再次创建它?请帮助

谢谢

【问题讨论】:

标签: android android-intent android-activity


【解决方案1】:

使用setFlags(),而不是addFlags()。你走在正确的轨道上。使用以下代码。

Intent intent = new Intent(this, DashBoard.class);    
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);

【讨论】:

  • Intent intent = new Intent(this, DashBoard.class); 然后intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);, startActivity(intent)
  • 你为什么要设置相同的标志两次(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_CLEAR_TOP)
  • 对不起,我的意思是使用FLAG_ACTIVITY_SINGLE_TOP。 :P,请再检查一次。
  • 哇这工作。你能告诉我为什么我们需要这两个 FLAGS 一起吗?
  • 好吧,让我引用developer.android.com/reference/android/content/…"上面示例中当前正在运行的活动B实例将在其 onNewIntent() 方法中接收您在此处开始的新意图,或者自己完成并以新的意图重新启动。如果它已声明其启动模式为“多重”(默认)并且您没有在同一意图中设置 FLAG_ACTIVITY_SINGLE_TOP,那么它将完成并重新创建;对于所有其他启动模式或如果设置了 FLAG_ACTIVITY_SINGLE_TOP 则此 Intent 将被传递
【解决方案2】:

删除 FLAG_ACTIVITY_CLEAR_TOP。

【讨论】:

  • 没有相同的结果...它再次调用 onCreate()
猜你喜欢
  • 1970-01-01
  • 2013-02-27
  • 2019-07-27
  • 2012-07-28
  • 1970-01-01
  • 2011-07-22
  • 2017-06-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多