How to execute Async task repeatedly after fixed time intervals
public void callAsynchronousTask() { final Handler handler = new Handler(); Timer timer = new Timer(); TimerTask doAsynchronousTask = new TimerTask() { @Override public void run() { handler.post(new Runnable() { public void run() { try { PerformBackgroundTask performBackgroundTask = new PerformBackgroundTask(); // PerformBackgroundTask this class is the class that extends AsynchTask performBackgroundTask.execute(); } catch (Exception e) { // TODO Auto-generated catch block } } }); } }; timer.schedule(doAsynchronousTask, 0, 50000); //execute in every 50000 ms}
//Every 10000 ms private void doSomethingRepeatedly() { Timer timer = new Timer(); timer.scheduleAtFixedRate( new TimerTask() { public void run() { try{ new SendToServer().execute(); } catch (Exception e) { // TODO: handle exception } } }, 0, 10000); }
You can just a handler:
private int m_interval = 5000; // 5 seconds by default, can be changed laterprivate Handle m_handler;@Overrideprotected void onCreate(Bundle bundle){ ... m_handler = new Handler();}Runnable m_statusChecker = new Runnable(){ @Override public void run() { updateStatus(); //this function can change value of m_interval. m_handler.postDelayed(m_statusChecker, m_interval); }}void startRepeatingTask(){ m_statusChecker.run(); }void stopRepeatingTask(){ m_handler.removeCallback(m_statusChecker);}
But I would recommend you to check this framework: http://code.google.com/intl/de-DE/android/c2dm/ Is a different approach: the server will notify the phone when something is ready (thus, saving some bandwidth and performance:))