What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java?

JavaJavascriptAndroidSettimeout

Java Problem Overview


Can anyone tell me if an equivalent for setInterval/setTimeout exists for Android? Does anybody have any example about how to do it?

Java Solutions


Solution 1 - Java

As always with Android there's lots of ways to do this, but assuming you simply want to run a piece of code a little bit later on the same thread, I use this:

new android.os.Handler(Looper.getMainLooper()).postDelayed(
    new Runnable() {
        public void run() {
            Log.i("tag", "This'll run 300 milliseconds later");
        }
    }, 
300);

.. this is pretty much equivalent to

setTimeout( 
    function() {
        console.log("This will run 300 milliseconds later");
    },
300);

Solution 2 - Java

setInterval()

function that repeats itself in every n milliseconds

Javascript

 setInterval(function(){ Console.log("A Kiss every 5 seconds"); }, 5000);

Approximate java Equivalent

new Timer().scheduleAtFixedRate(new TimerTask(){
    @Override
    public void run(){
       Log.i("tag", "A Kiss every 5 seconds");
    }
},0,5000);

setTimeout()

function that works only after n milliseconds

Javascript

setTimeout(function(){ Console.log("A Kiss after 5 seconds"); },5000);

Approximate java Equivalent

new android.os.Handler().postDelayed(
    new Runnable() {
        public void run() {
            Log.i("tag","A Kiss after 5 seconds");
        }
}, 5000);

Solution 3 - Java

If you're not worried about waking your phone up or bringing your app back from the dead, try:

// Param is optional, to run task on UI thread.     
Handler handler = new Handler(Looper.getMainLooper());
Runnable runnable = new Runnable() {
    @Override
    public void run() {
        // Do the task...
        handler.postDelayed(this, milliseconds) // Optional, to repeat the task.
    }
};
handler.postDelayed(runnable, milliseconds);

// Stop a repeating task like this.
handler.removeCallbacks(runnable);

Solution 4 - Java

Depending on what you actually want to achieve, you should take a look at Android Handlers:

http://developer.android.com/reference/android/os/Handler.html

If you previously used javascript setTimeout() etc to schedule a task to run in the future, this is the Android way of doing it (postDelayed / sendMessageDelayed).

Note that neither Handlers or Timers makes an Android phone wake up from sleep mode. In other words, if you want to schedule something to actually happen even though the screen is off / cpu is sleeping, you need to check out the AlarmManager too.

Solution 5 - Java

The first answer is definitely the correct answer and is what I based this lambda version off of, which is much shorter in syntax. Since Runnable has only 1 override method "run()", we can use a lambda:

this.m_someBoolFlag = false;
new android.os.Handler().postDelayed(() -> this.m_someBoolFlag = true, 300);

Solution 6 - Java

I do not know much about JavaScript, but I think Timers may be what you are looking for.

http://developer.android.com/reference/java/util/Timer.html

From the link:

One-shot are scheduled to run at an absolute time or after a relative delay. Recurring tasks are scheduled with either a fixed period or a fixed rate.

Solution 7 - Java

import java.util.Timer;
import java.util.TimerTask;

class Clock {
    private Timer mTimer = new Timer();

    private int mSecondsPassed = 0;
    private TimerTask mTask = new TimerTask() {
        @Override
        public void run() {
            mSecondsPassed++;
            System.out.println("Seconds passed: " + mSecondsPassed);
        }
    };

    private void start() {
	    mTimer.scheduleAtFixedRate(mTask, 1000, 1000);
    }

    public static void main(String[] args) {
	    Clock c = new Clock();
	    c.start();
    }
}

Solution 8 - Java

I was creating a mp3 player for android, I wanted to update the current time every 500ms so I did it like this

setInterval

private void update() {
    new android.os.Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            long cur = player.getCurrentPosition();
            long dur = player.getDuration();
            currentTime = millisecondsToTime(cur);
            currentTimeView.setText(currentTime);
            if (cur < dur) {
                updatePlayer();
            }

            // update seekbar
            seekBar.setProgress( (int) Math.round((float)cur / (float)dur * 100f));
        }
    }, 500);
}

which calls the same method recursively

Solution 9 - Java

Here's a setTimeout equivalent, mostly useful when trying to update the User Interface after a delay.

As you may know, updating the user interface can only by done from the UI thread. AsyncTask does that for you by calling its onPostExecute method from that thread.

new AsyncTask<Void, Void, Void>() {
		@Override
		protected Void doInBackground(Void... params) {
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// Update the User Interface
		}

	}.execute();

Solution 10 - Java

As always with Android there's lots of ways to do this, but assuming you simply want to run a piece of code on the same thread, I use this:

new Timer().scheduleAtFixedRate(new TimerTask(){
    @Override
    public void run(){
       Log.i("tag", "Hai Codemaker");
    }
},0,1000);

This code will log Hai Codemaker text every one second.

Solution 11 - Java

Kotlin:

You can also use CountDownTimer:

class Timer {
    companion object {
        @JvmStatic
        fun call(ms: Long, f: () -> Unit) {
            object : CountDownTimer(ms,ms){
                override fun onFinish() { f() }
                override fun onTick(millisUntilFinished: Long) {}
            }.start()
        }
    }
}

And in your code:

Timer.call(5000) { /*Whatever you want to execute after 5000 ms*/ }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionkarse23View Question on Stackoverflow
Solution 1 - JavaBen ClaytonView Answer on Stackoverflow
Solution 2 - JavaMidhunView Answer on Stackoverflow
Solution 3 - JavaSharkAlleyView Answer on Stackoverflow
Solution 4 - JavaapanlocoView Answer on Stackoverflow
Solution 5 - JavaneoRileyView Answer on Stackoverflow
Solution 6 - Javanicholas.hauschildView Answer on Stackoverflow
Solution 7 - JavaJeevaView Answer on Stackoverflow
Solution 8 - JavaJeevaView Answer on Stackoverflow
Solution 9 - JavaStephane JAISView Answer on Stackoverflow
Solution 10 - JavaCodemakerView Answer on Stackoverflow
Solution 11 - JavaPayam Roozbahani FardView Answer on Stackoverflow