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

后端 未结 5 1807
耶瑟儿~
耶瑟儿~ 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: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 mActivity;
    
            public NonLeakyHandler(FlashActivity activity) {
                mActivity = new WeakReference(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 );

提交回复
热议问题