Search code examples
androidflashblink

Timer does not stop by timer.cancel(). It causes crashing the activity


Below is my timer code to make flash led blink.

This is the logic behind it:

case MotionEvent.ACTION_DOWN should start the flash. case MotionEvent.ACTION_UP should stop the flash

When I use waitTimer.cancel(); the program crashes.

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;
}
});

Solution

  • It seems to be the same like this: https://stackoverflow.com/a/10810847/5220092

    You should write the declaration above your switch-block:

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

    and insert a null-check before calling cancel() on the timer:

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