Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call asyncTasks periodically

I have two AsyncTasks doing network operations. I want to call them periodically (like after one min.). How do I do that? I dont think I can do it on the UI thread. Do i need to create a new thread? Is it possible to implemet this without AlarmManager/Service?

Basically I want to exectue these two statements periodically after one min.

new UploadAsyncTask().execute();
new DownloadAsyncTask().execute();

Thank you

like image 579
Nemin Shah Avatar asked Jun 10 '13 20:06

Nemin Shah


People also ask

Is it possible to start AsyncTask from background thread?

Android App Development for Beginners Android AsyncTask going to do background operation on background thread and update on main thread. In android we cant directly touch background thread to main thread in android development. asynctask help us to make communication between background thread to main thread.

Is AsyncTask deprecated?

This class was deprecated in API level 30. AsyncTask was intended to enable proper and easy use of the UI thread. However, the most common use case was for integrating into UI, and that would cause Context leaks, missed callbacks, or crashes on configuration changes.

What are the problems in AsyncTask?

In summary, the three most common issues with AsyncTask are: Memory leaks. Cancellation of background work. Computational cost.

How do I use onProgressUpdate in AsyncTask?

onProgressUpdate() is used to operate progress of asynchronous operations via this method. Note the param with datatype Integer . This corresponds to the second parameter in the class definition. This callback can be triggered from within the body of the doInBackground() method by calling publishProgress() .


1 Answers

Just use a timer.

final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask task = new TimerTask() {       
     @Override
     public void run() {
       handler.post(new Runnable() {
          public void run() {  
             new UploadAsyncTask().execute();
             new DownloadAsyncTask().execute();
          }
        });
      }
};
timer.schedule(task, 0, 1000); //it executes this every 1000ms
like image 151
Alexis C. Avatar answered Oct 01 '22 06:10

Alexis C.