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();
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.