Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if dialog can be safely dismissed

Tags:

java

android

In my app, I am showing a dialog during a long-running background process which is modal.
This dialog is dismissed when android returns from the background task.

final ProgressDialog progressDialog = ProgressDialog.show(activity, "", "Doing something long running", true, true);

new Thread(new Runnable() {
    public void run() {
        someLongRunningCode(); // (not using AsyncTask!)

        activity.runOnUiThread(new Runnable() {
            public void run() {
                progressDialog.dismiss();
            }
        });
    }
}).start();

Now, however, when the user rotates his device while the background process is still running the activity is recreated and thus, the progressdialog gets detached from the activity.
When the long running process is done, android obviously tries to hide the (now detached) progress dialog which then results in an exception: java.lang.IllegalArgumentException: View not attached to window manager.
Is there any way to check if it is safe to dismiss the dialog?

Edit: Or better still, is there any way to attach the existing dialog to the newly created activity?
A new, cloned dialog would be fine aswell.

like image 566
PureSpider Avatar asked Oct 22 '22 04:10

PureSpider


1 Answers

Just catch the exception and ignore it. Android's decision to restart the activity on rotation makes threads have a few odd exceptions like that. But the end result you want is no dialog box displayed. If you just catch the exception, no dialog box is displayed. So you're good.

If you aren't using a separate layout/drawables for landscape and portrait, you can just override configChange in your manifest for the activity so it doesn't destroy the activity (it will still correctly rotate and resize everything for you). That way the same dialog will be up and you shouldn't get the exception. The other option would require a lot of work around onSaveInstanceState and onRestoreInstanceState, and you'd need to be very careful of timing issues if the thread actually finishes during that time. The whole recreate activity on rotation idea doesn't work well with multithreading.

like image 92
Gabe Sechan Avatar answered Oct 24 '22 03:10

Gabe Sechan