如果即使您的应用程序当前未运行,您也需要执行计划任务,建议您使用AlarmManager和BroadcastReceivers 。
否则,文档建议使用Handlers。
正如 AmitD 问题的评论中所讨论的那样。如果任务需要在后台运行,您可以在处理程序回调中使用 AsyncTask 来实现此目的。
final Handler handler = new Handler() {
public void handlerMessage(Message msg) {
new AsyncTask<TaskParameterType,Integer,TaskResultType>() {
protected TaskResultType doInBackground(TaskParameterType... taskParameters) {
// Perform background task - runs asynchronously
}
protected void onProgressUpdate(Integer... progress) {
// update the UI with progress (in response to call to publishProgress())
// - runs on UI thread
}
protected void onPostExecute(TaskResultType result) {
// update the UI with completion - runs on UI thread
}
}.execute(taskParameterObject);
}
};
handler.postMessageDelayed(msg, delayMillis);
对于重复执行,文档还提到ScheduledThreadPoolExecutor作为一个选项(这似乎优于java.util.Timer,主要是由于额外的灵活性)。
final Handler handler = new Handler() {
public void handlerMessage(Message msg) {
// update the UI - runs on the UI thread
}
};
ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
ScheduledFuture f = exec.scheduleWithFixedDelay(new Runnable() {
public void run() {
// perform background task - runs on a background thread
handler.sendMessage(msg); // trigger UI update
}
}, 0, 10, TimeUnit.SECONDS);