Search code examples
javaandroidhttpalarmmanagerscheduledexecutorservice

Optimal way for a daily network operation


I am kinda confused at the moment. What is the "correct" / "optimal" way for a daily network operation in an android app? Pseudocode:

If newDay
    HTTP Request to server
    If responseOfRequest equals something
        Do something
    If HTTP Request is unsuccessfull (no internet, server down, ...)
        Try again in 1 hour

How can I achieve that? I thought about a JobService but my minSDK is below Android 5.

Cheers, DDerTyp


Solution

  • What you need is a service to run the logic in the background and an alarm.

    A little bit of theory first:

    https://developer.android.com/training/scheduling/alarms.html#tradeoffs

    A repeating alarm is a relatively simple mechanism with limited flexibility. It may not be the best choice for your app, particularly if you need to trigger network operations. A poorly designed alarm can cause battery drain and put a significant load on servers. If you own the server that is hosting your app's data, using Google Cloud Messaging (GCM) in conjunction with sync adapter is a better solution than AlarmManager.

    https://developer.android.com/training/sync-adapters/running-sync-adapter.html

    By default, all alarms are canceled when a device shuts down.

    You will need to set up the alarm somewhere in your app, at the beginning, but saving a flag because you don't want to set up this alarm every time the user opens the app

    if (!appSettings.isAlarmSetUp()) {
        final AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
        final Intent i = new Intent(context, CustomService.class);
        final Intent intentNotRepeat = new Intent(context, CustomService.class);
        final PendingIntent pi = PendingIntent.getService(context, 0, i, 0);
    
        am.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + AlarmManager.INTERVAL_HALF_HOUR, AlarmManager.INTERVAL_DAY, pi);
    
        appSettings.setAlarmSetUp(true);
    }
    

    Here more info about alarms: https://developer.android.com/training/scheduling/alarms.html#type

    As you can see, this alarm is waking up a CustomService, where you will do all your logic

    public class CustomService extends IntentService {
    
        public CustomService(String name) {
            super(name);
        }
    
        @Override
        protected void onHandleIntent(Intent intent) {
            // Request to server
            client.requestToServer()
                    .subscribe(response -> {
                                    // Successful response
                                    doSomething(response);
                                }
                            },
                            error -> {
                                    // Error
                                    createAlarmInOneHour();
                            });
        }
    }