Android/Java 中 JavaScript setInterval/setTimeout 的等价物是什么?

发布于 2024-10-14 17:54:11 字数 72 浏览 5 评论 0原文

谁能告诉我 Android 上是否存在 setInterval/setTimeout 的等效项?有人有关于如何做到这一点的例子吗?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

倾城月光淡如水﹏ 2024-10-21 17:54:11

与往常一样,Android 有很多方法可以做到这一点,但假设您只是想稍后在同一个线程上运行一段代码,我使用这个:

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

.. 这几乎相当于

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

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);
白云不回头 2024-10-21 17:54:11

setInterval()

函数每 n 毫秒重复一次

Javascript

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

近似 java 等效

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

setTimeout()

函数,仅有效n 毫秒后

Javascript

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

近似 java 等价

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

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);
〃安静 2024-10-21 17:54:11

如果您不担心唤醒手机或让应用程序起死回生,请尝试:

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

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);
帅气尐潴 2024-10-21 17:54:11

根据您实际想要实现的目标,您应该查看 Android 处理程序:

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

如果您之前使用 javascript setTimeout() 等来安排任务在将来运行,这就是 Android 的执行方式(postDelayed / sendMessageDelayed)。

请注意,处理程序或计时器都不会使 Android 手机从睡眠模式中唤醒。换句话说,如果你想安排一些实际发生的事情,即使屏幕关闭/CPU 正在睡眠,你也需要检查 AlarmManager。

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.

羁〃客ぐ 2024-10-21 17:54:11

第一个答案绝对是正确的答案,也是我基于此 lambda 版本的基础,它的语法要短得多。由于 Runnable 只有 1 个重写方法“run()”,我们可以使用 lambda:

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

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);
一城柳絮吹成雪 2024-10-21 17:54:11

我对 JavaScript 不太了解,但我认为计时器可能就是您正在寻找的。

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

来自链接:

一次性计划在绝对时间或相对延迟后运行。重复任务按固定周期或固定速率进行安排。

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.

佼人 2024-10-21 17:54:11
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();
    }
}
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();
    }
}
蓝礼 2024-10-21 17:54:11

我正在为 android 创建一个 mp3 播放器,我想每 500ms 更新一次当前时间,所以我像

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

那样递归地调用相同的方法

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

寄风 2024-10-21 17:54:11

这是一个 setTimeout 等效项,在尝试更新用户界面时最有用
延迟之后。

如您所知,更新用户界面只能通过 UI 线程完成。
AsyncTask 通过从该线程调用其 onPostExecute 方法来为您完成此操作。

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

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();
抚笙 2024-10-21 17:54:11

与 Android 一样,有很多方法可以做到这一点,但假设您只是想在同一个线程上运行一段代码,我使用这个:

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

此代码将每秒记录 Hai Codemaker 文本。

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.

北方的巷 2024-10-21 17:54:11

如果有人想要 -

Kotlin 相当于 JavaScript setInterval/setTimeout

重要:请记住导入 android.os.Handler。不要被 java.util.logging.Handler

超时等效

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 等价

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)



可取消的超时和间隔

如果你想使用自定义处理程序,以便您可以取消可运行,然后您可以使用以下代码。

超时

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
}

超时:呼叫

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

// OR

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

间隔

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
}

间隔:呼叫

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

// OR

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

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)
南薇 2024-10-21 17:54:11

Kotlin:

您还可以使用 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()
        }
    }
}

并在您的代码中:

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

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*/ }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文