0

I have 2 activity in activity2 i have a timer when activity create timer is started in activity on_Destroy i put timer_task.cancel(); but When opened the activity2 for the second time is create new timer task and not Canceled or destroyed the last timer and 2 timer is while be run in one activity

my code

    private  TimerTask mTimerTask;
private void doTimerTask(){
    nCounter = 4;

    qtimer.setMax(20);

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

    mTimerTask = new TimerTask() {
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    Log.d("Timerrrr",nCounter+"");
                    if(nCounter<1){
                        Finished();
                    }else {
                        qtimer.setProgress(nCounter);
                        nCounter--;
                    }
                }
            });
        }};

    // public void schedule (TimerTask task, long delay, long period)
    t.schedule(mTimerTask, 0, 1000);  //

}

private void stopTask() {

    if (mTimerTask != null) {
        Log.d("nCounter canceled",nCounter+"");
        mTimerTask.cancel();
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    mTimerTask.cancel();
    MainActivity.this.finish();
}
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Android
  • 31
  • 1
  • 6

1 Answers1

0

Try This...

public void stopTimerTask(View v) {       
    //stop the timer, if it's not already null
    if (mTimerTask != null) {
        mTimerTask.cancel();
        mTimerTask = null;
    }
}

And Where do u call your stopTask() method?

And I suggest don't put mTimerTask.cancel(); in onDestroy(), but put it in onStop().

I hope this helps you.

User
  • 4,023
  • 4
  • 37
  • 63
zephyr
  • 665
  • 6
  • 19
  • Thanks I used this before, but it is not working. When the activity is destroyed, the timer is also stopped, but when the activity is called for the second time Timer initialized twice – Android Jun 29 '17 at 07:31
  • did you also try with putting in onStop()? – zephyr Jun 30 '17 at 06:49
  • yes i put it in (onstop, onDestroy, onPressBack) , i used System.exit(0) and is worked but is not true way – Android Jul 01 '17 at 04:15