How to set a timer in android

前端 未结 13 1712
天命终不由人
天命终不由人 2020-11-22 06:43

What is the proper way to set a timer in android in order to kick off a task (a function that I create which does not change the UI)? Use this the Java way: http://docs.ora

13条回答
  •  终归单人心
    2020-11-22 07:14

    Probably Timerconcept

    new CountDownTimer(40000, 1000) { //40000 milli seconds is total time, 1000 milli seconds is time interval
    
     public void onTick(long millisUntilFinished) {
      }
      public void onFinish() {
     }
    }.start();
    

    or

    Method 2 ::

    Program the timer

    Add a new variable of int named time. Set it to 0. Add the following code to onCreate function in MainActivity.java.

    //Declare the timer
    Timer t = new Timer();
    //Set the schedule function and rate
    t.scheduleAtFixedRate(new TimerTask() {
    
        @Override
        public void run() {
            //Called each time when 1000 milliseconds (1 second) (the period parameter)
        }
    
    },
    //Set how long before to start calling the TimerTask (in milliseconds)
    0,
    //Set the amount of time between each execution (in milliseconds)
    1000);
    

    Go into the run method and add the following code.

    //We must use this function in order to change the text view text
    runOnUiThread(new Runnable() {
    
        @Override
        public void run() {
            TextView tv = (TextView) findViewById(R.id.main_timer_text);
            tv.setText(String.valueOf(time));
            time += 1;
        }
    
    });
    

提交回复
热议问题