【问题标题】:clear stack activities and finish [duplicate]清除堆栈活动并完成[重复]
【发布时间】:2013-09-08 21:25:16
【问题描述】:

例如,

我有活动 A、B、C、D

一个电话 B

Intent intent = new Intent(A,B.class);

startActivity(intent);

然后,B调用C

Intent intent = new Intent(B,C.class);

startActivity(intent);

之后,C调用D

Intent intent = new Intent(C,D.class);

startActivity(intent);

在活动 D 中,我调用 finish()。它将返回到活动 C。

我的问题是如何在调用 finish() 之前清除 Activity A、B、C,以便应用正常退出。

不要建议在每个startactivity 上调用finish(),因为应用可以按回上一个活动以继续。

【问题讨论】:

  • 您的意思是要在调用某个活动之前清除所有活动堆栈?
  • @BirajZalavadia 现在堆栈有活动 A、B、C 和 D,现在我在活动 D 中调用 finish(),应用程序应该退出而不是返回活动 C

标签: java android android-activity android-lifecycle


【解决方案1】:

这绝对可以工作......

Intent intent = new Intent(D,A.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("close",true);
startActivity(intent);

and in oncreat of A activity u have to write
if (getIntent().getBooleanExtra("close", false)) {finish();
}
else {
{
 //ur previous code here
}

有什么问题可以问

【讨论】:

  • 现在堆栈有活动 A、B、C 和 D,现在我在活动 D 中调用 finish(),应用程序应该退出而不是返回活动 C。FLAG_ACTIVITY_CLEAR_TOP 在这里没用跨度>
  • 现在我已经根据您的需要编辑了代码
  • 我也在使用这个“技巧”。
  • 好,继续做好,享受...
【解决方案2】:

试试Intent.FLAG_ACTIVITY_CLEAR_TOP

Intent intent = new Intent(this, A.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

看这里 http://developer.android.com/reference/android/content/Intent.html

【讨论】:

  • 现在堆栈有活动A、B、C和D,现在我在活动D中调用finish(),应用程序应该退出而不是回到活动C。FLAG_ACTIVITY_CLEAR_TOP在这里没用,@ 987654325@ 需要 api 11
【解决方案3】:

我在我的应用程序中使用以下内容。希望它会有所帮助。

Intent intent = new Intent(this, A.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // this will clear the stacks
intent.putExtra("exitme", true); // tell Activity A to exit right away
startActivity(intent);

并在活动 A 中添加以下内容:

protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    if( getIntent().getBooleanExtra("exitme", false)){
        finish();
        return;
    }
}

【讨论】:

  • 这似乎有些逻辑,但不是完美的逻辑
  • 它为我完成了这项工作!在我的应用程序中使用它!
【解决方案4】:
FLAG_ACTIVITY_CLEAR_TOP
FLAG_ACTIVITY_SINGLE_TOP
FLAG_ACTIVITY_CLEAR_TASK
FLAG_ACTIVITY_NEW_TASK

确保如果一个实例已经在运行并且不在顶部,那么它上面的任何东西都将被清除并被使用,而不是启动一个新实例(这在你完成 Activity A -> Activity 后很有用B 然后你想从 B 回到 A,但是额外的标志不应该影响你上面的情况)。

【讨论】:

    【解决方案5】:

    尝试添加FLAG_ACTIVITY_NEW_TASK

    所以你的代码是:

    Intent intent = new Intent(this, A.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
    

    【讨论】:

    • 现在堆栈有活动 A、B、C 和 D,现在我在活动 D 中调用 finish(),应用程序应该退出而不是返回活动 C。FLAG_ACTIVITY_NEW_TASK 需要 api 11跨度>
    猜你喜欢
    • 2011-09-19
    • 2012-06-01
    • 2011-10-27
    • 1970-01-01
    • 1970-01-01
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    • 2016-10-14
    相关资源
    最近更新 更多