0

I have this Handler variable in my activity that I need to pass to a third party class.

private val handler =
        Handler(Handler.Callback { msg ->
            when (msg.what) {
                MESSAGE_READ -> {
                    val readBuf = msg.obj as ByteArray
                    val readMessage = String(readBuf, 0, msg.arg1)
                    val builder = AlertDialog.Builder(this)
                    builder.setMessage("Are you sure you want to pay $readMessage?")
                    builder.setPositiveButton("YES") { dialog, which ->
                        doCardTransaction(readMessage)
                        dialog.cancel()
                    }.setNegativeButton("NO") {
                            dialog, which -> dialog.dismiss()
                    }
                    builder.show()
                }
            }
            false
        })

I am able to see the dialog when i get the callback in the first launch of the app, but when i cancel the app, open it again. I get the crash

android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@fa03400 is not valid; is your activity running?

despite the fact i can interact with with the activity normally before the crash.

I am already trying to remove the callback and messages of the handler in onDestroy like this

override fun onDestroy() {
    super.onDestroy()

    handler.removeCallbacksAndMessages(null)

    chatController?.stop()
}

What can possibly be wrong and what can I do?

Bolaji
  • 556
  • 1
  • 6
  • 11

1 Answers1

0

Should be use runOnUiThread {...runnable...} to show the dialog, because your dialog at in a Handler. That's maybe not a UiThread.

dinhlam
  • 708
  • 3
  • 14
  • I have tried that too didnt work for me. The main issue I cant figure out is the activity's isFinishing is true even before it get to the crash site. – Bolaji Jun 12 '20 at 01:25