It's late! Try implementing Android Work Manager in Java (Beginner)

Introduction

I have a chance to use Android's WorkManager, and I will write down what I have researched as a memorandum. This article describes the basic usage of WorkManager. The content is simple for beginners.

What is WorkManager

According to the Official Page, there is the following description.

The WorkManager API makes it easy to schedule deferrable asynchronous tasks that are required to run even if the app exits or the device restarts.

in short,

You can see that it is an API. Previously, it was implemented using JobScheduler and BroadcastReceiver. It seems that this has become easier. As a detailed function, it seems that you can add restrictions on network and charging status, and specify the execution timing. Also, it seems that it is implemented in an appropriate way depending on the API level, so we can implement it without worrying about the API level. This is a pretty useful API.

What to make this time (sample application)

This sample app creates an app that outputs a notification (log this time) 10 seconds after the app is closed.

I will try this. Moreover, Kotlin is currently the mainstream on Android, but this time I would like to implement it in Java.

Implementation

Let's implement it now. The flow is such that the task is implemented in the class that inherits Worker, the constraint is added to WorkRequest, and the submission is submitted to WorkManager.

This time, I will explain with the following flow.

  1. Add library
  2. Create a task that runs in the background
  3. Execute the task

Add library

First, import the WorkManager library into your Android project. Add the following dependency to your app's build.gradle file.

dependencies {
    implementation "androidx.work:work-runtime:2.4.0"
    //···(abridgement)···
}

Create a task that runs in the background

Tasks are implemented by inheriting the Worker class. Override the doWork () method.

public class SampleWorker extends Worker {    //・ ・ ・(1)

    private static String TAG = SampleWorker.class.getName();

    public SampleWorker(Context context, WorkerParameters params) {
        super(context, params);
    }

    @Override
    public Result doWork() {                  //・ ・ ・(2)
        Log.d(TAG, "Performing background tasks");
        return Result.success();              //・ ・ ・(3)
    }
}
  1. Inherit the Worker class and create a task.
  2. Override the doWork method. Describe the process to be executed in the background in this method.
  3. The doWork method has a return value. This time, we will return the normal end.
Return value Overview
Result.success() When the task completes successfully
Result.failure() When a task fails
Result.retry() When you need to retry the task later

Perform a task

To execute a task, use the WorkRequest class. Whereas Worker defines a task, WorkRequest defines how and when to perform the task. There are ʻOneTimeWorkRequest that executes the task only once and PeriodicWorkRequest that executes it regularly. This time, we will use ʻOneTimeWorkRequest which is executed only once.


public class SampleActivity extends AppCompatActivity {

    //···(abridgement)···

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {      //・ ・ ・(1)
        if (keyCode == KeyEvent.KEYCODE_BACK) {
          
            //・ ・ ・(2)
            OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(SampleWorker.class)
                    .setInitialDelay(10, TimeUnit.SECONDS)       //・ ・ ・(3)
                    .build();

            WorkManager.getInstance(getApplicationContext()).enqueue(workRequest);
                                                                 //・ ・ ・(4)
        }

        return super.onKeyDown(keyCode, event);
    }
  1. This sample runs when the app is closed with the back key so that you can see that it is running in the background.
  2. Generate a ʻOneTimeWorkRequest` that runs only once.
  3. Add a constraint to run after 10 seconds.
  4. After defining the WorkRequest, set it in the WorkManager using the ʻenqueue ()` method.

Operation check

First, launch the app. Then press the back key to return to the home screen (to background) If the log is output after 10 seconds, it is successful!

Summary

Did the sample work? It may be difficult to understand at first, but you will get used to it after implementing it several times. WorkManager can set various restrictions (charging, network connection status, etc.). You can also do it on a regular basis. I would like to write an article about this in the near future.

see you!

Recommended Posts

It's late! Try implementing Android Work Manager in Java (Beginner)
It's late! Try implementing Android Notification in Java (Beginner)
Try implementing Android Hilt in Java
Difficulties when implementing Alarm Manager in Android Studio
Try implementing Yubaba in Kinx
Try using RocksDB in Java
Try implementing signature verification for elliptic curve cryptography in Java
Try calling JavaScript in Java
Try developing Spresense in Java (1)
Try functional type in Java! ①
Solve AtCoder Beginner Contest 151 in java
Solve AtCoder Beginner Contest 150 in java
Try implementing asynchronous processing in Azure
Solve AtCoder Beginner Contest 153 in java
Try running Selenuim 3.141.59 in eclipse (java)
Try an If expression in Java
Solve AtCoder Beginner Contest 175 in java
Solve AtCoder Beginner Contest 160 in java
Try running AWS X-Ray in Java
Try to implement Yubaba in Java
Solve AtCoder Beginner Contest 152 in java
Solve AtCoder Beginner Contest 156 in java
How arrays work in Java (illustration)
Java: Try implementing your own comma-separated formatter
Try to solve Project Euler in Java
Try to implement n-ary addition in Java
Try using the Stream API in Java
Try using JSON format API in Java
Try calling the CORBA service in Java 11+
Try making a calculator app in Java
Do TensorFlow in Java. It's easy, though. .. .. ..
Java to C and C to Java in Android Studio