Home » Android » My app frequently throws android.view.WindowLeaked exception —

My app frequently throws android.view.WindowLeaked exception —

Posted by: admin May 14, 2020 Leave a comment

Questions:

My app frequently throws exception like below:

E/WindowManager( 6282): android.view.WindowLeaked: Activity
com.myActivity has leaked window
[email protected] that
was originally added here

The app shows a progress dialog when the main activity starts and starts a task. When the task is done, it will dismiss the progress dialog.

My code is like below. Can someone help me?

public class MyActivity extends Activity {

private static int ID_DIALOG_PROGRESS = 2001;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);        
    setContentView(R.layout.my_activity);
    showDialog(ID_DIALOG_PROGRESS);
    new MyTask().execute(null, null, null);
}

@Override
protected Dialog onCreateDialog(int id) {
    if (id == ID_DIALOG_PROGRESS) {
        ProgressDialog loadingDialog = new ProgressDialog(this);
        loadingDialog.setTitle("");
        loadingDialog.setMessage("");
        loadingDialog.setIndeterminate(true);
        loadingDialog.setCancelable(false);
        return loadingDialog;
    }

    return super.onCreateDialog(id);
}

private class MyTask extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... arg0) {

            /* Do something expensive here...*/

            /* Start other activity*/
            Intent intent = new Intent(MyActivity.this, OtherActivity.class);
            startActivityForResult(intent, 1000);
        }

        return null;
    }

    protected void onPostExecute(Void arg0) {
        dismissDialog(ID_DIALOG_PROGRESS);
    }
}
}

Most of the time, the exception was thrown from showDialog() call. The other time, the exception was thrown from dismissDialog() call.

Thank you in advance!

How to&Answers:

You’re starting a new activity in doInBackground() before you dismiss the dialog in onPostExecute(), which is probably what is causing the dialog to leak. I would move

Intent intent = new Intent(MyActivity.this, OtherActivity.class);
startActivityForResult(intent, 1000);

to onPostExecute() after the dismissDialog() call and see what happens.

Answer:

It’s also good practise to place a try…catch around

dismissDialog(ID_DIALOG_PROGRESS);

Otherwise you will probably receive random application crashes when under some circumstances the dialog is not available anymore e.g. after screen rotation.