从android中删除堆栈中的活动

时间:2011-09-16 12:06:20

标签: java android android-activity activity-stack

我想使用code.Heres my case

从堆栈中删除一个活动
  
      
  1. 从第A页开始,我将转到第B页。
  2.   
  3. 从页面B我必须使用返回按钮返回页面A.
  4.   
  5. 在第B页中,我有一个按钮,它转到第C页。
  6.   
  7. 当我点击第B页的那个按钮时,我正在呼叫
  8.   
finish(); //to remove PageB from stack

好的,这是问题,当我点击返回按钮时,从页面C我被带到页面A.因为它在堆栈中。

  

当我点击页面B中的按钮时,我想从堆栈中删除页面A.

请注意,在调用Page B时我无法在页面A中调用finish(),因为我想返回到页面A.只有当我点击页面B中的按钮时,我不想返回的情况。

我怎么能在android中这样做? 感谢

4 个答案:

答案 0 :(得分:5)

当您启动B时,不要在A中调用startActivity,而是致电startActivityForResult。然后,您对A的活动处理onActivityResult

现在,在B中,当您打开C时,请在致电完成前致电setResult。这将允许您设置一些数据以传递回A的onActivityResult方法。传递一个标志,表示A应该关闭,然后调用finish。在A onActivityResult中处理该标志。

这样,每个活动都有责任自行关闭,而且你不会人为地搞乱后台。使用意图标记在简单的A,B,C情况下工作正常,但如果这3个屏幕是更大解决方案的一部分,则可能会分崩离析(即A,B和C深入到您不想要的一堆活动中一塌糊涂)。

答案 1 :(得分:4)

您可以通过启动Intent直接跳转到另一个Activity,而不是完成当前的Activity。

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

答案 2 :(得分:0)

您可以使用startActivity()从B再次调用A.

答案 3 :(得分:0)

肯定有一个更好的答案on this page但是,作为一种解决方法,您可以使用SharedPreferences将消息传递给活动A,请求它也完成。

活动A:

public class A extends Activity {

  public static final String CLOSE_A_ON_RESUME = "CLOSE_A_ON_RESUME";

  @Override
  public void onResume(){
    super.onResume();

    //Retrieve the message
    SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean IShouldClose=mPrefs.getBoolean(A.CLOSE_A_ON_RESUME,false);

    if (IShouldClose){

       //remove the message (will always close here otherwise)
       mPrefs.edit().remove(A.CLOSE_A_ON_RESUME).commit();

       //Terminate A
       finish();
    }
}

活动C:

public class C extends Activity {

  /*
   * Stores an application wide private message to request that A closes on resume
   * call this in your button click handler
   */
  private void finishCthenA(){

    //Store the message
    SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    mPrefs.edit().putBoolean(A.CLOSE_A_ON_RESUME,true).commit();

    //finish C
    finish();
}

请注意,这有点冒险,因为首选项在重新启动后仍然存在,并且例如,如果您的应用程序在A恢复之前被杀死,则可以阻止A启动。 要解决此问题,您还应该删除A.onCreate()

中的消息