Android 定时任务有好几种实现方法,可以针对不同的情况使用。我先写我用过的这种,后面再补充。
一、利用Timer + TimerTask + runOnUiThread 实现定时任务
先介绍下从网上看到的使用方法
private TimerTask mTimerTask = new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
//处理延时任务
}
});
}
};
timer.schedule(task, 2000, 3000);//启动定时任务
timer.cancel();//关闭定时任务
再说下此次项目中的简单使用(此次任务的目的是点击按钮实现定时的从网络请求数据,然后将是否请求成功结果用TextView展示出来)
@Override
public void onClick(View view) {
int i = view.getId();
if (i == R.id.button_baidu) {
mTask1 = new baiduTimerTask();//放任务时都要创建新的任务对象,且要保证上次任务已经移除。
mTimer.schedule(mTask1, DELAYTIME, PERIOD);
} else if (i == R.id.button_baidu_cancel) {
mTvBaidu.setText("");
if (mTimer != null) {
if (mTask1 != null) {
mTask1.cancel();
}
}
} else if (i == R.id.button_http_name) {
mTask2 = new questionListTimerTask();
mTimer.schedule(mTask2, DELAYTIME, PERIOD);
} else if (i == R.id.button_http_name_cancel) {
mTvHttpName.setText("");
if (mTimer != null) {
if (mTask2 != null) {
mTask2.cancel();
}
}
}
}
class baiduTimerTask extends TimerTask {
@Override
public void run() {
HttpManager.getBaidu(this, new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
final String baiduFailureInfo = e.toString();
runOnUiThread(new Runnable() {
@Override
public void run() {
mTvBaidu.setText(String.valueOf(i) + ":baidufailed");
i++;
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String baiduSuccessInfo = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
mTvBaidu.setText(String.valueOf(i) + ":baidusuccess");
i++;
}
});
}
});
}
}
class questionListTimerTask extends TimerTask {
@Override
public void run() {
HttpManager.questionList(this, TDSSCacheManager.getInstance().getStudentId(), 1, 10, new HttpCallBack() {
@Override
public void onSuccess(Object o) {
mTvHttpName.setText(String.valueOf(k) + ":questionListsuccess");
k++;
}
@Override
public void onFailed(String error) {
mTvHttpName.setText(String.valueOf(k) + ":" + error);
k++;
}
});
}
}
注意,每次放任务都要新建一个任务,且确保上一次的任务被移除了,否则会报java.lang.IllegalStateException: TimerTask is scheduled already 的错误。