Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
705 views
in Technique[技术] by (71.8m points)

android - How to change/reset handler post delayed time?

I'm using postDelayed method of the Handler in order to perform an action after certain amount of time:

private static int time_to_wait = 2000;

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
  public void run() {
    // Make Action
  }
}, time_to_wait);

now in the middle of the waiting time i want to change the value of the remaining milliseconds due to some processing results, let's say it now waited 1000 ms and i want to make it begins to count from 2000 again, So, i set the time_to_wait value to 2000 but it doesn't take that in count as it only takes the var value (2000) and just waits that time regardless changing the time_to_wait value to any other value.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

this can be achieved by easily create a runnable that will be displayed by the handler, then creating the handler as static member, finally when you want to stop it just remove the callback of your created runnable, and if you want to restart it you have to remove the callback and assign it again:

Runnable myRunnable = new Runnable() {
    @Override
    public void run() {
        // your code here
    }
};

public static Handler myHandler = new Handler();
private static final int TIME_TO_WAIT = 2000;

public void start() {
    myHandler.postDelayed(myRunnable, TIME_TO_WAIT);
}

public void stop() {
    myHandler.removeCallbacks(myRunnable);
}

public void restart() {
    myHandler.removeCallbacks(myRunnable);
    myHandler.postDelayed(myRunnable, TIME_TO_WAIT);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...