Communication between Service and Activity each ho

2019-05-31 07:09发布

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条回答
beautiful°
2楼-- · 2019-05-31 07:38

You have two separate issues:

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

  2. 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:

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

  2. 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()

  3. 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

  4. 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)

查看更多
登录 后发表回答