The Android docs have good examples of how to use AsyncTask
. There's one here. If you want to add some code to show dialogs, then maybe something like this:
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);
}
}
Before performing the background work, onPreExecute()
will be called back. This is an optional method to override in your AsyncTask
subclass, but it gives you a chance to throw up a UI before the network/database work starts.
After the background work completes, you have another opportunity to update the UI (or remove a dialog) in onPostExecute()
.
You'd use this class (from within an Activity
) like so:
DownloadFilesTask task = new DownloadFilesTask(this);
task.execute(new URL[] { new URL("http://host1.com/file.pdf"),
new URL("http://host2.net/music.mp3") });