X

OneTimeWorkRequest : Mastering Android Work Manager

OneTimeWorkRequest :

OneTimeWorkRequest is like a superhero for managing background tasks in Android apps. It’s great at handling tasks that can be done later and doesn’t mind waiting to get the job done, no matter what.

When Android updates to a new version, they’re all about saving your phone’s battery. This affects how background services work. They’re designed to stop themselves to save battery power. That’s where our superhero, Work Manager, comes into play. It’s like the brains behind the operation, making sure everything runs smoothly and efficiently.

I’ve included code examples in both java and kotlin, the two main languages for Android. So, no matter which language you prefer, you can use OneTimeWorkRequest to make your app work smarter.

Give it a try, and you’ll not only understand Android Work Manager better but also become a pro at coding in Java or Kotlin. Let’s make your Android projects awesome together!

All the services are being self stop so that they don’t consume much battery so here comes into the picture our work manager as a part of the jetpack component.

 

Project Structure :

OnetimeWorkRequest project structure is depicted in this image.

 

Dependency :

Add dependency’s required for the project.

def work_version = "2.3.4"
// Kotlin + coroutines
implementation "androidx.work:work-runtime-ktx:$work_version"

// optional - RxJava2 support
implementation "androidx.work:work-rxjava2:$work_version"

// optional - GCMNetworkManager support
implementation "androidx.work:work-gcm:$work_version"

// optional - Test helpers
androidTestImplementation "androidx.work:work-testing:$work_version"

 

OneTimeWorkRequest :

Develop a background worker class and define tasks for execution in the background using OneTimeWorkRequest in Android Work Manager.

Specify constraints such as battery optimization, internet connectivity (unlimited or limited network), and device availability (idle mode) to enhance efficiency.

This ensures seamless task execution, including uploading/downloading images, videos, and databases, in adherence to specified conditions for optimal performance.

BackgroundTask.class :

Create a class extended by worker class

Add a sample task to log a data i.e.., uploading images in the do work method

d("oneTimeWorkRequest","Uploading photos in background")

 

Kotlin :

import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import android.util.Log.d
import androidx.core.app.NotificationCompat
import androidx.work.Worker
import androidx.work.WorkerParameters

class BackgroundTask (context : Context, params : WorkerParameters)
    : Worker(context, params){
    override fun doWork(): Result {

        d("oneTimeWorkRequest","Uploading photos in background")

         return Result.success()
    }

}

 

Java :

import android.content.Context;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

public class BackgroundTask extends Worker {
    public BackgroundTask(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    @NonNull
    @Override
    public Result doWork() {

        Log.d("oneTimeWorkRequest","Uploading photos in background");

        return Result.success();
    }
}

 

activity_main.xml

Add a simple textview to layout because we don’t use the UI components in this project we only use toast to display.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

MainActivity.class :

Add the constraints for the WorkManager,Constraints are like few conditions which are to be satisfied to do a work in background like having a UNMETERED internet

Having sufficient charge in device i.e., battery, whether device is in idle state or not and many more depending upon your requirement.

 

val constraints = Constraints.Builder().setRequiresCharging(true).setRequiredNetworkType(NetworkType.UNMETERED).build()

 

Request oneTimeWorkRequest using a Builder and provide our BackgroundTask class

val oneTimeWorkRequest = OneTimeWorkRequest.Builder(BackgroundTask::class.java).build()

 

Get work manager instance

val workManager = WorkManager.getInstance(this)

 

enqueue the oneTimeRequest to work manager

workManager.enqueue(oneTimeWorkRequest)

 

we can also observe the final response is it success or not

workManager.getWorkInfoByIdLiveData(oneTimeWorkRequest.id).observeForever {
    if(it != null){

        Log.d("oneTimeWorkRequest", "Status changed to ${it.state.isFinished}")

    }
}

 

Kotlin:

Providing the full kotlin code for OneTimeWorkRequest

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.work.*

class MainActivity : AppCompatActivity() {

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

        val constraints = Constraints.Builder().setRequiresCharging(true).setRequiredNetworkType(NetworkType.UNMETERED).build()

        val oneTimeWorkRequest = OneTimeWorkRequest.Builder(BackgroundTask::class.java).build()
        val workManager = WorkManager.getInstance(this)
        workManager.enqueue(oneTimeWorkRequest)

        workManager.getWorkInfoByIdLiveData(oneTimeWorkRequest.id).observeForever {
            if(it != null){

                Log.d("oneTimeWorkRequest", "Status changed to ${it.state.isFinished}")

            }
        }

    }
}

 

Java :

Providing the full java code for OneTimeWorkRequest implementation.

import android.os.Bundle;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.work.Constraints;
import androidx.work.NetworkType;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkInfo;
import androidx.work.WorkManager;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Constraints constraints = new Constraints.Builder().setRequiresCharging(true).setRequiredNetworkType(NetworkType.UNMETERED).build();

        final OneTimeWorkRequest oneTimeWorkRequest = new OneTimeWorkRequest.Builder(BackgroundTask.class)
                .build();

        WorkManager workManager =  WorkManager.getInstance(this);

        workManager.enqueue(oneTimeWorkRequest);

        workManager.getWorkInfoByIdLiveData(oneTimeWorkRequest.getId())
                .observe(this, new Observer<WorkInfo>() {
                    @Override
                    public void onChanged(@Nullable WorkInfo workInfo) {
                        if (workInfo != null) {
                            Log.d("oneTimeWorkRequest", "Status changed to : " + workInfo.getState());

                        }
                    }
                });
    }
}

 

 

 

Optimize your background services effortlessly with OneTimeWorkRequest. For more details and updates, like, share, and let us know your queries in the comments section. Happy coding! 🚀

 

abhishek:
Related Post

This website uses cookies.