Activity has leaked window that was originally added

后端 未结 30 3184
野趣味
野趣味 2020-11-21 05:48

What is this error, and why does it happen?

05-17 18:24:57.069: ERROR/WindowManager(18850): Activity com.mypkg.myP has leaked window com.android.internal.pol         


        
30条回答
  •  南笙
    南笙 (楼主)
    2020-11-21 06:11

    here is a solution when you do want to dismiss AlertDialog but do not want to keep a reference to it inside activity.

    solution requires you to have androidx.lifecycle dependency in your project (i believe at the moment of the comment it's a common requirement)

    this lets you to delegate dialog's dismiss to external object (observer), and you dont need to care about it anymore, because it's auto-unsubscribed when activity dies. (here is proof: https://github.com/googlecodelabs/android-lifecycles/issues/5).

    so, the observer keeps the reference to dialog, and activity keeps reference to observer. when "onPause" happens - observer dismisses the dialog, and when "onDestroy" happens - activity removes observer, so no leak happens (well, at least i dont see error in logcat anymore)

    // observer
    class DialogDismissLifecycleObserver( private var dialog: AlertDialog? ) : LifecycleObserver {
        @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
        fun onPause() {
            dialog?.dismiss()
            dialog = null
        }
    }
    // activity code
    private fun showDialog() {
            if( isDestroyed || isFinishing ) return
            val dialog = AlertDialog
                .Builder(this, R.style.DialogTheme)
                // dialog setup skipped
                .create()
            lifecycle.addObserver( DialogDismissLifecycleObserver( dialog ) )
            dialog.show()
    }
    
    

提交回复
热议问题