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

前端 未结 10 1177
遥遥无期
遥遥无期 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: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

提交回复
热议问题