I’m currently using the following code to show / hide a ProgressDialog in my Andorid app (called from withing MyActivity):
private void startTask() {
new MyTask().execute();
}
private class MyTask extends AsyncTask<A, String, C> {
private ProgressDialog pd;
@Override
protected void onPreExecute() {
super.onPreExecute();
this.pd = ProgressDialog.show(MyActivity.this, "Title", "Message", true, true);
pd.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
MyTask.this.cancel(true);
}
});
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
this.pd.setMessage(values[0]);
}
@Override
protected void onCancelled() {
super.onCancelled();
Toast.makeText(MyActivity.this, "cancelled", Toast.LENGTH_SHORT).show();
}
@Override
protected void onPostExecute(RequestResult result) {
super.onPostExecute(result);
this.pd.dismiss();
}
}
Now, since I read so much about onCreateDialog in Activities, I just want to know if my way of doing it has any downsides I didn’t think of, or even why I should prefer the onCreateDialog mechanism.
[UPDATED]
The problem with this approach is that in case Activity will be destroyed (e.g. on rotation) your AsyncTask will retain it in memory, thus create a temporary memory leak. Also, it will cause an IllegalArgumentException while attempting to access ProgressDialog after activity’s onDestroy().