Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timer and TimerTask in Android

I need a timer for my program. I have written it and it works fine on PC in emulalator program (Android 1.5/2.2). But it doesn't work on the real device (Android 1.5). What am I doing wrong?

TimerTask task = new TimerTask() {
            public void run() {
                if (condition) {
                    myFunc();
                } else {
                    this.cancel();
                }
            }
        };
        Timer timer = new Timer();
        timer.schedule(task, 500, 85);
like image 472
Scit Avatar asked Jun 25 '11 12:06

Scit


People also ask

What is timer and TimerTask in Java?

Timer and TimerTask are java util classes that we use to schedule tasks in a background thread. Basically, TimerTask is the task to perform, and Timer is the scheduler.

What is TimerTask?

TimerTask is an abstract class defined in java. util package. TimerTask class defines a task that can be scheduled to run for just once or for repeated number of time. In order to define a TimerTask object, this class needs to be implemented and the run method need to be overridden.

What is delay and period in Timer Android?

delay - delay in milliseconds before task is to be executed. period - time in milliseconds between successive task executions. (Your IDE should also show it to you automatically) So delay is the time from now till the first execution, and after that it executes every period milliseconds again.

What is the difference between Android timer and a handler to do action every n seconds?

Handler is better than TimerTask . The Java TimerTask and the Android Handler both allow you to schedule delayed and repeated tasks on background threads. However, the literature overwhelmingly recommends using Handler over TimerTask in Android (see here, here, here, here, here, and here).


Video Answer


1 Answers

You need to cancel() timer not the timer task.

like image 55
Jarek Potiuk Avatar answered Oct 05 '22 01:10

Jarek Potiuk