下面是我的定时器代码,使闪光灯闪烁。
这是它背后的逻辑:
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;
}
});
答案 0 :(得分:2)
看起来像这样:https://stackoverflow.com/a/10810847/5220092
您应该在switch-block上面写下声明:
CountDownTimer waitTimer = null;
switch(event.getAction()){
...
}
并在定时器上调用cancel()之前插入空值检查:
if(waitTimer != null){
waitTimer.cancel();
}