从另一个活动中完成活动 [英] Finish activity from another activity

查看:88
本文介绍了从另一个活动中完成活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个活动A,B和C.A导致B导致C.我希望能够在A和B之间来回移动,但是我想在C开始后同时完成A和B .我了解在通过意图启动C时如何关闭B,但是在C启动时如何也关闭A?

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?

推荐答案

在您的onCreate()方法中,将静态实例分配给变量以创建Singleton:

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;
}

然后在C中:

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

(重复上面的代码B和A)

(Repeat above code for B as well as A)

我会说这不是很优雅,势必会引入奇怪的生命周期错误.

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

如果可以调整需求,那就更好了-如果不能,则可以使用单个Activity并将A,B和C更改为Fragments?

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.

使用Service绑定到活动"似乎有点过头了-但是,如果上述方法不起作用,您可能要考虑一下.

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

祝你好运!

这篇关于从另一个活动中完成活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆