How to get results from an IntentService back into an Activity?

前端 未结 4 944
猫巷女王i
猫巷女王i 2020-12-01 00:46

I am using an IntentService to handle network communications with a server via JSON. The JSON/server part is working fine, but I\'m having trouble getting the results back

相关标签:
4条回答
  • 2020-12-01 01:13

    You should look at creating your own ResultReceiver subclass in your activity. ResultReceiver implements Parcelable so can be passed from your Activity to your Service as an extra on the Intent.

    You'll need to do something like this:

    1. Implement a subclass of ResultReceiver within your activity class. The key method to implement is onReceiveResult(). This method provides you a with Bundle of result data which can be used to pass whatever information you are retrieving in your Service. Simply unpack the data you need and use it to update your activity.

    2. In your activity, create a new instance of your custom ResultReceiver and add it to the Intent you use to start your service.

    3. In your Service's onStartCommand() method, retrieve the ResultReceiver passed in on the Intent and store it in a local member variable.

    4. Once your Service completes its work, have it call send() on the ResultReceiver passing whatever data you want to send back to the activity in a Bundle.

    This is a pretty effective pattern and means you're not storing data in nasty static variables.

    0 讨论(0)
  • 2020-12-01 01:15

    There's many ways to do stuffs in background getting back a result (AsyncTask, bind an Activity to a Service...), but if you want to mantain your IntentService's code you can simply:

    1- send a broadcast intent (that contains the status in its extended data) at the end of the work in your IntentService

    2- implement a LocalBroadcastReceiver in your Activity that consumes the data from the Intent

    This is also the recommended way in the official documentation (if you want to mantain your IntentService):

    https://developer.android.com/training/run-background-service/report-status.html

    0 讨论(0)
  • 2020-12-01 01:25

    If all you need to do is get a JSON from the server without locking up the UI thread, it may be simpler to just use AsyncTask.

    0 讨论(0)
  • 2020-12-01 01:35

    You can use Otto library. Otto is an Open Source project designed to provide an event bus implementation so that components can publish and subscribe to events.

    0 讨论(0)
提交回复
热议问题