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

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

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

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

    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().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);
    
    0 讨论(0)
提交回复
热议问题