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