Periodically Running an AsyncTask Class Object: Updated

What is the best way to start AsyncTask again after its completion. My application is where I need to do some background processing that updates the user interface every 30 seconds or so.

So it will be alright

MyAsyncTask t; onCreate(){ postDelayed(myrunnable,..) } myrunnable(){ if(t && t.getStatus()== FINISHED){ t = new MyAsyncTask(); t.execute() postDelayed(myrunnable,30000) }else postDelayed(myrunnable,2000) } 

Update: Edited code. Therefore, if this sequence seems valid, say yes or suggest changes.

0
source share
2 answers

You can:

  • Register your class responsible for executing AsyncTask as a listener in your AsyncTask.
  • Embed a callback in your AsyncTask when the task completes at the end of doInBackground.
  • Run the following AsyncTask when receiving the callback.

Example: Your listener interface:

 public interface IProgress { public void onProgressUpdate(final boolean isFinished); } 

Your activity implements IProgress:

 public class MyActivity implements IProgress { public void onProgressUpdate(final boolean isFinished) { if (isFinished) { // delayed execution myHandler.postDelayed(new MyRunnable(MyActivity.this), 30000); } } 

Your AsyncTask contains an IProgress instance, and you call onProgressUpdate at the end of doInBackground or in onPostExecute:

...

  private final IProgress progressListener; public MyAsyncTask( final IProgress progressListener) { super(); this.progressListener = progressListener; } 

...

  @Override protected void onPostExecute(final int result) { progressListener.onProgressUpdate(true); super.onPostExecute(result); } 

Create runnnable for postDelayed:

  protected class MyRunnable implements Runnable { private final IProgress progressListener; public MyRunnable(final IProgress progressListener) { super(); this.progressListener= progressListener; } public void run() { new MyAsyncTask(progressListener).execute(); } }; 
+1
source

The Async-task class for a specific time, such as a 30 second interval.

You can use http://developer.android.com/reference/java/util/concurrent/ScheduledExecutorService.html .

0
source

Source: https://habr.com/ru/post/1208971/


All Articles