user1650281
user1650281

Reputation: 195

Android: How to schedule a Background Service to run repeatedly

I have a AsyncTask in a Service which gets RSS feeds and stores them in the SQLiteDatabase. The service is started from the main Activity. I need the AsyncTask to be executed say after every 4 hours or so to pull the RSS feeds. I tried using the TimerTask as below but this does not seem to be working. The background task is run just once. Any ideas on how to best implement this scenario/any alternatives?

public class FeedReader extends Service{

    private void getFeedsRegularly() {
        timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
        handler.post(new Runnable() {

        @Override
        public void run() {
            new BgTask().execute(feedURL);

        }
            });
            }
    }, 0, UPDATE_INTERVAL);
    }

    private class BgTask extends AsyncTask<...> 
    {...}
}

Upvotes: 2

Views: 1665

Answers (1)

Raghav Sood
Raghav Sood

Reputation: 82533

For such a set schedule, you should use AlarmManager. You can use it to set your app to run every 4 hours.

This is not only convenienti, but will also improve battery performance, as your app isn't continuously running in the background, just to make the AsyncTask every four hours. Instead, Android will run your app when the time is right, and you can do your work, and then wait for the alarm to go off again.

Upvotes: 2

Related Questions