How to Download File in Background Using Android WorkManager (Tutorial)

This Android WorkManager tutorial will be useful to those who want to develop an Android app with the feature of downloading any file such as music, document, or video.

In this Android app tutorial, we will learn how to

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

But, let’s first understand the term “Background Task” and “Android WorkManager”.

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 on 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.

Let’s See How It Works

Step 1: Add dependency in application module Gradle file (build.gradle)

implementation "androidx.work:work-runtime:2.0.0-rc01"

Step 2: Create a work manager instance in onCreate() of activity

 val workManager = WorkManager.getInstance()

Step 3: 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()
        }
    }

Step 4: Set Constraints & start(enqueue) workmanager task

A) One Time task enqueue

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

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)

Step 5: 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
                }
            }
        })

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

OUTPUT

SO-Android-WorkManager

 


Conclusion

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

Refer the demo & download the source code from Github. In case, if you have any query on implementing Android WorkManager in your project or if you are looking to develop an Android app with this feature, you can contact Space-O Technologies & get your free consultation.

 
 

Have an App Idea?

Get your free consultation now

Leave a Reply

Your email address will not be published. Required fields are marked *