Android Snippets: Showing a ProgressDialog in an AsyncTask

AsyncTask is a relatively pain-free way to thread a background task in an Android application. However, you may want to discourage the user from performing any interaction with the application while the task is running. Or you may want to simply let them know that something is happening in the background, e.g. their file is actually downloading and pressing the button again won't make it happen any faster!

In any case, here is short example of how to show a ProgressDialog while your AsyncTask is running:

private class BackgroundTask extends AsyncTask <Void, Void, Void> {
	private ProgressDialog dialog;
	
	public BackgroundTask(MyMainActivity activity) {
		dialog = new ProgressDialog(activity);
	}

	@Override
	protected void onPreExecute() {
		dialog.setMessage("Doing something, please wait.");
		dialog.show();
	}
	
	@Override
	protected void onPostExecute(Void result) {
		if (dialog.isShowing()) {
			dialog.dismiss();
		}
	}
	
	@Override
	protected Void doInBackground(Void... params) {
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		return null;
	}
	
}

You should replace MyMainActivity in the ProgressDialog constructor with the name of the calling activity. Note also that this example doesn't actually do anything - it just sleeps for 5 seconds and then finishes. To start the task, you can use the following:

BackgroundTask task = new BackgroundTask(MyMainActivity.this);
task.execute();