开发者

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

Can anyone tell me if an equivalent for setInterval/setTimeout exists for Andro开发者_运维百科id? Does anybody have any example about how to do it?


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);


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.


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);


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.


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();
    }
}


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


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();


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.


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*/ }


In case someone wants -

Kotlin equivalent to JavaScript setInterval/setTimeout

IMPORTANT: Remember to import android.os.Handler. Don't get mistaken by java.util.logging.Handler

Timeout equivalent

Javascript: setTimeout()

setTimeout(function(){
   // something that can be run.
}, 1500);

Kotlin: runOnTimeout()

inline fun runOnTimeout(crossinline block: () -> Unit, timeoutMillis: Long) {
    Handler(Looper.getMainLooper()).postDelayed({
        block()
    }, timeoutMillis)
}

Kotlin: Calling

runOnTimeout({
   // something that can be run.
}, 1500)

Timeinterval equivalent

Javascript: setInterval()

setInterval(function(){
   // something that can be run.
}, 1500);

Kotlin: runOnInterval()

inline fun runOnInterval(crossinline block: () -> Unit, interval: Long) {
    val runnable = object : Runnable {
        override fun run() {
            block()
            handler.postDelayed(this, interval)
        }
    }
    handler.post(runnable)
}

Kotlin: Calling

runOnInterval({
   // something that can be run.
}, 1500)



Cancellable timeout and interval

If you want to use custom handler so that you can cancel the runnable, then you can use following codes.

Timeout

inline fun runOnTimeout(crossinline block: () -> Unit, timeoutMillis: Long) {
    runOnTimeout(Handler(Looper.getMainLooper()), block, timeoutMillis)
}

inline fun runOnTimeout(handler: Handler, crossinline block: () -> Unit, timeoutMillis: Long): Runnable {
    val runnable = Runnable { block() }
    handler.postDelayed(runnable, timeoutMillis)
    return runnable
}

Timeout: Calling

runOnTimeout({
    // something that can be run.
}, 1500)

// OR

val runnable = runOnTimeout(mHandler, {
    // something that can be run.
}, 1500)
// to cancel
mHandler.removeCallbacks(runnable)

Interval

inline fun runOnInterval(crossinline block: () -> Unit, interval: Long) {
    runOnInterval(Handler(Looper.getMainLooper()), block, interval)
}

inline fun runOnInterval(handler: Handler, crossinline block: () -> Unit, interval: Long): Runnable {
    val runnable = object : Runnable {
        override fun run() {
            block()
            handler.postDelayed(this, interval)
        }
    }
    handler.post(runnable)
    return runnable
}

Interval: Calling

runOnInterval({
    // something that can be run.
}, 1500)

// OR

val runnable = runOnInterval(mHandler, {
    // something that can be run.
}, 1500)
// to cancel
mHandler.removeCallbacks(runnable)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜