Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android AsyncTask with activity lifecycle

Am using AsyncTask in order to download images within my activity

the flow goes like this:

protected void onPreExecute() {
        \\begin animation
}

protected IUpiResponse doInBackground(String... params) {
         \\ download the image
}

protected void onPostExecute(IUpiResponse upiResponse) {
         \\stop the animation
}

till here everything fine, the problem start if i go to background while the asynctask is working sometimes I get an exception nullpointer in the animation stops, because the views no longer valid (i guess),

I can check before the stop animation if the activity is in foreground but i prefer to avoid this approach, what else i can do ?

like image 256
and_dev Avatar asked Jan 03 '13 12:01

and_dev


1 Answers

I prefer to avoid the asyncTask approach and to download the images in a simple thread, which also saves them to persistence layer such as file system, and then sends an Intent ,

Note: if the activity in the background the Intent ( if you register and unregister your receiver in onResume and onPause as advised ) will not be received so to avoid such cases inside onResume you can check if there is update waiting for you

like image 154
Tomer Mor Avatar answered Sep 30 '22 20:09

Tomer Mor