Android:如何获取当前的前台活动(从服务中)? [英] Android: How can I get the current foreground activity (from a service)?

查看:47
本文介绍了Android:如何获取当前的前台活动(从服务中)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有原生 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)?

  1. 向活动发送广播 Intent -- 这里是一个示例项目 演示了这种模式
  2. 让活动提供服务调用的PendingIntent(例如,通过createPendingResult())
  3. 让活动通过 bindService() 向服务注册回调或侦听器对象,并让服务调用该回调/侦听器对象上的事件方法
  4. 向活动发送一个有序的广播 Intent,并使用一个低优先级的 BroadcastReceiver 作为备份(如果活动是,则引发 Notification不在屏幕上)--这里有一篇博文 有更多关于这个模式的内容
  1. Send a broadcast Intent to the activity -- here is a sample project demonstrating this pattern
  2. Have the activity supply a PendingIntent (e.g., via createPendingResult()) that the service invokes
  3. 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
  4. Send an ordered broadcast Intent to the activity, with a low-priority BroadcastReceiver as backup (to raise a Notification if the activity is not on-screen) -- here is a blog post with more on this pattern

这篇关于Android:如何获取当前的前台活动(从服务中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆