How to create time (true) in AsyncTask without blocking Activity?

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

How can I execute such an unlimited loop when processing a button click in my Activity class without locking?

+4
source share
3 answers

As others have said, an endless loop without a break condition is not a pleasant user experience. First get an instance for your AsyncTask:

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

Try this in doInBackground() :

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

If the application is closed by the user, AsyncTask must be stopped in onPause() .

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

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

If you do not like this, put your task in the service.

+3
source

As others have said, you should put your โ€œendless loopโ€ inside the doInBackground () AsyncTask method. However, this cycle is not so endless, because it should end when you exist in an action or application. I suggest changing while (true) { } to while (! mustStop) { } and setting the boolean mustStop as an instance variable of your activity. Thus, you can completely stop the process by setting mustStop=true (it would be nice to set this in the onPause method).

So this will be:

 public class AsyncBigCalculActivity extends Activity { private boolean mustStop = false; @Override public void onPause() { super.onPause(); mustStop=true; // Stop the infinite loop } .... @Override protected String doInBackground(String... params) { mustStop=false; while (!mustStop) { ... } } 
+1
source

you can put the loop in the doInBackground() method for AsyncTask. As a suggestion, you can add AsyncTask as an inner class in your activity. This way you can easily access variables declared in your activity. Although the android documentation suggests using AsyncTask only for short tasks. Its more advisable to create a runnable object and put your while loop in the run() method and execute it using ExecutorService , which allows you to safely run asynchronous code in android.

http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html

http://developer.android.com/reference/java/util/concurrent/ExecutorService.html

0
source

All Articles