头图

In WorkManager 2.5 , we make it easier for multi-process applications to access a specific WorkManager instance running in a specified process.

Now, in WorkManager 2.6, we have further added support to allow Workers to run in any process, and can bind Workers to specified processes. Multi-process support is very useful for applications that need to run Worker in multiple processes. Although most applications only need one process to work well, some applications require multiple processes to complete their work. It used to be difficult to manage the work between different processes, but now everything is different!

Starting from WorkManager 2.6, you can use RemoteListenableWorker or RemoteCoroutineWorker to bind Worker to a specific process. If you use Kotlin to implement Worker, please use RemoteCoroutineWorker, and in other cases use RemoteListenableWorker. In this article, our example will be implemented using Kotlin, and we also provide a similar Java implementation in the example link below.

The implementation of RemoteCoroutineWorker CoroutineWorker , but instead of overwriting doWork , it overwrites do**Remote**Work . When generating WorkRequest, ARGUMENT_CLASS_NAME and ARGUMENT_PACKAGE_NAME are passed into InputData to bind it to a specific process.

val PACKAGE_NAME = "com.example.background.multiprocess"

// RemoteWorkerService 被添加到应用的 AndroidManifest.xml
val serviceName = RemoteWorkerService::class.java.name
val componentName = ComponentName(PACKAGE_NAME, serviceName)

val data: Data = Data.Builder()
   .putString(ARGUMENT_PACKAGE_NAME, componentName.packageName)
   .putString(ARGUMENT_CLASS_NAME, componentName.className)
   .build()

return OneTimeWorkRequestBuilder<ExampleRemoteCoroutineWorker>
   .setInputData(data)
   .build()

Then you need to add service definition in AndroidManifest for each RemoteWorkerService like this:

<manifest ... >
    <service
            android:name="androidx.work.multiprocess.RemoteWorkerService"
            android:exported="false"
            android:process=":worker1" />

    <!-- RemoteWorkerService2 extends RemoteWorkerService -->    
    <service
            android:name=".RemoteWorkerService2"
            android:exported="false"
            android:process=":worker2" />
    ...
</manifest>

You can learn how these new features work in the new WorkManager multi-process example , which is implemented using RemoteCoroutineWorker and RemoteListenableWorker at the same time.

You can also see a detailed list of changes and improvements in WorkManager 2.6 release notes

Finally, if you have any questions or ideas about WorkManager, please feel submit it to our public issue tracker .

Welcome to click here to submit feedback to us, or share your favorite content or problems found. Your feedback is very important to us, thank you for your support!


Android开发者
404 声望2k 粉丝

Android 最新开发技术更新,包括 Kotlin、Android Studio、Jetpack 和 Android 最新系统技术特性分享。更多内容,请关注 官方 Android 开发者文档。