Android Jetpack:WorkManager - WorkInfo的获取注意

一. 使用WorkRequstBuilder

  • 通过Builder构建Request
 val oneTimeWorkRequest= OneTimeWorkRequestBuilder<MyWorker>()
        		.build()
          

or

val periodicWorkRequestBuilder= PeriodicWorkRequestBuilder<MyWorker>()
        		.build()

二. WorkManager调度Request

1. BeginUniqueWork

  • 开发文档:
//doc: one request
public final WorkContinuation beginUniqueWork (
				String uniqueWorkName, 
                ExistingWorkPolicy existingWorkPolicy, 
                OneTimeWorkRequest work)
//doc: more than one
public abstract WorkContinuation beginUniqueWork (
				String uniqueWorkName, 
                ExistingWorkPolicy existingWorkPolicy, 
                List<OneTimeWorkRequest> work)
  • 我的代码:
//my code:
workManager.beginUniqueWork(
            TAG_SEARCHFRIENDWORKER,//TAG: 字符串常量
            ExistingWorkPolicy.REPLACE,//替换策略
            oneTimeWorkRequest //要入队的Request,也可以是 List<OneTimeWorkRequest> 
        ).enqueue()

只允许在队列里存在一个有TAG_SEARCHFRIENDWORKERTAG的Request,根据ExistingWorkPolicy.REPLACE,如果有新的重复的就替换掉前面的

2. BeginWith

//doc: one request
public final WorkContinuation beginWith (OneTimeWorkRequest work)

//doc: more than one
public abstract WorkContinuation beginWith (List<OneTimeWorkRequest> work)

三. Observer WorkInfo

这里获取,UiqueWork就得用第一个方法,不然获取不到

    lateinit var outputWorkInfoOfSearch: LiveData<List<WorkInfo>>
  • UniqueWork
    通过TAG获取
	outputWorkInfoOfSearch = workManager.getWorkInfosForUniqueWorkLiveData(TAG_SEARCHFRIENDWORKER)
  • Work
    也是TAG
	outputWorkInfoOfSearch = workManager.getWorkInfoByIdLiveData(TAG_SEARCHFRIENDWORKER)

也可以通过Id

	public abstract LiveData<WorkInfo> getWorkInfoByIdLiveData (UUID id)

四. 清除上次Request残留在internal db 的WorkInfo

  • 解决方法:在每次获取实例的时候清除内部数据库,虽然WorkManager有自己的机制去清理,但是有时候不满足需求
  • 开发文档:
public abstract Operation pruneWork ()
  • 作用:

Prunes all eligible finished work from the internal database. Eligible work must be finished (WorkInfo.State.SUCCEEDED, WorkInfo.State.FAILED, or WorkInfo.State.CANCELLED), with zero unfinished dependents.

  • 警告

Use this method with caution; by invoking it, you (and any modules and libraries in your codebase) will no longer be able to observe the WorkInfo of the pruned work. You do not normally need to call this method - WorkManager takes care to auto-prune its work after a sane period of time. This method also ignores the WorkRequest.Builder.keepResultsForAtLeast(long, TimeUnit) policy.

  • 我的代码:
 workManager =  WorkManager.getInstance(context).apply {
    
    
            pruneWork()
        }

开发文档:Google: Getting started with WorkManager

猜你喜欢

转载自blog.csdn.net/qq_43709922/article/details/104211613