How to repeat a task after a fixed amount of time in android?

后端 未结 5 1799
耶瑟儿~
耶瑟儿~ 2020-12-08 02:41

I want to repeatedly call a method after every 5-seconds and whenever I wish to to stop the repeated call of the method I may stop or restart the repeated call of the method

相关标签:
5条回答
  • 2020-12-08 03:16

    use TimerTask to call after specific time interval

        Timer timer = new Timer();
        timer.schedule(new UpdateTimeTask(),1, TimeInterval);
    

    and

      class UpdateTimeTask extends TimerTask {
    
            public void run() 
               {        
                // do stufff
               }
    
            }
    
    0 讨论(0)
  • 2020-12-08 03:17

    Use a Handler in the onCreate() method. Its postDelayed() method causes the Runnable to be added to the message queue and to be run after the specified amount of time elapses (that is 0 in given example). Then this will queue itself after fixed rate of time (1000 milliseconds in this example).

    Refer this code :

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        android.os.Handler customHandler = new android.os.Handler();
        customHandler.postDelayed(updateTimerThread, 0);
    }
    
    private Runnable updateTimerThread = new Runnable()
    {
        public void run()
        {
            //write here whaterver you want to repeat
            customHandler.postDelayed(this, 1000);
        }
    };
    
    0 讨论(0)
  • 2020-12-08 03:18

    You have to put this code inside the activity you want to call every 5 seconds

    final Runnable tarea = new Runnable() {   public void run() {
    hola_mundo();//the operation that you want to perform }}; 
    ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor();
    timer.scheduleAtFixedRate(tarea, 5, 5, TimeUnit.SECONDS);
    
    0 讨论(0)
  • 2020-12-08 03:30

    Do it in Android's way with the help of Handler.

    Declare a Handler which does not leak Memory

    /**
         * Instances of static inner classes do not hold an implicit
         * reference to their outer class.
         */
        private static class NonLeakyHandler extends Handler {
            private final WeakReference<FlashActivity> mActivity;
    
            public NonLeakyHandler(FlashActivity activity) {
                mActivity = new WeakReference<FlashActivity>(activity);
            }
    
            @Override
            public void handleMessage(Message msg) {
                FlashActivity activity = mActivity.get();
                if (activity != null) {
                    // ...
                }
            }
        }
    

    Declare a runnable which handle your task

       private Runnable repeatativeTaskRunnable = new Runnable() {
            public void run() {
                new Handler(getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
    
             //DO YOUR THINGS
            }
        };
    

    Initialize handler object in your Activity/Fragment

    //Task Handler
    private Handler taskHandler = new NonLeakyHandler(FlashActivity.this);
    

    Repeat task after fix time interval

    taskHandler.postDelayed(repeatativeTaskRunnable , DELAY_MILLIS);

    Stop repetition

    taskHandler .removeCallbacks(repeatativeTaskRunnable );

    0 讨论(0)
  • 2020-12-08 03:36

    Set repeated task using this:

    //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);
    

    and if you wanted to cancel the task simply call t.cancel() here t is your Timer object

    and you can also check comment placed below your answer they have given brief information about that.

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