定时器不会被timer.cancel()停止。它会导致活动崩溃

时间:2015-08-17 20:49:41

标签: android flash blink

下面是我的定时器代码,使闪光灯闪烁。

这是它背后的逻辑:

case MotionEvent.ACTION_DOWN应启动闪光灯。 case MotionEvent.ACTION_UP应停止闪光

当我使用waitTimer.cancel()时;程序崩溃了。

final Button button = (Button) findViewById(R.id.myImageView);
button.setOnTouchListener(new OnTouchListener() {

@Override
 public boolean onTouch(View v, final MotionEvent event) {
    switch (event.getAction()) {

        case MotionEvent.ACTION_DOWN:

        //Flash ON
        CountDownTimer waitTimer;
        waitTimer = new CountDownTimer(3000, 25) {

        public void onTick(long millisUntilFinished) {
            final Parameters p = camera.getParameters();
            if (!isLighOn) {
                p.setFlashMode(Parameters.FLASH_MODE_ON);
                p.setFlashMode(Parameters.FLASH_MODE_TORCH);
                camera.setParameters(p);
                isLighOn = true;
            } else {
                p.setFlashMode(Parameters.FLASH_MODE_OFF);
                camera.setParameters(p);
                isLighOn = false;
            }
        }

        public void onFinish() {
            final Parameters pp = camera.getParameters();
            pp.setFlashMode(Parameters.FLASH_MODE_OFF);
            camera.setParameters(pp);
            isLighOn = false;  
            isPlaying = false;
            }
        }.start();

    }
  }     
}

break;

case MotionEvent.ACTION_UP:

    //Flash OFF
    waitTimer.cancel();
    waitTimer = null;
    final Parameters pp = camera.getParameters();
    pp.setFlashMode(Parameters.FLASH_MODE_OFF);
    camera.setParameters(pp);
    isLighOn = false;
    }
return false;
}
});

1 个答案:

答案 0 :(得分:2)

看起来像这样:https://stackoverflow.com/a/10810847/5220092

您应该在switch-block上面写下声明:

CountDownTimer waitTimer = null;
switch(event.getAction()){
...
}

并在定时器上调用cancel()之前插入空值检查:

if(waitTimer != null){
waitTimer.cancel();
}