当前位置:网站首页>Learning II of workmanager
Learning II of workmanager
2022-07-05 10:16:00 【Mr_ Tony】
List of articles
One 、 Preface
Work
There are several states during operation . At run time , State
It also changes . When the task begins , Status is ENQUEUED
. Run time transition to RUNNING
, At the end of the run, it will become SUCCEEDED
、FAILED
. If you try again , The state will return to ENQUEUED
. If you cancel the work , The state will become CANCELLED
.
SUCCEEDED
、FAILED
and CANCELLED
All indicate the termination status of this work . If your work is in any of the above states ,WorkInfo.State.isFinished()
Will return to true.
The following is the flow chart of task execution
The above is a one-time task execution process . If it's a timed mission , Then there won't be SUCCEEDED
、FAILED
state . The following is the flow chart of scheduled tasks .
Two 、 Only job
Generally speaking, the following methods can be used to start work
WorkManager
.getInstance(this)
.enqueue(uploadWorkRequest)
But if we inadvertently write the code twice , Then the task will be performed twice ( Although this should not appear ). To avoid this problem , Officials provide the only way to ensure the execution of one-time tasks and scheduled tasks respectively .
WorkManager.enqueueUniqueWork()
( For one-time work )WorkManager.enqueueUniquePeriodicWork()
( For regular work )
Both methods accept 3 Parameters :
- uniqueWorkName - Used to uniquely identify a work request
String
. - existingWorkPolicy - this
enum
You can tell WorkManager: If there is a unique work chain with that name that has not yet been completed , What should be done . For details , see also Conflict resolution policy . - work - To schedule
WorkRequest
.
The reference codes are as follows :
val sendLogsWorkRequest =
PeriodicWorkRequestBuilder<SendLogsWorker>(24, TimeUnit.HOURS)
.setConstraints(Constraints.Builder()
.setRequiresCharging(true)
.build()
)
.build()
WorkManager.getInstance(this).enqueueUniquePeriodicWork(
"sendLogs",
ExistingPeriodicWorkPolicy.KEEP,
sendLogsWorkRequest
)
3、 ... and 、 Conflict strategy
Please refer to the official website below
When scheduling only work , You must inform WorkManager A conflict occurs when an operation is to be performed . You can do this by passing an enumeration when you add work to the queue .
For one-time work , You need to provide a
ExistingWorkPolicy
, It supports... For handling conflicts 4 An option .
REPLACE
: Replace an existing job with a new one . This option will cancel the existing work .KEEP
: Keep your current job , And ignore new jobs .APPEND
: Attach new work to the end of existing work . This policy will lead to your new job link To existing work , After the existing work is completed .Existing jobs will be a prerequisite for new jobs . If the current job becomes
CANCELLED
orFAILED
state , New jobs will also becomeCANCELLED
orFAILED
. If you want to run a new job regardless of the state of your existing job , Please switch toAPPEND_OR_REPLACE
.
APPEND_OR_REPLACE
The function is similar toAPPEND
, But it doesn't depend on precondition Working state . Even if the existing work becomesCANCELLED
orFAILED
state , The new job will still work .For regular work , You need to provide a
ExistingPeriodicWorkPolicy
, It supportsREPLACE
andKEEP
These two options . The functions of these options correspond to ExistingWorkPolicy Function the same .
Four 、 Observe the state of work
When the work starts , The corresponding work information can be obtained in the following ways .
// by id
workManager.getWorkInfoById(syncWorker.id) // ListenableFuture<WorkInfo>
// by name
workManager.getWorkInfosForUniqueWork("sync") // ListenableFuture<List<WorkInfo>>
// by tag
workManager.getWorkInfosByTag("syncTag") // ListenableFuture<List<WorkInfo>>
The assignment methods corresponding to the above three acquisition methods are as follows :
// by id
val uploadWorkRequest: OneTimeWorkRequest = OneTimeWorkRequest.from(WorkTest::class.java)// Simple way
val workerId = uploadWorkRequest.id
//by name
WorkManager
.getInstance(this)
.enqueueUniqueWork("workName",
ExistingWorkPolicy.KEEP,
uploadWorkRequest)
//by tag
val uploadWorkRequest: WorkRequest = // Complex builder approach
OneTimeWorkRequestBuilder<WorkTest>()
.addTag("first")
.build()
The query returns
WorkInfo
Object'sListenableFuture
, This value contains the of the workid
、 Its mark 、 Its currentState
And byResult.success(outputData)
Any output data set .Using each method
LiveData
variant , You can observe by registering listenersWorkInfo
The change of ( It should be noted that the name of the called function is getWorkInfoByIdLiveData instead of getWorkInfoById()). for example , If you want to display a message to the user after a job is successfully completed , You can make the following settings :workManager.getWorkInfoByIdLiveData(syncWorker.id) .observe(viewLifecycleOwner) { workInfo -> if(workInfo?.state == WorkInfo.State.SUCCEEDED) { Snackbar.make(requireView(), R.string.work_completed, Snackbar.LENGTH_SHORT) .show() } }
5、 ... and 、 Complex query
WorkManager 2.4.0 And later versions support the use of
WorkQuery
Object to perform complex queries on the jobs that have been queued .WorkQuery Supports tags by work 、 A combination of status and unique work name .The following example shows how to find a with “syncTag” Mark 、 be in
FAILED
orCANCELLED
state , And the unique job name is “preProcess” or “sync” All work of .val workQuery = WorkQuery.Builder .fromTags(listOf("syncTag")) .addStates(listOf(WorkInfo.State.FAILED, WorkInfo.State.CANCELLED)) .addUniqueWorkNames(listOf("preProcess", "sync")) .build() val workInfos: ListenableFuture<List<WorkInfo>> = workManager.getWorkInfos(workQuery)
WorkQuery
Every component in ( Mark 、 Status or name ) And other components areAND
logical relationship . Every value in the component isOR
logical relationship . for example :(name1 OR name2 OR ...) AND (tag1 OR tag2 OR ...) AND (state1 OR state2 OR ...)
.
WorkQuery
It also applies to equivalent LiveData MethodgetWorkInfosLiveData()
.
6、 ... and 、 Cancel and stop work
Sometimes tasks need to be cancelled , You can use the following
// by id
workManager.cancelWorkById(syncWorker.id)
// by name
workManager.cancelUniqueWork("sync")
// by tag
workManager.cancelAllWorkByTag("syncTag")
WorkManager Will check the work in the background
State
. If the work has complete , The system doesn't do anything . otherwise , The status of the work will change toCANCELLED
, Then it won't run . whatever Rely on this work OfWorkRequest
The assignment will also becomeCANCELLED
.at present ,
RUNNING
May receive a reply toListenableWorker.onStopped()
Call to . If any cleaning operation is required , Please replace this method . For details , see also Stop the running worker .
So after the task stops , Can be rewritten in onStopped()
Function to handle the closing work . It can also be done through ListenableWorker.isStopped()
Come and see if the task of wiping sweat stops , Examples are as follows :
class WorkTest(val appContext: Context, workerParams: WorkerParameters): Worker(appContext, workerParams) {
override fun doWork(): Result {
if(isStopped){
return Result.success()
}
return Result.success()
}
}
7、 ... and 、 Reference link
边栏推荐
- How to judge that the thread pool has completed all tasks?
- 小程序中自定义行内左滑按钮,类似于qq和wx消息界面那种
- To bring Euler's innovation to the world, SUSE should be the guide
- 基于单片机步进电机控制器设计(正转反转指示灯挡位)
- [system design] index monitoring and alarm system
- B站大量虚拟主播被集体强制退款:收入蒸发,还倒欠B站;乔布斯被追授美国总统自由勋章;Grafana 9 发布|极客头条...
- oracle和mysql批量Merge对比
- Write double click event
- 面试:List 如何根据对象的属性去重?
- 学习笔记4--高精度地图关键技术(下)
猜你喜欢
Universal double button or single button pop-up
Fluent generates icon prompt logo widget
Today in history: the first e-book came out; The inventor of magnetic stripe card was born; The pioneer of handheld computer was born
伪类元素--before和after
钉钉、企微、飞书学会赚钱了吗?
苹果 5G 芯片研发失败?想要摆脱高通为时过早
Is it really reliable for AI to make complex decisions for enterprises? Participate in the live broadcast, Dr. Stanford to share his choice | qubit · viewpoint
MySQL character type learning notes
Comment obtenir le temps STW du GC (collecteur d'ordures)?
ByteDance Interviewer: how to calculate the memory size occupied by a picture
随机推荐
Interview: is bitmap pixel memory allocated in heap memory or native
Livedata interview question bank and answers -- 7 consecutive questions in livedata interview~
ByteDance Interviewer: how to calculate the memory size occupied by a picture
Interview: how does the list duplicate according to the attributes of the object?
Fluent generates icon prompt logo widget
@Serializedname annotation use
Generics, generic defects and application scenarios that 90% of people don't understand
Zblogphp breadcrumb navigation code
Kotlin compose and native nesting
TypeError: Cannot read properties of undefined (reading ‘cancelToken‘)
isEmpty 和 isBlank 的用法区别
Events and bubbles in the applet of "wechat applet - Basics"
如何獲取GC(垃圾回收器)的STW(暫停)時間?
@Jsonadapter annotation usage
The Alipay in place function can't be found, and the Alipay in place function is offline
Cent7 Oracle database installation error
QT realizes signal transmission and reception between two windows
小程序中自定义行内左滑按钮,类似于qq和wx消息界面那种
学习笔记4--高精度地图关键技术(下)
Advanced opencv:bgr pixel intensity map