处理程序无法正常工作

时间:2017-08-09 22:55:36

标签: android multithreading android-handler

首先请原谅我,如果我的标题没有很好地描述我的问题,但我找不到更好的问题。

有一个简单的stopWatch应用程序,它有三个按钮开始,停止,重置和一个文本视图来显示时间。 app只有一个这样的活动:

public class StopwatchActivity extends AppCompatActivity {

private int mNumberOfSeconds = 0;
private boolean mRunning = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_stopwatch);
    //if if uncomment this runner method and delete the runner inside onClickStart everything will work find 
    //runner()

}

public void onClickStart(View view){
    mRunning = true;
    runner();
}

public void onClickStop(View view){
    mRunning = false;
}

public void onClickReset(View view){
    mRunning = false;
    mNumberOfSeconds = 0;

}

public void runner(){
    final TextView timeView = (TextView) findViewById(R.id.time_view);
    final Handler handler = new Handler();
    handler.post(new Runnable() {
        @Override
        public void run() {
            int hours = mNumberOfSeconds/3600;
            int minutes = (mNumberOfSeconds%3600)/60;
            int second = mNumberOfSeconds%60;
            String time = String.format("%d:%02d:%02d" , hours , minutes , second );
            timeView.setText(time);
            if (mRunning){
                mNumberOfSeconds++;
            }
            handler.postDelayed(this , 1000);
        }
    });

}
}

我的问题是当我在onClickStart方法中评论runner()并将其放入onCreate方法时,一切正常。但是当我改变上面的代码时,代码仍然在运行,但是在我按下停止按钮然后再次按下启动后,第二个将非常快地增加4或5。 任何人都可以解释一下这两种模式之间的区别是什么?

1 个答案:

答案 0 :(得分:1)

全局声明您的处理程序

public void runner(){
    timeView = (TextView) findViewById(R.id.time_view);
    handler = new Handler();
    runnable = new Runnable() {
        @Override
        public void run() {
            int hours = mNumberOfSeconds/3600;
            int minutes = (mNumberOfSeconds%3600)/60;
            int second = mNumberOfSeconds%60;
            String time = String.format("%d:%02d:%02d" , hours , minutes , second );
            timeView.setText(time);
            if (mRunning){
                mNumberOfSeconds++;
            }
            handler.postDelayed(this , 1000);
        }
    }
    handler.post(runnable);

}

按钮功能

public void onClickStart(View view){
    if(handler != null) {
        //restart the handler to avoid duplicate runnable 
        handler.removeCallbacks(runnable);//or this handler.removeCallbacksAndMessages(null);
    }
    mRunning = true;
    runner();
}

public void onClickStop(View view){
    mRunning = false;
    handler.removeCallbacks(runnable); // this will stop the handler from working
}