简体   繁体   中英

How to close an Activity in onReceive()

I'm stating a new Activity in onReceive() like this.

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

But can't close the activity directly in onReceive() .

I have a static variable which stores the reference to the new Activity.

(the context is assigned in onCreate() of the Activity)

So I'm calling finish() in onReceive() like this.

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() . And also can't call finish() when the Broadcast Receiver is static, not dynamic.

I'm stating a new Activity in onReceive() like this.

That is a strong code smell, unless this is a local broadcast ( LocalBroadcastManager ), in which case it is a weaker code smell.

I have a static variable which stores the reference to the new Activity.

That is a strong code smell.

And also can't call finish() when the Broadcast Receiver is static, not dynamic.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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