简体   繁体   中英

How can I make all of my activities able to handle a broadcast from a service?

Let's say I have activity A which will go to activity B and also start a service in the background. Activity B could go to a lot of other activities (C, D, E, F, etc). The background service will do some work, and when it finishes, it will send a broadcast such that the whole app will go back to activity A no matter which activity the app is currently in. I would like to ask how to implement this kind of broadcast and how to make all of my activities able to handle the broadcast without adding code for each activity class.

创建基本活动,并从您的所有活动中扩展它。在基本活动中编写您的句柄逻辑

I'd question whether you need your activities to handle this response. In most cases, you will only ever have one or zero Activities in the foreground at any one time, so there's no need for background Activities to process this information as it will only be relevant to whatever activity is user visible.

I would run any logic you need in the Service and output some kind of serializable/parcelable "result", which can then be persisted (SharedPreferences, SQLite, whatever else). Your Activities can subscribe to changes to this by registering an appropriate listener (ie an OnSharedPreferenceChangeListener or ContentObserver ) in onResume and unregister in onPause , which means only visible activties will handle the information. Also in onResume , you can query this result value, so any Activities that subsequently come to the foreground can use this "Result" as and when it is required.

The Listener can be placed in its own class, and you can either put it in a BaseActivity or some sort, or just have your Activities implement it separately as it will be just a line or two.

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