without - why we use handler in android




Android, pausing and resuming handler callbacks (2)

Have you tried with:

@Override
public void onPause()
{
  handler.removeCallbacks(Play);
  Soundmanager.autoPause()
}

Ger

I have a handler that I am using as follows:

handler.postDelayed(Play, 1000);

when my application onPause() is called before this is done, I need to pause it and tell it not to perform the "postDelayed" until I resume.

is this possible, or is there an alternative way?

My problem is that when onPause() is called I pause the audio (SoundManager), but if this handler.postDelayed is called after that, the audio will not be paused and will continue to play with my application in the background.

@Override
public void onPause()
{
  Soundmanager.autoPause()
}

but then the postDelayed after 1000ms starts the audio playing again.


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<Message> s = new Stack<Message>();
    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
               // ...
        }
    }
    //...
}




handler