定期执行的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();
}
};