Android, pausing and resuming handler callbacks

前端 未结 5 1152
遥遥无期
遥遥无期 2020-12-03 11:50

I have a handler that I am using as follows:

handler.postDelayed(Play, 1000);

when my application onPause() is called before this is done,

5条回答
  •  既然无缘
    2020-12-03 11:57

    Modifying the answer given by CpcCrunch. There handleMessage not worked for me, so instead of it using dispatchMessage. Note: Below code is written in Kotlin:

    class CustomHandler: Handler() {
    
        var s = Stack()
        var is_paused = false
    
        @Synchronized
        fun pause() {
            is_paused = true
        }
    
        @Synchronized
        fun resume() {
            is_paused = false
            while (!s.empty()) {
                sendMessageAtFrontOfQueue(s.pop())
            }
        }
    
        override fun dispatchMessage(msg: Message?) {
            if (is_paused) {
                s.push(Message.obtain(msg))
                return
            } else {
                super.dispatchMessage(msg)
            }
        }
    }
    

提交回复
热议问题