Repeat a task with a time delay?

后端 未结 12 1578
小蘑菇
小蘑菇 2020-11-22 02:14

I have a variable in my code say it is \"status\".

I want to display some text in the application depending on this variable value. This has to be done with a speci

12条回答
  •  天涯浪人
    2020-11-22 02:53

    You should use Handler's postDelayed function for this purpose. It will run your code with specified delay on the main UI thread, so you will be able to update UI controls.

    private int mInterval = 5000; // 5 seconds by default, can be changed later
    private Handler mHandler;
    
    @Override
    protected void onCreate(Bundle bundle) {
    
        // your code here
    
        mHandler = new Handler();
        startRepeatingTask();
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        stopRepeatingTask();
    }
    
    Runnable mStatusChecker = new Runnable() {
        @Override 
        public void run() {
              try {
                   updateStatus(); //this function can change value of mInterval.
              } finally {
                   // 100% guarantee that this always happens, even if
                   // your update method throws an exception
                   mHandler.postDelayed(mStatusChecker, mInterval);
              }
        }
    };
    
    void startRepeatingTask() {
        mStatusChecker.run(); 
    }
    
    void stopRepeatingTask() {
        mHandler.removeCallbacks(mStatusChecker);
    }
    

提交回复
热议问题