Handling Offline Network Request — WorkManager to the rescue

Pulkit Aggarwal
Coding Blocks
3 min readSep 6, 2019

--

Using WorkManger to queue Network Request when the device is offline

Recently, I faced a task to implement network request for offline mode of the app in which if the user watches the video lectures by downloading them, their course progress should be updated accordingly. So I first thought of implementing via background service but then but starting from Oreo(API >26 ) there is a limit of Background Execution, here WorkManager comes to the rescue.

WorkManager is part of Android JetPack which makes it easy to schedule deferrable, asynchronous tasks that are expected to run even if the app exits or device restarts.

WorkManager is intended for tasks that are deferrable — that is, not required to run immediately — and required to run reliably even if the app exits or the device restarts. So it falls in the same category as JobScheduler, JobDisPatcher, AlarmManager, and BroadcastReciver.It is also backwards compatible up to API 14

  • Uses JobScheduler on devices with API 23+
  • Uses a combination of BroadcastReceiver + AlarmManager on devices with API 14–22

So now let's see the code

In the above, I am using retrofit 2.6.0 which have inbuilt support for coroutines so because of that I was able to return the function value depending upon the API response. Also, I'm using worker parameters to get some additional data which was required to make the API call.

val response = Clients.onlineV2JsonApi.setProgress(progress).execute()

In the above code snippet, I'm getting the response and depending upon the response I'll be doing the work.

if (response.isSuccessful) {
//Do Some Work
return Result.success()
}else{
if (response.code() in (500..599)) {
// try again if there is a server error
return Result.retry()
}
return Result.failure()
}

One important thing to notice that if the request fails due to some server error we can call “Result.retry()” to hit the request again after some time and that will be handled by the WorkManager itself.Pretty Cooll Right !!!!!

Now, let’s move to the part where we have to execute this Task from our Activity/Fragment. One important thing that we need to check while executing this task is that Network should be connected otherwise it wouldn’t be any helpful but apparently WorkManager helps us there too as one of it’s key features is that it lets you set constraints, such as network status or charge state, on when the task runs. So we need to just add a constraint whether the network is connected or not while executing this task and if not workmanager will be handling on its own and making the call the network whenever the network status changes.

In this code first, we are setting up the constraint to execute this task only if the network is connected

val constraints = Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()

then we’re creating a list of key-value pair to send data to worker class and the creating a OneTimeRequest with constrains and list of key-value pair and finally enqueuing the task using

WorkManager.getInstance().enqueue(request)

Conclusion

If you building an app with offline capabilities and you want things to be in-sync with your web server, then using WorkManager to make your network calls is not only the best option out there but it is also convenient to retry the request the calls and handling multiple constraints such as network should be connected, it should be un-metered(WIFI),device should be idle etc. You can set up as many constraints depending upon your work.

If you liked this article, click on the 👏 button, follow me here on Medium and share this article on your socials!

--

--