What Is WorkManager? / Android Development

Dolyetyus

Co Admin
21 Nis 2020
1,207
670
Delft
What's WorkManager?

WorkManager is an API used to program deferred and asynchronous processes. WorkManager continues its operations even if the application is closed or the device is restarted. As with most Android technologies, WorkManager is in Android Jetpack. WorkManager can be preferred over all legacy job scheduling APIs (Firebase Job Dispatcher, Gcm Network Manager and Job Scheduler). It can work in harmony with the new features and procedures since the WorkManager API 14.

The structure of WorkManager used in programming is as follows.

overview-criteria.png


New Features

Working Limits;

It is used to set the limits required for a work. For example; If the charge of the device is below 50%, it downloads data from the internet. Working Limits help us specify the conditions under which a job will take place in this way.

Work Chaining;

Instead of complex works, you can create a flow in the background by chain all jobs together. For example; You can first download the data from the internet, then check notifications, then get the current Iocation. Also work chaining is a widely used feature.

Work Planning Example:

Kotlin

Kod:
[COLOR="palegreen"]WorkManager.getInstance(...)
    .beginWith(listOf(workA,workB))
    .then(workC)
    .enqueue()[/COLOR]

Java

Kod:
[COLOR="PaleGreen"]WorkManager.getInstance(...)
    .beginWith(Arrays.asList(workA, workB))
    .then(workC)
    .enqueue();[/COLOR]

As you can see, there are no much differences.

Flexible Retry Procedure;

Sometimes the planned works cannot be completed or get an error, the WorkManager has an error listener for such situation, when a job results in an error without you needing to code, it runs it again after a certain period of time.

Strong Work Planning Structure;

WorkManager allows you to specify whether a job is to be replicated on a one-time basis or on a schedule. With WorkManager, you can assign names to jobs, group them and make planning. Scheduled jobs are kept in a local database and the WorkManager takes care of this database in cases such as restarting the device.

Integrated Structure;

WorkManager is integrated with asynchronous APIs such as RxJava and Coroutines and can work seamlessly with your own asynchronous APIs. In addition, WorkManager can work with both very urgent and deferred jobs. Emergency work continues even if the application is closed or the device restarts.

For Example;

Sending logs and data to backend services
Periodically synchronizing the app with the server.

WorkManager is not developed for processes that can be destroyed when the application is closed. It is more about background processing.

Now Let's Make An Example Of WorkManager For Kotlin.

In this example, we will increase the number in our database by 1 every 15 minutes.

First of all, let's import WorkManager in our project. Let's paste these under build.gradle -> dependencies.

Kod:
[COLOR="PaleGreen"]dependencies {
  def work_version = "2.4.0"

    implementation "androidx.work:work-runtime-ktx:$work_version"
}[/COLOR]

Now we create a class that will do our background process, in our example it will be RefréshDatabase.

and extend the Worker class, so it will look like this

classRefréshDatabase(val context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {}

After writing in this way, when there will be a function that it wants us to implement, this doWork, everything in doWork will be performed periodically or at one time.

Kod:
[COLOR="palegreen"]val getData = inputData
        val myNumber = getData.getInt("key", 0)

        RefréshDatabase(myNumber)
        return Result.success()

RefréshDatabase in

private fun RefréshDatabase (myNumber: Int) {
        val sharedPreferences = context.getSharedPreferences("com.ego1st.kotlinworkmanager", Context.MODE_PRIVATE)
        var savedNumber = sharedPreferences.getInt("number1", 0)
        savedNumber += myNumber
        println(savedNumber)
        sharedPreferences.edit().putInt("number1", savedNumber).apply()

    }[/COLOR]

We are writing here, we increase our number one by one, in this way, we established our WorkManager system in a structured way, now let's come to the MainActivity.

The reason why we take context and workerparams in the class here is that the worker class we extend requests them. And don't worry about where this data comes from, we send it on MainActivity.

You must write your own package name on context.getSharedPreferences("com.ego1st.kotlinworkmanager", Context.MODE_PRIVATE) instead of com.ego1st.kotlinworkmanager. Otherwise, data wouldn't be saved.

Kod:
[COLOR="palegreen"]val data = Data.Builder().putInt("key", 1).build()

        val constraints = Constraints.Builder()
            .setRequiresCharging(false)
            .build()

        val request1: PeriodicWorkRequest = PeriodicWorkRequestBuilder<RefréshDatabase>(15, TimeUnit.MINUTES)
            .setConstraints(constraints)
            .setInputData(data)
            .build()

        WorkManager.getInstance(this).enqueue(request1)

        WorkManager.getInstance(this).getWorkInfoByIdLiveData(request1.id).observe(this, Observer {

            when (it.state) {
                WorkInfo.State.RUNNING -> println("Working")
                WorkInfo.State.FAILED -> println("Failed")
                WorkInfo.State.SUCCEEDED -> println("Success")
            }
        })[/COLOR]
On the other hand, we put the data to be received with DataBuilder, the name is key and the value is 1, then build.

Then we determined the limits I mentioned above. The device should not be in charge in this example.

Then we made a Periodic Work Request and ran Refrésh Database, then stated that it should happen every 15 minutes. We put the constarint and data, then we did it build.

Then we got the work in queue.

Then we put an observer, so we learned the status of the work that we previously determined as request1 and printed it. These are the things I can share about WorkManager.

Some Notes;

- Always try to use the latest version of WorkManager. It'd be better because it has a constantly evolving structure.

- You have to be very careful while using WorkManager because it does not have a very good recovery system, go through all the processes you have written twice.

- WorkManager works better with Kotlin than Java. If you want to use WorkManager, Kotlin should be your 1st choice.

- WorkManager and Coroutines library work 100% synchronously, it gives you an advantage to have both in your project.


(By the way, congratulations for your success in the contest, Ego1st.)

Translated From: https://www.turkhackteam.org/android-gelistirme/1948104-workmanager-nedir.html#post9217823
Author: Ego1st
Translator: Dolyetyus

 
Son düzenleme:
Üst

Turkhackteam.org internet sitesi 5651 sayılı kanun’un 2. maddesinin 1. fıkrasının m) bendi ile aynı kanunun 5. maddesi kapsamında "Yer Sağlayıcı" konumundadır. İçerikler ön onay olmaksızın tamamen kullanıcılar tarafından oluşturulmaktadır. Turkhackteam.org; Yer sağlayıcı olarak, kullanıcılar tarafından oluşturulan içeriği ya da hukuka aykırı paylaşımı kontrol etmekle ya da araştırmakla yükümlü değildir. Türkhackteam saldırı timleri Türk sitelerine hiçbir zararlı faaliyette bulunmaz. Türkhackteam üyelerinin yaptığı bireysel hack faaliyetlerinden Türkhackteam sorumlu değildir. Sitelerinize Türkhackteam ismi kullanılarak hack faaliyetinde bulunulursa, site-sunucu erişim loglarından bu faaliyeti gerçekleştiren ip adresini tespit edip diğer kanıtlarla birlikte savcılığa suç duyurusunda bulununuz.