使用PendingIntent在不同流程中托管的服务和活动之间的通信 [英] Communication between Service and Activity each hosted in different process using PendingIntent

查看:118
本文介绍了使用PendingIntent在不同流程中托管的服务和活动之间的通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从一个片段启动前台服务,该片段在调用startService()后被销毁,这就是我不能使用ResultReceiverMessanger的原因.因此,该选项仍为PendingIntent.如何使用PendingIntent在任何活动/片段之间的前台服务(在不同进程中托管)之间进行通信?

I am starting a foreground service from a fragment which gets destroyed after call to startService(), which is a reason I can't use ResultReceiver or Messanger. So the option remains PendingIntent. How can I communicate between foreground service(hosted in different process) from any activity/fragment using PendingIntent?

推荐答案

您有两个独立的问题:

  1. 如何从服务流程到UI流程获取数据?

  1. How do you get data from the service process to the UI process?

如何将数据从您为#1做的工作中获取到UI的任何部分需要该数据的地方?

How do you get the data from whatever you did for #1 to whatever portion of the UI needs that data?

#1有许多解决方案:PendingIntentResultReceiverMessenger,用于绑定服务连接的AIDL定义的回调等.#2然后主要是使用事件总线或类似于向所有相关Java对象发出有关新数据的警报.

There are any number of solutions for #1: PendingIntent, ResultReceiver, Messenger, AIDL-defined callback for a bound service connection, etc. #2 then mostly is a matter of using an event bus or something similar to alert all relevant Java objects about the new data.

例如,这是使用PendingIntent为此的现成配方:

So, for example, here is an off-the-cuff recipe for using a PendingIntent for this:

  1. 在活动过程中实施BroadcastReceiverService,已在清单中注册,但没有<intent-filter>

  1. Implement a BroadcastReceiver or Service in your activity process, registered in the manifest, but with no <intent-filter>

作为调用startService()的一部分,使用其getBroadcast()getService()工厂方法创建一个PendingIntent,并使用Intent标识您的BroadcastReceiverService,并将其放入PendingIntentstartService()

As part of calling startService(), create a PendingIntent using its getBroadcast() or getService() factory method, with an Intent that identifies your BroadcastReceiver or Service, and put that PendingIntent in an extra for the Intent used with startService()

在另一个过程中,当您的服务有要传递到活动过程的数据时,

Your service in the other process, when it has data to deliver to the activity process, calls send() on the PendingIntent, including an Intent with data to fill into the broadcast or service request

您在步骤#1中的BroadcastReceiverService接收了传递给它的Intent,并使用事件总线让您的其余活动过程知道发生了什么,还处理了<在活动过程中没有任何注册事件(例如,如果所有活动均被破坏,则举报Notification)

Your BroadcastReceiver or Service from step #1 takes the Intent delivered to it and uses an event bus to let the rest of your activity process know about whatever happened, also handling the case where nothing in the activity process is registered for the event (e.g., raise a Notification if all activities were destroyed)

这篇关于使用PendingIntent在不同流程中托管的服务和活动之间的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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