我真的无法阻止处理程序!我怎么能够?

时间:2016-02-21 13:43:02

标签: java android handler runnable

我已经使用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);

    //...
}

以下是活动在时间用完之前退出的情况:

if(myAnswer == correctAnswer)
{
    Intent i = new Intent(this, CorrectAnswer.class);
    startActivity(i);
    handler.removeCallbacksAndMessages(null);
    finish();
}

1 个答案:

答案 0 :(得分:0)

您需要在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);