How to Solve WindowLeaked error

For my long-term project, I encountered a WindowLeaked error in Android Java. Fortunately, with the help of online resources, I was able to find a solution.

To provide some context: the error occurred while I was attempting to hide a dialog that had been briefly displayed as the activity was finishing. Initially, I believed the issue would be nearly impossible to resolve—but eventually, I found a way. Here’s how.

android.view.WindowLeaked: Activity ... has leaked window DecorView...

This happens because i was trying to dialog.show() after the Activity is already finishing or destroyed — so Android can’t attach the dialog to a valid window.

Why this happens:

Even though I was checking:

if (activity != null && !activity.isFinishing() && !activity.isDestroyed())

The timing is critical. Between this check and dialog.show(), the Activity can still finish or be destroyed — especially if this code runs in onCreate() or during a lifecycle transition.

From my stack trace:

at com.sample.util.CameraPermission.checkPermission(CameraPermissionClass.java:172)
at com.sample.activity.QRResultActivity.onCreate(CmaeraResultActivity.java:69)

I wascheckPermission() directly inside onCreate(), which is way too early to show a dialog — the activity’s window isn’t fully attached yet!

Solution: Delay the dialog slightly using Handler

Wrap the dialog.show() call in a Handler with a short delay, e.g. 300ms:

AlertDialog dialog = builder.create();

new Handler(Looper.getMainLooper()).postDelayed(() -> {
    if (activity != null && !activity.isFinishing() && !activity.isDestroyed()) {
        dialog.show();
    } else {
        Log.w("PERMISSION_DIALOG", "Activity no longer valid for showing dialog");
    }
}, 300); // wait until Activity is stable

This allows the activity to fully attach its window before showing the dialog.

Bonus tip: Also avoid dialog.show() in onCreate() or immediately after requestPermissions()

If you’re launching the permission request and showing a custom dialog at the same time, the system may reject one of them — or leak the dialog if the activity finishes after a denial.

Summary

ProblemFix
Dialog shown too early in onCreate()Delay it using Handler.postDelayed()
Activity finishes before dialog.show()Check isFinishing() and isDestroyed() again inside the delayed block
Dialog overlaps system permissionAvoid showing both at the same time

Leave a Reply

Your email address will not be published. Required fields are marked *