处理程序不能正常工作
首先,如果我的标题没有很好地描述我的问题,但我找不到更好的问题。处理程序不能正常工作
有一个简单的秒表应用程序,它有三个按钮开始,停止,重置和显示时间的文本视图。应用程序只有一个这样的活动:
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方法,并把它在onCreate方法一切正常。但是当我更改上面的代码时,代码仍在运行,但是在按停止按钮之后,再次按下启动按钮,第二个代码将以非常快的速度增加4或5。 任何人都可以解释我有什么区别这两种模式?
声明你处理全球
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
}
当我想运行此代码,并在应用程序开始后。在按下开始按钮后,空指针异常将抛出 –
尝试在空对象引用 –
上调用虚拟方法'void android.os.Handler.removeCallbacks(java.lang.Runnable)'我修复了它。只是在声明它时实例化Handler。谢谢 –
你杀得了亚军,所以当你重新启动定时器,将创建一个季军。当你只测试mRunning的价值时,第一名选手和第二名选手都会重新开始计时。 – Nick
@Nick为什么当我把runner()放在onCreate代码里面的时候会发现。我认为这是相同的场景 –
因为onCreate只执行一次,所以你只能启动跑步者的一个实例。 – Nick