6

This question has already been asked here but yet no good answer.

So basically I have an intent service running in the background to do some stuff and once finished I send the result back to activity using resultreceiver so what I need to know is the following:

  1. How can I handle a situation when activity is destroyed while intent service is still running?
  2. How to know if activity is destroyed from intent service?
  3. What happens to resultreciever when sending the result back to activity when the activity is already destroyed? Does that produce an error?
Elydasian
  • 2,016
  • 5
  • 23
  • 41
has19
  • 1,307
  • 16
  • 31

1 Answers1

4

This is a late answer, but I was researching the functioning of IntentService and I came across your question.

how can handle a situation when activity is destroyed while intent service is still running ?

Since the IntentService is a separate component it will continue to run until the task designated to it is complete or the process on which the application is running is destroyed. The initial thought might be to stop the IntentService when the activity is destroyed. Simple, isn't it? Well, not quite. As it turns out when you call stopService(Intent), though the onDestroy() method of the IntentService is called, the background thread will continue to run until it's complete and deliver a result to the receiver.

how to know if activity is destroyed from intent service?

This is a good question and something that I myself wondered. One neat solution is described here - IntentService responding to dead ResultReceiver

what happen to resultreciever when sending the result back to activity when the activity is already destroyed ?does that produced error?

This will most likely not result in any visible exception as the activity is not visible. But it could result in a memory leak on a configuration change as you have a reference to an object defined in the activity (which will prevent the activity from being garbage collected as long the thread continues to run - see IntentService prevents activity from destroying). But the answer linked above should alleviate this problem as it nulls out the reference of the ResultReceiver in onDestroy, avoiding any potential memory issues

Also, it would be worthwhile to mention that you can consider the approach of a LocalBroadcastManager which makes it easier to work with the lifecycle of the Activity by registering/unregistering the BroadcastReceiver. Example available here from the google samples repo

Anatolii
  • 14,139
  • 4
  • 35
  • 65
Abhijit
  • 4,853
  • 3
  • 30
  • 33