Android のドキュメントには、 の使用方法の良い例がありますAsyncTask
。 ここに 1 つあります。ダイアログを表示するコードを追加したい場合は、おそらく次のようになります。
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
// Constant for identifying the dialog
private static final int LOADING_DIALOG = 1000;
private Activity parent;
public DownloadFilesTask(Activity parent) {
// record the calling activity, to use in showing/hiding dialogs
this.parent = parent;
}
protected void onPreExecute () {
// called on UI thread
parent.showDialog(LOADING_DIALOG);
}
protected Long doInBackground(URL... urls) {
// called on the background thread
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
// called on the UI thread
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
// this method is called back on the UI thread, so it's safe to
// make UI calls (like dismissing a dialog) here
parent.dismissDialog(LOADING_DIALOG);
}
}
バックグラウンド作業を実行する前に、onPreExecute()
コールバックされます。これは、サブクラスでオーバーライドするオプションのAsyncTask
メソッドですが、ネットワーク/データベースの作業が開始する前に UI をスローする機会が与えられます。
バックグラウンド作業が完了したら、 で UI を更新 (またはダイアログを削除) する別の機会がありますonPostExecute()
。
このクラスを ( 内からActivity
) 次のように使用します。
DownloadFilesTask task = new DownloadFilesTask(this);
task.execute(new URL[] { new URL("http://host1.com/file.pdf"),
new URL("http://host2.net/music.mp3") });