且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WorkManager:如何在同一应用程序中设置不同的WorkManager配置

更新时间:2022-06-10 05:56:47

您可以使用 DelegatingWorkerFactory

You can use a DelegatingWorkerFactory and add you're custom WorkerFactory to it.

您的自定义WorkerFactory将需要检查传递给工厂的类名是否是要处理的类名,如果不是,则只需返回 null ,并且 DelegatingWorkerFactory 将还原到使用反射的默认工人工厂.

Your custom WorkerFactory will need to check if the classname passed to the factory is the one it want to handle, if not, just return null and the DelegatingWorkerFactory will revert to the default worker factory using reflection.

请记住,每次初始化WorkManager时都需要添加自定义WorkerFactory.如果您不这样做,并且WorkManager尝试为您的Worker(通常由自定义WorkerFactory处理)完全填充一个WorkRequest,它将回退到默认的WorkerFactory并失败(可能是找不到类异常).

Keep in mind that you need to add your custom WorkerFactory each time you initialize WorkManager. If you don't do that and WorkManager tries to fullfill a WorkRequest for your Worker (that is normally handled by the custom WorkerFactory) it will fallback to the default WorkerFactory and fail (probably with a class not found exception).

我们在DelegatingWorkerFactory /apps/iosched/shared/data/work/IoschedWorkerFactory.kt"rel =" nofollow noreferrer> IOsched ,用于I/O和Android开发者峰会的调度应用.您的自定义WorkerFactory的代码将类似于:

We are using the DelegatingWorkerFactory in IOsched, the scheduling app used for I/O and the Android Developer Summit. The code of your custom WorkerFactory is going to be something like:

class ConferenceDataWorkerFactory(
    private val refreshEventDataUseCase: RefreshConferenceDataUseCase
) : WorkerFactory() {

    override fun createWorker(
        appContext: Context,
        workerClassName: String,
        workerParameters: WorkerParameters
    ): ListenableWorker? {

        return when (workerClassName) {
            ConferenceDataWorker::class.java.name ->
                ConferenceDataWorker(appContext, workerParameters, refreshEventDataUseCase)
            else ->
                // Return null, so that the base class can delegate to the default WorkerFactory.
                null
        }
    }
}