My program does some network activity in a background thread. Before starting, it pops up a progress dialog. The dialog is dismissed on the handler. This all works fine, exc
These days there is a much more distinct way to handle these types of issues. The typical approach is:
Anything that is a background process should be in a retained Fragment
(set this with Fragment.setRetainInstance()
. This becomes your 'persistent data storage' where anything data based that you would like retained is kept. After the orientation change event, this Fragment
will still be accessible in its original state through a FragmentManager.findFragmentByTag()
call (when you create it you should give it a tag not an ID as it is not attached to a View
).
See the Handling Runtime Changes developed guide for information about doing this correctly and why it is the best option.
You must reverse your linking process. At the moment your background process attaches itself to a View
- instead your View
should be attaching itself to the background process. It makes more sense right? The View
's action is dependent on the background process, whereas the background process is not dependent on the View
.This means changing the link to a standard Listener
interface. Say your process (whatever class it is - whether it is an AsyncTask
, Runnable
or whatever) defines a OnProcessFinishedListener
, when the process is done it should call that listener if it exists.
This answer is a nice concise description of how to do custom listeners.
Now you must worry about interfacing the background task with whatever your current View
structure is. If you are handling your orientation changes properly (not the configChanges
hack people always recommend), then your Dialog
will be recreated by the system. This is important, it means that on the orientation change, all your Dialog
's lifecycle methods are recalled. So in any of these methods (onCreateDialog
is usually a good place), you could do a call like the following:
DataFragment f = getActivity().getFragmentManager().findFragmentByTag("BACKGROUND_TAG");
if (f != null) {
f.mBackgroundProcess.setOnProcessFinishedListener(new OnProcessFinishedListener() {
public void onProcessFinished() {
dismiss();
}
});
}
See the Fragment lifecycle for deciding where setting the listener best fits in your individual implementation.
This is a general approach to providing a robust and complete solution to the generic problem asked in this question. There is probably a few minor pieces missing in this answer depending on your individual scenario, but this is generally the most correct approach for properly handling orientation change events.