Skip to content Skip to sidebar Skip to footer

Call Web Service In Interval On Background

Application need synchronize data from server in interval (for example every 30min) or manually on background. Result is saved to local database. After sync is done I want remind a

Solution 1:

I would use the AlarmManager and register a BroadcastReceiver. Once the receiver is fired, I will launch an IntentService to download the data in the background.

Configure your alarm:

    AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, MyBroadcast.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    manager.setInexactRepeating(AlarmManager.RTC, 0, AlarmManager.INTERVAL_HALF_HOUR, pendingIntent);

Create a BroadcastReceiver that will get notified when the alarm goes off. Note that I'm using a WakefulBroadcastReceiver so that the device doesn't go to sleep when you're syncing.

class MyBroadcast extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        Intent syncIntent = new Intent();
        syncIntent.setClass(context, DataSyncer.class);
        startWakefulService(context, syncIntent);
    }
}

Next, an IntentService that will download data in the background:

class DataSyncer extends IntentService{

    ...

    @Override
    protected void onHandleIntent(Intent intent) {
       //sync data
       MyBroadcast.completeWakefulIntent(intent);
    }

}

Update: So now that you have your data synced, there are several options to notify Activities and Fragments. You can use a LocalBroadcastManager to broadcast. Take a look at this link for more details.


Solution 2:

Use an AlarmManager to trigger a PendingIntent on a 30 minute interval that starts an IntentService to do your download.

Intent intent = new Intent(context, PollingService.class);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);

AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(
                AlarmManager.RTC,
                System.currentTimeMillis(),
                AlarmManager.INTERVAL_HALF_HOUR,
                pendingIntent
);

When the IntentService is done updating your data, it can send a Broadcast that your Activity/Fragment has registered to listen for to notify it of new data and refresh it's view.

sendBroadcast(new Intent("DATA_UPDATED"));

In your Fragment

getActivity().registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //update UI
        }
    }, new IntentFilter("DATA_UPDATED"));

Post a Comment for "Call Web Service In Interval On Background"