[英]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. 假设我有活动A,它将转到活动B并在后台启动服务。 Activity B could go to a lot of other activities (C, D, E, F, etc).
活动B可以进行许多其他活动(C,D,E,F等)。 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.
后台服务将完成一些工作,当它完成时,它将发送一个广播,使得整个应用程序将返回到活动A,无论该应用程序当前处于哪个活动。我想问一下如何实现这种广播以及如何使我的所有活动都能够处理广播,而无需为每个活动类添加代码。
创建基本活动,并从您的所有活动中扩展它。在基本活动中编写您的句柄逻辑
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). 我将在
Service
运行您需要的任何逻辑并输出某种可序列化/可分配的“结果”,然后可以将其保留(SharedPreferences,SQLite,等等)。 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. 您的活动可以通过在
onResume
注册适当的侦听器(即OnSharedPreferenceChangeListener
或ContentObserver
)并在onPause
取消注册来订阅对此的更改,这意味着只有可见的活动才能处理该信息。 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. 同样在
onResume
,您可以查询此结果值,因此随后到达前台的任何活动都可以在需要时使用此“结果”。
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. Listener
可以放在它自己的类中,您可以将它放在BaseActivity或某种类型中,或者让您的活动单独实现它,因为它只是一两行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.