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

前端 未结 10 1112
遥遥无期
遥遥无期 2020-11-29 16:54

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

相关标签:
10条回答
  • 2020-11-29 17:30

    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();
    
    0 讨论(0)
  • 2020-11-29 17:32

    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*/ }
    
    0 讨论(0)
  • 2020-11-29 17:40

    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

    0 讨论(0)
  • 2020-11-29 17:44

    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);
    
    0 讨论(0)
  • 2020-11-29 17:44

    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.

    0 讨论(0)
  • 2020-11-29 17:48

    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.

    0 讨论(0)
提交回复
热议问题