Reputation: 798
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?
Upvotes: 2
Views: 482
Reputation: 1007359
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 BroadcastReceiver
or Service
in your activity process, registered in the manifest, but with no <intent-filter>
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
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)
Upvotes: 2