Finish activity from another activity

江枫思渺然 提交于 2019-12-13 14:20:12

问题


I have 3 activities A, B and C. A leads to B which leads to C. I would like to be able to move back and forth between A and B but I want to finish both A and B once C gets started. I understand how to close B when starting C via the intent but how do I also close A when C gets started?


回答1:


In your onCreate() method assign a static instance to a variable to create a Singleton:

public static ActivityA instance = null;
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    instance = this;
}

@Override
public void finish() {
    super.finish();
    instance = null;
}

then in C:

public void onCreate(Bundle savedInstanceState) {
    if(ActivityA.instance != null) {
        try {  
            ActivityA.instance.finish(); 
        } catch (Exception e) {}
    }
}

(Repeat above code for B as well as A)

I would say this is NOT elegant and is bound to introduce strange lifecycle bugs.

It would be better if you could tweak your requirement - if you can't you could perhaps use a single Activity and change A, B and C into Fragments?

I would have suggested a Broadcast but as I understand it you can't have instance level broadcast receivers on "non resumed" Activities.

Using a Service to bind to the Activities seems like overkill - but you might want to consider that if the above doesn't work.

Good luck!




回答2:


((Activity)context_of_another_activity).finish();



回答3:


When you start C from B, do it in this way:

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

Now, C starts, but A and B are gone.

However, I think it is better if you can rethink your design such that C does not depend on A being finished or not.



来源:https://stackoverflow.com/questions/15792014/finish-activity-from-another-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!