paint-brush
Scheduling A Periodic Background Job Using Android Work Manager by@jaikherajani
1,085 reads
1,085 reads

Scheduling A Periodic Background Job Using Android Work Manager

by Jai KherajaniFebruary 4th, 2021
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Here we explain how to use Work Manager in Android to schedule a synchronized periodic background job.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - Scheduling A Periodic Background Job Using Android Work Manager
Jai Kherajani HackerNoon profile picture

🎯 Objective

We will perform a very simple task of printing a number in the logs every 15 minutes with the help of Work Manager.

🤔 What is Work Manager?

Work Manager is a simple library for doing any deferrable background work reliably. Here, a background task which doesn't needs to be executed at an exact moment is considered to be deferrable and by reliably I mean that the task should be executed even if the user exits the app or the device restarts.

👨🏽‍💻 Let's code

⚠️ Pre-requisites

1. Create an android project with an Empty activity. Select Launcher Activity and Generate layout file options.

2. Verify you have 

google()
 in Project level 
build.gradle
 file. If not please add it. The result should look as below :

allprojects {
    repositories {
        google()

        // If you're using a version of Gradle lower than 4.1, you must instead use:
        // maven {
        //     url '//maven.google.com'
        // }
        // An alternative URL is '//dl.google.com/dl/android/maven2/'
    }
}

👉🏼 Import library

In Module level 

build.gradle
file paste the following the line of code :

implementation "androidx.work:work-runtime:2.5.0"

For latest available version of this library, please refer .

👉🏼 Create a Worker class

1. Create a new class 

MyWorker
 and it should extend 
Worker
.

2. Create a parameterized constructor :

public MyWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

3. Override and implement the 

doWork()
 method :

@NonNull
    @Override
    public Result doWork() {
        return null;
    }

4. Create a new static integer variable called count.

5. Inside the 

doWork()
, increase value of count and also print the value in log :

count++;
Log.d("MyWorker","worker called - "+count+" time(s)");

💡

doWork()
is the method where we need to perform the actual background task, this method gets executed on a background thread. It is good for doing Synchronous tasks. For asynchronous task I will write another tutorial.

6. Return 

Result.success()
.

We've written our worker class and the final class should look similar to :

public class MyWorker extends Worker {

    private static int count = 0;

    public MyWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    @NonNull
    @Override
    public Result doWork() {
        count++;
        Log.d("MyWorker", "worker called - " + count + " time(s)");
        return Result.success();
    }
}

👉🏼 Create UI

In 

activity_main.xml
 create a Button inside the 
LinearLayout
 :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="//schemas.android.com/apk/res/android"
    xmlns:tools="//schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context=".MainActivity"
    android:layout_margin="16dp">

    <Button
        android:id="@+id/trigger_job"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Trigger Job" />

</LinearLayout>

👉🏼 Start worker on button press

1. In 

MainActivity
, create a Button type variable and map it to xml button using 
findViewById()
 :

Button scheduleJob = findViewById(R.id.trigger_job);

2. Set a new 

onClickListener()
 on button :

scheduleJob.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

3. Inside the onClickListener(), assuming that we don't want to run this job when battery is low, create Constraints for the job :

Constraints constraints = new Constraints.Builder()
                        .setRequiresBatteryNotLow(true)
                        .build();

💡 Constraints as the name implies are set of conditions that must be satisfied for the job to execute. For more details please refer .

4. Create a periodic work request, we need to specify our worker class, time and its unit in which our task will be execute at least once as long as the constraints are satisfied.

PeriodicWorkRequest periodicWorkRequest = new PeriodicWorkRequest.Builder(MyWorker.class, 15, TimeUnit.MINUTES)
                        .setConstraints(constraints)
                        .build();

5. Enqueue this periodic work request. We need to provide a unique name to be used by this worker, whether to replace or keep the pending (uncompleted) request, and 

periodicWorkRequest
 object that we have created previously. We'll display a toast on the screen to notify user that work has been scheduled.

WorkManager workManager = WorkManager.getInstance(getApplicationContext());
                workManager.enqueueUniquePeriodicWork("Counter", ExistingPeriodicWorkPolicy.KEEP,periodicWorkRequest);
                Toast.makeText(MainActivity.this, "🎉 Scheduled job!", Toast.LENGTH_SHORT).show();

The 

MainActivity
 class will look similar to this :

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button scheduleJob = findViewById(R.id.trigger_job);
        scheduleJob.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Constraints constraints = new Constraints.Builder()
                        .setRequiresBatteryNotLow(true)
                        .build();

                PeriodicWorkRequest periodicWorkRequest = new PeriodicWorkRequest.Builder(MyWorker.class, 15, TimeUnit.MINUTES)
                        .setConstraints(constraints)
                        .build();

                WorkManager workManager = WorkManager.getInstance(getApplicationContext());
                workManager.enqueueUniquePeriodicWork("Counter", ExistingPeriodicWorkPolicy.KEEP,periodicWorkRequest);
                Toast.makeText(MainActivity.this, "🎉 Scheduled job!", Toast.LENGTH_LONG).show();
            }
        });
    }
}

💻 Let's run the code

🖱 Click the button on the UI :

👀 Observe in the logcat :

⌚ After some time we see :

📴 After a reboot, we again see :

🥳 Good work. Mission Accomplished!

💽 Code can be downloaded from here :

Previously published at

바카라사이트 바카라사이트 온라인바카라