Search code examples
androidandroid-intentandroid-alertdialogandroid-night-mode

Activity has leaked IntentReceiver AutoNightModeManager registered on AlertDialog creation


I have an activity with an AlertDialog created on the onCreate method.

When the activity is destroyed, I get this exception:

E/ActivityThread: Activity com.materight.turkdroid.ui.activities.LoginActivity has leaked IntentReceiver androidx.appcompat.app.AppCompatDelegateImpl$AutoNightModeManager$1@18c886c that was originally registered here. Are you missing a call to unregisterReceiver()?
    android.app.IntentReceiverLeaked: Activity com.materight.turkdroid.ui.activities.LoginActivity has leaked IntentReceiver androidx.appcompat.app.AppCompatDelegateImpl$AutoNightModeManager$1@18c886c that was originally registered here. Are you missing a call to unregisterReceiver()?
        at android.app.LoadedApk$ReceiverDispatcher.<init>(LoadedApk.java:1429)
        at android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:1210)
        at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1476)
        at android.app.ContextImpl.registerReceiver(ContextImpl.java:1449)
        ...
        at com.materight.turkdroid.ui.activities.LoginActivity.onCreate(LoginActivity.java:74)
        ...

The line 74 where the error is thrown is where the dialog is created:

        pendingDialog = new MaterialAlertDialogBuilder(this)
                .setCancelable(false)
                .setTitle(R.string.pending_purchase_title)
                .setMessage(R.string.pending_purchase_content)
                .setPositiveButton(R.string.close, (d, which) -> finishAffinity())
                .create();

I've already tried to add pendingDialog.dismiss() in onDestroy, finish and finishAffinity methods with no results. The dialog is not always shown, so maybe the dismiss method doesn't work correctly in this case?

What cause this exception and how can I solve it?

Thank you!


Solution

  • After a lot of trials, I've finally found a solution.

    Symply by using finishAffinity() instead of finish() to close the current activity the issue disappeared.