我已经用 Google 搜索过,所有主题都说相同的解决方案 handler.removeCallbacks(null)
或 handler.removeCallbacksAndMessages(null)
。但他们都不适合我。
Handler handler;
Runnable runnable;
@Override
protected void onCreate(Bundle savedInstanceState) {
//...
handler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
time -= 100;
if(time == 0){
Intent i = new Intent(Question.this, WrongAnswer.class);
startActivity(i);
finish();
}
else{
handler.postDelayed(this, 100);
}
}
};
handler.postDelayed(runnable,3000);
//...
}
这里是 Activity 在时间用完之前退出的情况:
if(myAnswer == correctAnswer)
{
Intent i = new Intent(this, CorrectAnswer.class);
startActivity(i);
handler.removeCallbacksAndMessages(null);
finish();
}
最佳答案
您需要先将 runnable 设为全局,然后 handler.removeCallbacks(runnable)
才能正常工作。另外,您可以使用全局变量来检查您是否已经取消(这只是为了安全起见)
private boolean isCancelled = false;
private Runnable mRunnable = new Runnable() {
@Override
public void run() {
if (isCancelled) return;
time -= 100;
if(time == 0){
Intent i = new Intent(Question.this, WrongAnswer.class);
startActivity(i);
finish();
}
else{
handler.postDelayed(this, 100);
}
}
};
然后:
isCancelled = true;
handler.removeCallbacks(mRunnable);
关于java - 我真的无法阻止处理程序!我怎么能够?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35536879/