问题
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:
You have two separate issues:
How do you get data from the service process to the UI process?
How do you get the data from whatever you did for #1 to whatever portion of the UI needs that data?
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.
So, for example, here is an off-the-cuff recipe for using a PendingIntent for this:
Implement a
BroadcastReceiverorServicein your activity process, registered in the manifest, but with no<intent-filter>As part of calling
startService(), create aPendingIntentusing itsgetBroadcast()orgetService()factory method, with anIntentthat identifies yourBroadcastReceiverorService, and put thatPendingIntentin an extra for theIntentused withstartService()Your service in the other process, when it has data to deliver to the activity process, calls send() on the PendingIntent, including an
Intentwith data to fill into the broadcast or service requestYour
BroadcastReceiverorServicefrom step #1 takes theIntentdelivered 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 aNotificationif all activities were destroyed)
来源:https://stackoverflow.com/questions/38936643/communication-between-service-and-activity-each-hosted-in-different-process-usin