Tuesday 14 August 2018

HB Blog 158: Jetpack Architecture: - Work Manager.

The WorkManager API makes it easy to specify deferrable, asynchronous tasks and when they should run. These APIs let you create a task and hand it off to WorkManager to run immediately or at an appropriate time.

It is intended for tasks that require a guarantee that the system will run them even if the app exits, like uploading app data to a server. It is not intended for in-process background work that can safely be terminated if the app process goes away; for situations like that, we recommend using ThreadPools.

It chooses an appropriate way to schedule a background task--depending on the device API level and included dependencies, which might use JobScheduler, Firebase JobDispatcher, or AlarmManager. You don't need to write device logic to figure out what capabilities the device has and choose an appropriate API; instead, you can just hand your task off to WorkManager and let it choose the best option.

Refer the below link for complete sample code:-

Download Sample Code

Have a look on few code snippets,

//build.gradle
1
2
3
4
5
6
7
8
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.0'
    def work_version = "1.0.0-alpha04"
    implementation "android.arch.work:work-runtime:$work_version" // use -ktx for Kotlin
    // optional - Firebase JobDispatcher support
    implementation "android.arch.work:work-firebase:$work_version"
}

//BasicWorker.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
package com.harshalbenake.workmanager.worker;

import android.support.annotation.NonNull;
import androidx.work.Worker;

public class BasicWorker extends Worker{

    @Override
    public Result doWork() {
        printBasicWork();
        // Indicate success or failure with your return value:
        return Result.SUCCESS;
    }

    private void printBasicWork() {
        System.out.println("harshalbenake printBasicWork");
    }
}

//PeriodicWorker.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
package com.harshalbenake.workmanager.worker;

import android.support.annotation.NonNull;
import androidx.work.Worker;

public class PeriodicWorker extends Worker{
 
    @Override
    public Result doWork() {
        printPeriodicWork();
        // Indicate success or failure with your return value:
        return Result.SUCCESS;
    }

    private void printPeriodicWork() {
        System.out.println("harshalbenake printPeriodicWork");
    }
}