定期执行的AsyncTask类对象:更新时间 [英] Periodically Executing AsyncTask Class object: Updated

查看:113
本文介绍了定期执行的AsyncTask类对象:更新时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是重新开始的AsyncTask它已经完成之后的最佳方式。 我的应用程序,我需要做一些更新UI每30秒左右的后台处理。

what is the best way to start AsyncTask again after it has completed. My application is where I need to do some background processing that updates UI every 30 secs or so.

所以将这个好

MyAsyncTask t;

onCreate(){
 postDelayed(myrunnable,..)
}

myrunnable(){
if(t && t.getStatus()== FINISHED){
t = new MyAsyncTask();
t.execute()

 postDelayed(myrunnable,30000)
}else
postDelayed(myrunnable,2000)
}

更新:编辑在code,所以如果这个序列似乎有效,请说是或建议更改

Update:Edited the code, So if this sequence seems valid please say yes or suggest changes

推荐答案

您可以:

  • 注册类负责AsyncTask的执行作为听众你的AsyncTask的。
  • 当任务完成后,在doInBackground方法在年底前实施在AsyncTask的回调。
  • 当您收到回调执行下一个AsyncTask的。

例: 您的侦听器接口:

Example: Your listener interface:

public interface IProgress {

  public void onProgressUpdate(final boolean isFinished);

}

您的活动实现IProgress:

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);
    }
  }

您的AsyncTask包含IProgress实例,并调用onProgressUpdate在doInBackground年底或onPostExecute:

Your AsyncTask contains a 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);
  }

对于postDelayed创建runnnable:

Create a runnnable for the 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();
    }
  };

这篇关于定期执行的AsyncTask类对象:更新时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆