简体   繁体   English

如何在onReceive()中关闭活动

[英]How to close an Activity in onReceive()

I'm stating a new Activity in onReceive() like this. 我正在像这样在onReceive()中声明一个新的Activity。

context.startActivity(new Intent(context, SecondActivity.class));

But can't close the activity directly in onReceive() . 但是不能直接在onReceive()中关闭活动。

I have a static variable which stores the reference to the new Activity. 我有一个静态变量,用于存储对新Activity的引用。

(the context is assigned in onCreate() of the Activity) (上下文是在Activity的onCreate()中分配的)

So I'm calling finish() in onReceive() like this. 所以我这样在onReceive()中调用finish()

SecondActivity.context.finish();

But I don't think this is a good way. 但是我认为这不是一个好方法。 Is there a better approach for this? 有更好的方法吗?

I know I can just call finish() directly in onReceive() if my BroadcastReceiver is defined within an Activity class, but the problem is, it'll close 'this' Activity but not the Activity newly created in onReceive() . 我知道如果我的BroadcastReceiver是在Activity类中定义的,那么我可以直接在onReceive ()中直接调用finish() ,但是问题是,它将关闭“ this”活动,而不是onReceive()中新创建的Activity。 And also can't call finish() when the Broadcast Receiver is static, not dynamic. 并且,当广播接收器是静态的而不是动态的时,也不能调用finish()

I'm stating a new Activity in onReceive() like this. 我正在像这样在onReceive()中声明一个新的Activity。

That is a strong code smell, unless this is a local broadcast ( LocalBroadcastManager ), in which case it is a weaker code smell. 除非是本地广播( LocalBroadcastManager ),否则这是强烈的代码气味,在这种情况下,它是较弱的代码气味。

I have a static variable which stores the reference to the new Activity. 我有一个静态变量,用于存储对新Activity的引用。

That is a strong code smell. 那是强烈的代码气味。

And also can't call finish() when the Broadcast Receiver is static, not dynamic. 并且,当广播接收器是静态的而不是动态的时,也不能调用finish()。

Changing the mix of activities based on a system broadcast is another strong code smell. 根据系统广播更改活动混合是另一个强烈的代码味道。

Is there a better approach for this? 有更好的方法吗?

Given all the code smells, I suspect that you have significant architectural problems with your app. 考虑到所有代码的味道,我怀疑您的应用程序存在严重的体系结构问题。

That being said, the general approach is not to have outside parties control activities this way. 话虽如此,一般的做法是不要让外部方以这种方式控制活动。 Instead, you use an event bus ( LocalBroadcastManager , greenrobot's EventBus) to raise an event. 而是使用事件总线( LocalBroadcastManager ,greenrobot的EventBus)引发事件。 The activity, if it exists, can listen for those events and take appropriate action, which might include destroying itself. 该活动(如果存在)可以侦听这些事件并采取适当的措施,包括破坏自身。 Alternatively, it is possible that reactive solutions (RxJava/RxAndroid, etc.) might help here, where on receipt of the broadcast you do something that triggers an observer registered by the activity. 或者,反应式解决方案(RxJava / RxAndroid等)在这里可能会有所帮助,在接收广播时,您会执行一些触发该活动注册的观察者的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM