quad
quad

Reputation: 882

Android pause async task after network lost

I am using an AsyncTask where I download images using HttpUrlConnection.Im using a BroacastReciever to listen to connectivity changes. I want to know how I can pause it when network is lost and continue it after regaining the connectivity. It would be helpful if anyone can provide some snippet/code.

Thank you.

Upvotes: 1

Views: 1886

Answers (1)

Swayam
Swayam

Reputation: 16364

As far as I know, AsyncTask cannot be paused.

The documentation says that they can be run once and only once. So if you are trying to pause and resume an AsyncTask, it would lead to an IllegalStateException.

What you can do :

Inside your doInBackground(), keep checking for network connectivity after a certain time interval. When network is not available, cancel it and save the data in your application cache. Start a timer to keep on checking for network after certain timeout. When network is back again, start a fresh AsyncTask from where you left off (to be determined what you have in the cache). The last part is what I am not sure about, because you would need markers from the server as to how much you already have downloaded and how much is left. I don't think all servers provide that, which is evident from the fact that some downloads are resumable while some are not.

Another very dirty way would be put your background thread to sleep when you lose network connectivity.

Something like :

if(networkConnectivity == false)
do
{

   sleep(5000); // pauses the thread for 5 seconds

}while(networkConnectivity == false);

Upvotes: 3

Related Questions