问题
@Override
public void onUserInteraction() {
Handler handler = new Handler();
handler.postDelayed(new Runnable () {
public void run() {
finish();
}
}, 5000);
handler.removeCallbacks(null);
}
I am trying to run the handler when the OnCreate method is called. I would then like to cancel the handler and call it again (restart the handler) when I receive user interaction.
How would I do this?
Thanks in advance
回答1:
You can use a boolean object, example:
@Override
public void onUserInteraction() {
isStarted = true;
Handler handler = new Handler();
handler.postDelayed(new Runnable () {
public void run() {
if(isStarted){
finish();
}
}
}, 5000);
}
or you can make something like this:
Runnable myRunnable = new Runnable() {
@Override
public void run() {
finish();
}
};
public static Handler myHandler = new Handler();
private static final int TIME_TO_WAIT = 5000;
@Override
public void onUserInteraction() {
restart();
}
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);
}
回答2:
Store the runnable and handler in a field and reuse them
Handler handler;
Runnable runnable = new Runnable () {
public void run() {
finish();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler = new Handler();
handler.postDelayed(runnable, 5000);
}
@Override
public void onUserInteraction() {
handler.removeCallbacks(null);
handler.postDelayed(runnable, 5000);
}
回答3:
Create a handler and keep its reference as global variable
private Runnable runnable;
private Handler newHandler;
newHandler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
try {
//update UI
newHandler.postDelayed(runnable,100);
} catch (Exception e) {
e.printStackTrace();
}
}
};
newHandler.post(runnable);
And on user Interaction
@Override
public void onUserInteraction() {
super.onUserInteraction();
newHandler.removeCallbacks(runnable);
//Do some task
if(//task done){
newHandler.postDelayed(runnable,100);
}
}
回答4:
It was not work for me until I used Handler's removeCallbacksAndMessages(Object token)
method.
On kotlin
private var restartingHandler = Handler()
private var runnable: () -> Unit = {}
fun start() {
restartingHandler.postDelayed(runnable, 5000L)
}
fun restart() {
restartingHandler.removeCallbacks(runnable)
restartingHandler.removeCallbacksAndMessages(null)
restartingHandler.postDelayed(runnable, 5000L)
}
fun stop() {
restartingHandler.removeCallbacks(runnable)
restartingHandler.removeCallbacksAndMessages(null)
}
来源:https://stackoverflow.com/questions/46403060/restart-a-handler-postdelayed-in-java