写点什么

CoroutineWorker

用户头像
Changing Lin
关注
发布于: 3 小时前
CoroutineWorker

1.WorkManager

  • 在工程中声明依赖项

dependencies {	def work_version = "2.6.0"
// (Java only) implementation "androidx.work:work-runtime:$work_version"
// 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"
// optional - Multiprocess support implementation "androidx.work:work-multiprocess:$work_version"}
复制代码


  • 不要扩展 Worker,而应扩展 CoroutineWorker,后者包含 doWork() 的挂起版本

class CoroutineDownloadWorker(    context: Context,    params: WorkerParameters) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result { val data = downloadSynchronously("https://www.google.com") saveData(data) return Result.success() }}
复制代码


2.在其他进程中运行 CoroutineWorker

  • RemoteCoroutineWorker 会使用您在构建工作请求时于输入数据中提供的两个额外参数绑定到特定进程:ARGUMENT_CLASS_NAME 和 ARGUMENT_PACKAGE_NAME。

val PACKAGE_NAME = "com.example.background.multiprocess"
val serviceName = RemoteWorkerService::class.java.nameval componentName = ComponentName(PACKAGE_NAME, serviceName)
val data: Data = Data.Builder()   .putString(ARGUMENT_PACKAGE_NAME, componentName.packageName)   .putString(ARGUMENT_CLASS_NAME, componentName.className)   .build()
return OneTimeWorkRequest.Builder(ExampleRemoteCoroutineWorker::class.java)   .setInputData(data)   .build()
复制代码


<manifest ... >    <service            android:name="androidx.work.multiprocess.RemoteWorkerService"            android:exported="false"            android:process=":worker1" />
<service android:name=".RemoteWorkerService2" android:exported="false" android:process=":worker2" /> ...</manifest>
复制代码


发布于: 3 小时前阅读数: 2
用户头像

Changing Lin

关注

获得机遇的手段远超于固有常规之上~ 2020.04.29 加入

我能做的,就是调整好自己的精神状态,以最佳的面貌去面对那些未曾经历过得事情,对生活充满热情和希望。

评论

发布
暂无评论
CoroutineWorker