アプリが現在実行されていない場合でもスケジュールされたタスクを実行する必要がある場合は、 AlarmManagerとBroadcastReceiversを使用することをお勧めします。
それ以外の場合、ドキュメントではハンドラーの使用を推奨しています。
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);