Android background and foreground data synchronization

933 views Asked by At

Currently i'm developing an app that needs to synchronize data to the server, every 15 minutes and manual if the sync button is pressed. The issue i'm facing at the moment is that syncs are not queued. A manual sync job can run at the same time as an automatically triggered one, and this should not be possible. The sync will go wrong if the same data is send twice at the same time.

I've tried JobService and WorkManager, but can't really think of a right solution. I've created a PeriodicWorkRequest and a OneTimeWorkRequest. They should queue, and run after the active task is finished.

Any thoughts?

1

There are 1 answers

0
Leon Boon On

I fixed it like this. I think this should work:

background scheduling:

Constraints constraints = new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build();
PeriodicWorkRequest workRequest = new PeriodicWorkRequest.Builder(SyncWorker.class,15, TimeUnit.MINUTES).setConstraints(constraints).build();
WorkManager.getInstance().enqueueUniquePeriodicWork(SyncWorker.BACKGROUND_SYNC, ExistingPeriodicWorkPolicy.KEEP, workRequest);

foreground / active sync:

OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(SyncWorker.class).build();
WorkManager.getInstance().enqueueUniqueWork(SyncWorker.FOREGROUND_SYNC, ExistingWorkPolicy.KEEP, workRequest);

To manage background and foreground syncs:

public class SyncWorker extends Worker {

    public final static String FOREGROUND_SYNC = "FOREGROUND";
    public final static String BACKGROUND_SYNC = "BACKGROUND";
    private static boolean isWorking = false;

    public SyncWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    @NonNull
    @Override
    public Result doWork() {
        if(isWorking) {
            return Result.failure();
        }

        isWorking = true;

        // sync

        isWorking = false;
        return Result.success();
    }
}