Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent to javax.swing.Timer in Android

Is there something that looks like the javax.swing.Timer on Android. I know how to create own Threads, but is there something that is like the swing-timer?

like image 365
SlowDeep Avatar asked Aug 31 '11 16:08

SlowDeep


People also ask

What is javax swing timer?

A Swing timer (an instance of javax. swing. Timer ) fires one or more action events after a specified delay. Do not confuse Swing timers with the general-purpose timer facility in the java. util package.

Can we use Java swing in Android Studio?

Luckily, there's an app for that. AjaxSwing allows you to convert any java Swing application to a web application so you can then run it on iOS and Android devices.

What is timer in Android Studio?

A facility for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals. Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks, sequentially.


2 Answers

The main point of javax.swing.Timer is that it executes tasks on GUI thread (EDT - event dispatching thread). This makes it safe to manipulate Swing components.

In Android there is also EDT and you should only manipulate GUI elements on EDT. To delay your code and then run it on EDT use view.postDelayed(runnable).

like image 28
Peter Knego Avatar answered Nov 08 '22 19:11

Peter Knego


You are probably looking for the class android.os.CountDownTimer

You can inherit the class like this:

class MyTimer extends CountDownTimer
{
    public MyTimer(int secsInFuture) {
        super(secsInFuture*1000, 1000); //interval/ticks each second.
    }

    @Override
    public void onFinish() {
        Log.d("mytag","timer finished!");
    }

    @Override
    public void onTick(long millisUntilFinished) {
        //fired on each interval
        Log.d("mytag","tick; " + millisUntilFinished + " ms left");
    }
}
like image 172
poplitea Avatar answered Nov 08 '22 20:11

poplitea