How to Download File in Background Using Android WorkManager

This Android WorkManager download file tutorial will be useful for those who want to develop an Android app with the feature of downloading any file, such as music, document, or video
In this Android WorkManager upload file tutorial, we will learn how to:-

  • Add WorkManager in an Android Project
  • Creating a background task
  • Configuring how to run the task

Before moving to the technical part, we will understand what is a background task, what is Android WorkManager, the benefits of it, and when one should make use of it.

What is a Background Task?

To define a background task in simple terms, we can say that the Background task is an existing app-related task which not executed completely within the app. Generally, we need to execute the task within an app on a background thread because it is an invaluable process.

Now, because we don’t want to block the existing app or we want the task to continue running even after if we close the current app, we have to put that task into a background thread to execute.

What is Android WorkManager?

Have you ever noticed when downloading any file, data or document in an Android app that sometimes when you close the app, that file download gets paused/stop?

Moreover, in some cases, you also have observed that when you come out of the app, the download still works until the file is downloaded completely. Isn’t it?

Yes, this all occurs with the help of Android WorkManager. Now, you must be wondering what is WorkMager?

WorkManager in Android is one of the parts of Architecture Components and Android Jetpack that runs the postponed background task when the task’s restrictions are fulfilled.

WorkManager controls the background task that needs to run when various restrictions are gathered, irrespective of whether the application process is viable or not.

There are many options available on the Android platform for prolonged background work and WorkManager is one of the most compatible and simple libraries to perform the temporary adjourned task. WorkManager has been preferred as one of the best task schedulers in Android to work on postponed tasks with an assurance of execution.

The background task can be executed in 2 different methods using Android WorkManager,

  1. Opportunistic execution:– In this method, the WorkManager will perform the execution of the background task as soon as possible.
  2. Guaranteed execution:– In this method, the WorkManager will make sure to start the execution of background tasks under different conditions, even if we come out of the app.

Benefits of Android WorkManager

WorkManager in Android is a simple yet resilient library which has numerous benefits, given as:

  1. Follows system health best practices
  2. Fully backward compatible
  3. Handles API level compatibility back to API level
  4. Supports constraints such as network conditions, storage space, and charging status
  5. LiveData support to easily display work request state in UI
  6. Tasks can be chained, while it also supports both asynchronous one-off and periodic tasks

When to Use Android WorkManager?

Although there are different ways for background task execution like ForegroundService, JobScheduler, AlarmManager, Firebase JobDispatcher, here we will prefer to use Android WorkManager as it can easily set up a task for run & forward it to the system based on specified conditions.

There are a few use cases where it is suitable to use WorkManager, such as

  • Upload files to the server
  • Syncing data to or from the server
  • Sending logs to the server
  • Executing the valuable process

To know more in detail, you can refer to the Android development guide released by Google. In our Android app development tutorial, we will learn how to download a file using WorkManager.

Want to Create an Android Application?

Want to validate your app idea? Want to get a free consultation from an expert?

Cta Image

Let’s See How to Download File Using Android WorkManager

hand icon Add dependency in application module Gradle file (build.gradle)

implementation "androidx.work:work-runtime:2.0.0-rc01"
Copy to Clipboard

hand icon Create a work manager instance in onCreate() of activity

val workManager = WorkManager.getInstance()
Copy to Clipboard

hand icon Create a work manager class extends with Worker

    class DownLoadFileWorkManager(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {
        override fun doWork(): Result {
        //TODO perform your async operational task here
        /**
        * We have performed download task here on above example
        */
        return Result.success()
    }
}
Copy to Clipboard

hand icon Set Constraints & start(enqueue) workmanager task

A) One Time task enqueue

val constraints = Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()
val task = OneTimeWorkRequest.Builder(DownLoadFileWorkManager::class.java).
setConstraints(constraints).build()
workManager.enqueue(task)
Copy to Clipboard

B) Periodic task enqueue, Recommended periodic work interval minimum time is 900000 seconds or in other words 15 minutes.

val periodicWorkRequest = PeriodicWorkRequest.Builder(DownLoadFileWorkManager::class.java,
PERIODIC_INTERVAL,
TimeUnit.MINUTES)
.setConstraints(Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build())
.build()

workManager.enqueue(periodicWorkRequest)
Copy to Clipboard

👉 Get status of One time or periodic work Request task status.

workManager.getWorkInfoByIdLiveData(task.id)
    .observe(this@MainActivity, Observer {
    it?.let {
        if (it.state == WorkInfo.State.RUNNING) {
            //task running, you can update UI
        } else if (it.state.isFinished) {
            // task finished you can notify to Views
        }
    }
})    
Copy to Clipboard

and done. Now let’s check how it runs.

OUTPUT

SO-Android-WorkManager

Now, we will answer some of the most common questions that you might have.

Frequently Asked Questions

Why Use Android WorkManager?

WorkManager effortlessly runs background work while taking care of compatibility issues and system health. With WorkManager, background work can be executed in parallel or sequentially, where you can specify an execution order.

What is the use of WorkManager in Android?

An Android library, WorkManager, runs deferrable background work when the work’s constraints are satisfied.

What’s the difference between Android WorkManager and JobScheduler?

While WorkManager is not very different than JobScheduler, it does have a few extra features that set it apart. For instance, with WorkManager, you can set work sequences, chained jobs, observe job status — all of that without influencing the system health.

Conclusion

Using the above Android WorkManager Tutorial, we learned how to download a file in the background.

Refer to the demo & download the source code from Github. In case, if you have any queries on implementing Android WorkManager in your project, let us know. We will be happy to help. Furthermore, if you’re looking for a reliable Android software development company, look no further. Our team of professional developers has got you covered. Schedule a call today and our experts will be happy to guide you in creating your next mobile app.

Bhaval Patel

Written by

Bhaval Patel is a Director (Operations) at Space-O Technologies. He has 20+ years of experience helping startups and enterprises with custom software solutions to drive maximum results. Under his leadership, Space-O has won the 8th GESIA annual award for being the best mobile app development company. So far, he has validated more than 300 app ideas and successfully delivered 100 custom solutions using the technologies, such as Swift, Kotlin, React Native, Flutter, PHP, RoR, IoT, AI, NFC, AR/VR, Blockchain, NFT, and more.