OneTimeWorkRequest :
Android Work Manager OneTimeWorkRequest is used to handle the background task which are deferable and asynchronously done.
Deferable means task can be done later not immediately and should be guaranteed that the work is to be done under any circumstance.
When the new versions of android operating system’s released to market they mainly concentrate on improving the battery life of the device and this led to effect the background services functioning.
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.
I have provided code in both the preferred programming languages for android i.e., java and kotlin.
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 :
Create a background worker class and add the task to be performed in the background by the work manager.
Here we can also specify the constraints required for the task to be performed like battery constraints, internet whether it is unlimited or limited network.
And also whether the device is busy in other task like calling, browsing etc., then it will wait till device is idle mode and then perform task like uploading /downloading images, videos and databases.
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()); } } }); } }
If you have any query’s on OneTimeWorkRequest do let us know in the comment section below.If you like this tutorial do like and share us for more interesting updates.