Can anyone tell me if an equivalent for setInterval/setTimeout exists for Android? Does anybody have any example about how to do it?
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();
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*/ }
I was creating a mp3 player for android, I wanted to update the current time every 500ms so I did it like this
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
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);
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.
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.