Android, pausing and resuming handler callbacks

前端 未结 5 1163
遥遥无期
遥遥无期 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:54

    You need to subclass Handler and implement pause/resume methods as follows (then just call handler.pause() when you want to pause message handling, and call handler.resume() when you want to restart it):

    class MyHandler extends Handler {
        Stack s = new Stack();
        boolean is_paused = false;
    
        public synchronized void pause() {
            is_paused = true;
        }
    
        public synchronized void resume() {
            is_paused = false;
            while (!s.empty()) {
                sendMessageAtFrontOfQueue(s.pop());
            }
        }
    
        @Override
        public void handleMessage(Message msg) {
            if (is_paused) {
                s.push(Message.obtain(msg));
                return;
            }else{
                   super.handleMessage(msg);
                   // otherwise handle message as normal
                   // ...
            }
        }
        //...
    }
    

提交回复
热议问题