Android:如何获取当前的前台活动(从服务中)? [英] Android: How can I get the current foreground activity (from a service)?
问题描述
是否有原生 android 方法可以从服务中获取对当前正在运行的 Activity 的引用?
Is there a native android way to get a reference to the currently running Activity from a service?
我有一个在后台运行的服务,我想在事件发生时更新我当前的活动(在服务中).有没有一种简单的方法可以做到这一点(就像我上面建议的那样)?
I have a service running on the background, and I would like to update my current Activity when an event occurs (in the service). Is there a easy way to do that (like the one I suggested above)?
推荐答案
是否有原生 android 方法可以从服务中获取对当前正在运行的 Activity 的引用?
Is there a native android way to get a reference to the currently running Activity from a service?
您可能不拥有当前正在运行的活动".
You may not own the "currently running Activity".
我有一个在后台运行的服务,我想在事件发生时更新我当前的活动(在服务中).有没有一种简单的方法可以做到这一点(就像我上面建议的那样)?
I have a service running on the background, and I would like to update my current Activity when an event occurs (in the service). Is there a easy way to do that (like the one I suggested above)?
- 向活动发送广播
Intent
-- 这里是一个示例项目 演示了这种模式 - 让活动提供服务调用的
PendingIntent
(例如,通过createPendingResult()
) - 让活动通过
bindService()
向服务注册回调或侦听器对象,并让服务调用该回调/侦听器对象上的事件方法 - 向活动发送一个有序的广播
Intent
,并使用一个低优先级的BroadcastReceiver
作为备份(如果活动是,则引发Notification
不在屏幕上)--这里有一篇博文 有更多关于这个模式的内容
- Send a broadcast
Intent
to the activity -- here is a sample project demonstrating this pattern - Have the activity supply a
PendingIntent
(e.g., viacreatePendingResult()
) that the service invokes - Have the activity register a callback or listener object with the service via
bindService()
, and have the service call an event method on that callback/listener object - Send an ordered broadcast
Intent
to the activity, with a low-priorityBroadcastReceiver
as backup (to raise aNotification
if the activity is not on-screen) -- here is a blog post with more on this pattern
这篇关于Android:如何获取当前的前台活动(从服务中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!