Android, pausing and resuming handler callbacks

2019-01-11 19:06发布

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.

3条回答
我只想做你的唯一
2楼-- · 2019-01-11 19:44

Have you tried with:

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

Ger

查看更多
对你真心纯属浪费
3楼-- · 2019-01-11 19:44
public class YourActivity extends AppCompatActivity {

    private static boolean handlerflag=false;
    private Handler handler;
    private Runnable runnable;
    private int myind=0,index=0,count=0;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_activtiy);         
        //oncreate exe only
        handlerflag=true;
        handler = new Handler();
        startyourtime(0);
 }
  private void  startyourtime(int a) {

    myind=0;
    for (index=a; index<10 ;index++) {
            myind++;
            runnable=new Runnable() {
                count++;
                @Override
                public void run() {
                          //your code here
               }
            };handler.postDelayed(runnable, Constants.TIME_LIMIT * myind);

   }
    @Override
    protected void onPause() {
        super.onPause();
        handlerflag=false;
        handler.removeCallbacksAndMessages(null);
    }
    @Override
    protected void onResume() {
        super.onResume();
        if(!handlerflag)
        {
           startyourtime(count);

        }
    }
}
查看更多
Fickle 薄情
4楼-- · 2019-01-11 19:50

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
               // ...
        }
    }
    //...
}
查看更多
登录 后发表回答