建议你使用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);
任何周期性的,这期间会杀了,因为它永远不会让CPU(和系统)睡觉电池 –