如何定期调用asyncTasksasyncTasks

2023-09-07 01:40:37 作者:感情稳浪场

我有两个AsyncTasks做网络操作。我想定期打电话给他们(如1分钟后)。我怎么做?我不认为我能做到这一点的UI线程。我是否需要创建一个新线程?是否有可能implemet这一点没有AlarmManager /服务?

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?

基本上我想一分钟后,定期exectue这两个语句。

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

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

感谢您

推荐答案

只需使用一个计时器。

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