What is the equivalent to a JavaScript setInterval/setTimeout in Android/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);
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);
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);