Timer Not Stopping In Android
android
Solution
timer = new Timer("Message Timer");
Here your object `timer` is not a `static` so `timer.cancel();` will cancel another instance of the Timer class. I suggest you to create a static instance variable of Timer Class on the top of the class, like below,
private static Timer timer;
Problem
THE PROBLEM I am having problems stopping the Timer whilst developing in android. The timer is already null when it comes to stopping it. I then move the timer initialisation to outside of a method just like the TimerTask which solves the null problem but still doesn't cancel when `timer.cancel();` is called upon it. The code below is an example of the timer already being null when it comes to stopping the recording. TimerTask My `TimerTask` is initialized inside the class but outside of a method and the codes below... ``` private TimerTask task = new TimerTask() { @Override public void run() { Log.e("TRACK_RECORDING_SERVICE","Timer Running"); } }; ``` Timer & Timer Start I then have a startRecroding method which is called when I want to start the timer... ``` public void startRecording(){ timer = new Timer("Message Timer"); timer.scheduleAtFixedRate(this.task, 0, 1000); } ``` Timer Stop I then call the below method when I want to stop the timer... ``` public void stopRecording() { if (timer != null) { timer.cancel(); timer = null; } else { Log.e("TRACK_RECORDING_SERVICE","Timer already null."); } } ``` Any help would be much appreciated.