java.lang.IllegalStateException: WorkManager 已经初始化。即使未初始化工作管理器

java.lang.IllegalStateException: WorkManager is already initialized. Even though work manager is not initialized

我正在尝试进行自定义工作管理器初始化。我不希望工作管理器在一开始就被初始化,我只想在登录成功时才初始化。但即使未初始化工作管理器,我总是会收到以下异常:

java.lang.IllegalStateException: WorkManager is already initialized.  Did you try to initialize it manually without disabling WorkManagerInitializer? See WorkManager#initialize(Context, Configuration) or the class level Javadoc for more information.

下面是我的清单文件,我禁用了工作管理器的默认初始化:

 <provider
            tools:node="remove"
            android:name="androidx.work.impl.WorkManagerInitializer"
            android:authorities="${applicationId}.workmanager-init"
            android:exported="false"
            android:enabled="false"/>

下面是我的应用class,我已经实现了Configuration.Provider:

open class MyApplication : Application(), Configuration.Provider {

override fun onCreate() {
        super.onCreate()
 daggerComponent = DaggerApplicationComponent.builder().application(this).build()
    
}

  override fun getWorkManagerConfiguration(): Configuration {
        val factory: AppWorkerFactory = daggerComponent?.factory()!!
       return Configuration.Builder()
            .setMinimumLoggingLevel(android.util.Log.INFO)
            .setExecutor(appExecutors.upload).setWorkerFactory(factory)
            .build()
    }
}

如果登录成功,我正在尝试初始化工作管理器,如下所示在 LoginFragment 中:

WorkManager.initialize(activity?.application as MyApplication, (activity?.application as MyApplication).workManagerConfiguration)

请告诉我我缺少什么以及为什么我无法在登录片段中初始化工作管理器,我没有在任何其他地方初始化工作管理器,但为什么我仍然得到工作管理器已经初始化的异常?

您可以在 ContentProvider 中使用 context.applicationContext 来获取 Application class,如

class WorkManagerInit : ContentProvider {
    override fun onCreate() : Boolean{
        context?.let {
            val myApp = context.applicationContext as MyApplication
            WorkManager.initialize(myApp, myApp.getWorkManagerConfiguration())
        }
        return true
    }
}

如果您通过让您的应用程序实现 Configuration.Provider 并覆盖 getWorkManagerConfiguration() 来实现 On Demand Initialization,那么您不需要 调用 initialize 手动 - 这正是 On Deman Initialization 为您所做的。