0

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;
}
});
whereisSQL
  • 638
  • 2
  • 13
  • 23

1 Answers1

2

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();
}
Community
  • 1
  • 1
corvus
  • 116
  • 3
  • When I insert a null-check before calling cancel() on the timer: It did nothing .. It does not crash the activity because it feels it like null although the blinking is still on – وليد عبد العزيز Aug 17 '15 at 21:36
  • Did you declare the variable "waitTimer" above the switch-block? Otherwise _waitTimer_ will always be null. – corvus Aug 17 '15 at 21:39