How to perform an Async task again after fixed intervals

How to make the Async task run several times after a certain time interval in the same way as the Timer ... In fact, I am developing an application that will automatically download all the latest unread greetings from the server, and for this I need to check for updates from the server after some fixed time intervals .... I know that this can be done easily with a timer, but I want to use an async task, which, in my opinion, is more efficient for Android applications.

+51
android android-asynctask android-service timertask
Jun 30 '11 at 8:20
source share
4 answers
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 } 
+105
Jun 30 '11 at 8:52
source share
  //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); } 
+6
Feb 26 '14 at 13:33
source share

You can just handler:

 private int m_interval = 5000; // 5 seconds by default, can be changed later private Handle m_handler; @Override protected 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 that you check this structure: http://code.google.com/intl/de-DE/android/c2dm/ . Another approach: the server will notify the phone when something is ready (thus preserving some bandwidth and performance :))

+2
Jun 30 '11 at 8:25
source share

Wouldn't it be more efficient to create a service and schedule it through the alarm manager?

+2
Jul 12 '12 at 5:10
source share



All Articles