How to run an async task for every x mins in android?

前端 未结 9 1077
长发绾君心
长发绾君心 2020-11-27 12:28

how to run the async task at specific time? (I want to run it every 2 mins)

I tried using post delayed but it\'s not working?

    tvData.postDelayed         


        
9条回答
  •  不知归路
    2020-11-27 13:22

    You can use handler if you want to initiate something every X seconds. Handler is good because you don't need extra thread to keep tracking when firing the event. Here is a short snippet:

    private final static int INTERVAL = 1000 * 60 * 2; //2 minutes
    Handler mHandler = new Handler();
    
    Runnable mHandlerTask = new Runnable()
    {
         @Override 
         public void run() {
              doSomething();
              mHandler.postDelayed(mHandlerTask, INTERVAL);
         }
    };
    
    void startRepeatingTask()
    {
        mHandlerTask.run(); 
    }
    
    void stopRepeatingTask()
    {
        mHandler.removeCallbacks(mHandlerTask);
    }
    

    Note that doSomething should not take long (something like update position of audio playback in UI). If it can potentially take some time (like downloading or uploading to the web), then you should use ScheduledExecutorService's scheduleWithFixedDelay function instead.

提交回复
热议问题