Communication between Service and Activity each hosted in different process using PendingIntent

南笙酒味 提交于 2019-12-08 05:25:02

问题


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:

  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)



来源:https://stackoverflow.com/questions/38936643/communication-between-service-and-activity-each-hosted-in-different-process-usin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!