Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a while(true) in a AsyncTask whithout blocking the Activity?

I have created an AsyncTask and I have to create an while(true) on my AsyncTask.

How can I execute such an unbounded loop upon handling a button click in my Activity class without blocking?

like image 719
Shuty Avatar asked Jan 22 '13 15:01

Shuty


1 Answers

How others said a infinit loop without a break condition isn't a nice user experience. First get a instance for your AsyncTask:

 PostTask pt = new PostTask(this);
 pt.execute();

Try this in your doInBackground():

while(!this.isCancelled()){
    // doyourjobhere


}

If the app is getting closed by the user the AsyncTask have to be stopped in your onPause().

@Override
public void onPause(){
    pt.cancel(false);  
}

TheAsyncTask.cancel(boolean) sets isCancelled() to true, calls the AsyncTask.onCanceled() method instead of onPostExecute() and can be overwritten for your own purpose.

If you don't like this put your task in a Service.

like image 63
Steve Benett Avatar answered Sep 22 '22 17:09

Steve Benett