Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use WorkManager to develop Jetpack components with Android

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "Android development Jetpack component WorkManager how to use", in daily operation, I believe many people in Android development Jetpack component WorkManager how to use the problem there are doubts, Xiaobian consulted all kinds of information, sorted out simple and easy to use operation methods, I hope to answer "Android development Jetpack component WorkManager how to use" doubts helpful! Next, please follow the small series to learn together!

I. Introduction

WorkManager is used to handle Android background tasks. We just need to set the task content and when to execute it, and the rest of the work can be completely handled by the system. It is automatically backward compatible, with different implementations on different Android versions.

Because it is handed over to the system scheduling, it can ensure that the application exits even after the phone restarts, the task can still be executed. WorkManager is well suited for performing tasks that interact regularly with the server, such as synchronizing data periodically. WorkManager also supports periodic tasks and chained tasks.

It should be noted that WorkManager does not guarantee that tasks will be executed on time, because the system in order to reduce power consumption, will trigger several tasks near the event together to reduce the number of times the CPU is awakened, extend battery life.

In addition, WorkManager may not work properly on domestic mobile phones, because most mobile phone manufacturers add a "one-button close" function when customizing Android system, so that the killed application can neither receive broadcast nor run background tasks of WorkManager. Domestic mobile phones add this function is also forced to helpless, mainly because there are too many malicious applications on the market want to occupy the background. Therefore, we do not use WorkManager to implement core functions on domestic mobile phones.

II. Introduction

Add dependencies to app/build.gradle:

implementation 'androidx.work:work-runtime:2.3.2' III. Basic Usage

WorkManager is used in three steps:

Define a background task

Configure Task Operating Conditions

Transfer tasks to WorkManager

3.1 Define background tasks

Create a SimpleWorker class that inherits from Worker:

class SimpleWorker(context: Context, params: WorkerParameters) : Worker(context, params) { override fun doWork(): Result { Log.d("~~~", "do something") return Result.success() }}

Result.success() indicates that the task was successfully executed

Result.failure() indicates failure of task execution

Result.retry() indicates that the task needs to be retried. This method needs to be used with the task retry configuration

3.2 Configure Task Operating Conditions 3.2.1 Task that only needs to be performed once

OneTimeWorkRequest builds tasks that only need to be performed once

val request = OneTimeWorkRequest.Builder(SimpleWorker:: class.java).build()3.2.2 Periodically executed tasks

Use PeriodicWorkRequest to build periodic tasks

val request = PeriodicWorkRequest.Builder(SimpleWorker::class.java, 15, TimeUnit.MINUTES).build()

In order to reduce power consumption, PeriodicWorkRequest requires that the task execution cycle should not be shorter than fifteen minutes. Looking at the source code, you can find that if the incoming value is shorter than fifteen minutes, the system will print a warning and then automatically set the cycle to fifteen minutes:

public static final long MIN_PERIODIC_INTERVAL_MILLIS = 15 * 60 * 1000L; // 15 minutes./** * Sets the periodic interval for this unit of work. * * @param intervalDuration The interval in milliseconds */public void setPeriodic(long intervalDuration) { if (intervalDuration

< MIN_PERIODIC_INTERVAL_MILLIS) { Logger.get().warning(TAG, String.format( "Interval duration lesser than minimum allowed value; Changed to %s", MIN_PERIODIC_INTERVAL_MILLIS)); intervalDuration = MIN_PERIODIC_INTERVAL_MILLIS; } setPeriodic(intervalDuration, intervalDuration);}3.3 将任务传给 WorkManagerWorkManager.getInstance(this).enqueue(request) 这就是 WorkManager 的基本使用。 四、高级配置4.1 设置任务延迟执行 通过 setInitialDelay 方法设置延迟时间 val request = OneTimeWorkRequest.Builder(SimpleWorker::class.java) .setInitialDelay(5, TimeUnit.MINUTES) .build()4.2 给任务添加标签 通过 addTag 方法添加标签: val request = OneTimeWorkRequest.Builder(SimpleWorker::class.java) .addTag("simple") .build() 添加标签的作用是,方便我们根据标签取消任务。 4.3 取消任务4.3.1 根据标签取消任务WorkManager.getInstance(this).cancelAllWorkByTag("simple")4.3.2 根据 request 的 id 取消任务WorkManager.getInstance(this).cancelWorkById(request.id)4.3.3 取消所有任务WorkManager.getInstance(this).cancelAllWork()4.4 任务重试 通过 setBackoffCriteria 配置任务重试: val request = OneTimeWorkRequest.Builder(SimpleWorker::class.java) .setBackoffCriteria(BackoffPolicy.LINEAR, 10, TimeUnit.SECONDS) .build() 前文说到,Result.retry() 表示任务需要重试,这个方法需要配合任务重试配置一起使用。任务重试配置就是指这个 setBackoffCriteria 方法,它传入了三个值,第二个值和第三个值表示重试时间配置。第一个值表示重试延迟的形式,有两个值可供选择: BackoffPolicy.LINEAR 重试时间每次呈线性增长,按照此例中的配置,每次重试时间就是 10s,20s,30s,40s… BackoffPolicy.EXPONENTIAL 重试时间每次呈指数级增长,按照此例中的配置,每次重试时间就是 10s,20s,40s,80s… 4.5 监听任务结果WorkManager.getInstance(this).getWorkInfoByIdLiveData(request.id).observe(this) { Log.d("~~~", "state = ${it.state}, tags = ${it.tags.toList()}") when (it.state) { WorkInfo.State.SUCCEEDED ->

Log.d("~~~", "success") WorkInfo.State.FAILED -> Log.d("~~~", "fail") WorkInfo.State.RUNNING -> Log.d("~~~", "running") WorkInfo.State.ENQUEUED -> Log.d("~~~", "enqueued") WorkInfo.State.CANCELLED -> Log.d("~~~", "cancelled") WorkInfo.State.BLOCKED -> Log.d("~~~", "blocked") }}

First, get LiveData data of task information through getWorkInfoByLiveIdData, and then observe this data. You can also get LiveData of the same Tag by getWorkInfosByTagLiveData, and observe this list of task information. Get the task status through getState method of WorkInfo. The main statuses used are WorkInfo.State.SUCCEEDED and WorkInfo.State.FAILED, which mark the success and failure of the task.

4.6 Pass Data val request = OneTimeWorkRequest.Builder(SimpleWorker:: class.java) .setInputData(Data.Builder().apply { putString("key", "value") }.build()) .build()

Read this data in the SimpleWorker class:

inputData.getString("key")4.7 Chained Task val first = OneTimeWorkRequest.Builder(SimpleWorker:: class.java) .build()val second = OneTimeWorkRequest.Builder(SimpleWorker::class.java) .build()val third = OneTimeWorkRequest.Builder(SimpleWorker::class.java) .build()WorkManager.getInstance(this) .beginWith(first) .then(second) .then(third) .enqueue()

Chain tasks are initiated by initiatingWith, followed by the suffix then, and the tasks are executed in sequence according to the order of connection. WorkManager requires that the previous task be executed successfully before the next task is executed. This means that failure of any one task will result in the interruption of the chain task.

At this point, the study of "how to use Android Jetpack component WorkManager" is over, hoping to solve everyone's doubts. Theory and practice can better match to help everyone learn, go and try it! If you want to continue learning more relevant knowledge, please continue to pay attention to the website, Xiaobian will continue to strive to bring more practical articles for everyone!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report