Testing out Android Jetpack’s WorkManager!

So first time to hear about Work-manager?

Ok, so first of all. By using the WorkManager API, you can easily specify deferred tasks, asynchronous tasks, and when to run them. Using these APIs, you can create tasks and pass them to WorkManager immediately or at the right time.

Choose the appropriate method to perform the task based on factors such as device API level and app state. If WorkManager performs any task while the application is running, WorkManager can execute the task in a new thread in the application’s process.

If your app is not running, Work Manager will choose the appropriate way to schedule background tasks-depending on the API level of the device and the possibility of Work Manager to use, including dependencies JobScheduler, Firebase JobDispatcher, or AlarmManager.

So, in other words, you can use it for the following purposes.

(1. Can be used to execute delayed tasks and asynchronous tasks
(2. Can specify execution timing
(3. The task is executed in a new thread
(4. Run in the background

(5. and more, I need to check them out properly soon!

 

So let’s try out and see how it works!

First, add WorkManager Library to Android Project WorkManager requires compiled-sdk version 28 or higher.

Refer to this link: https://developer.android.com/topic/libraries/architecture/adding-components#workmanager

open up your build.gradle in the app and add the following code 

  def work_version = "1.0.0-alpha09"
    implementation "android.arch.work:work-runtime:$work_version"
    implementation "android.arch.work:work-runtime-ktx:$work_version"

Ok, I’ve added the library into my project so what should I do from here? Before we get into the implementations. Here is a flow.

(1. Write the action to the class that inherited Worker,
(2. Prepare constraints for WorkRequest,
(3. Ask WorkManager to execute,
(4. You can manage task status/receive results with WorkStatus.

Kind of simple right? So let’s start coding! But remember that it’s better to start with an easy project. So today we are going to write a code that allows you to press a button and displays a log!

 

MainActivity
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        tap.setOnClickListener {
            // Tap the button to start the work manager 
            initWorkManager()
        }
    }

    // WorkManager initialize!!!!
    private fun initWorkManager() {
        val startTest = OneTimeWorkRequestBuilder<TestWorker>().build()
        WorkManager.getInstance().enqueue(startTest)
    }
}

// WorkManager class
class TestWorker(context: Context, params: WorkerParameters) : Worker(context, params) {
    override fun doWork(): Result {
        // Do all your special stuffs in here 
        Log.d("MainActivity", "WorkManager Test")
        return Result.SUCCESS
    }
}

If you want to Observe the log you can do it like the following

WorkManager.getInstance().getStatusById(startWorker.id).observe(this, Observer {
            if (it == null) return@Observer
            Log.d("MainActivity:status", it.toString())
        })

 How to cancel?
The cancellation is indeterminate and the task may already be running/completed

  WorkManager.getInstance().cancelWorkById(startWorker.id)

And that’s all for now! Wait, there were some settings you can add …It was called constraints or something, I will take a look at it well! But according to my basic knowledge, you can add a constraint for when the battery is low.

val constraintsSettings = Constraints.Builder()
                .setRequiresCharging(true)      
                .setRequiresBatteryNotLow(true) 
                .build()
        
        val workerTest = OneTimeWorkRequestBuilder<TestWorker>()
                .setConstraints(constraintsSettings)    
               .build()

 

 

Leave a Reply

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