I want to run an long running operation in Android. Say the task would run for about 5-10 mins. For this reason I am planning to use a JobIntentService
and Bind it to an Activity
.
Right now I am using a AsyncTask
, even though I know AsyncTask
cannot/should not be used for long running operations hence I am planning to change it now. Many times what happens is while the task is running the user minimizes the app and after sometime the Android OS closes/clears the Activity
to free up some memory.
So my AsyncTask
is kept running without any purpose and crashes while trying to update a view in that Activity
.
So I am planning to use an JobIntentService
. But will using an JobIntentService
and Binding it to an Activity
will reduce the chances of Android OS closing/clearing the Activity
? or still will it follow the same process?
Any Help would be really grateful.
If your
Activity
is in the background then blocking Android from killing yourActivity
doesn't sound like a good idea (and even necessary) to me. Since yourActivity
is in the background it's not visible to the user and there's no need to update the UI during this time.Instead, you could do the following:
If
Activity
is in the foreground then it can receive updates from yourJobIntentService
viaBroadcastReceiver
that you register/unregister withLocalBroadcastManager
inonResume/onPause
.IF
JobIntentService
has completed its work when yourActivity
was killed or in the background you could persist the result somewhere (for example, inSharedPreferences
) and then inonResume
of yourActivity
you could read that result fromSharedPreferences
.