1. WorkManager.getInstance() crash fix

Fatal Exception: java.lang.RuntimeException
Unable to start activity ComponentInfo{packageName/packageName.LauncherActivity}: java.lang.IllegalStateException: WorkManager is not initialized properly. The most likely cause is that you disabled WorkManagerInitializer in your manifest but forgot to call WorkManager#initialize in your Application#onCreate or a ContentProvider.
android.app.ActivityThread.performLaunchActivity

在启动页调用 WorkManager.getInstance()抛出异常,看提示信息说是可能在AndroidManifest.xml中我们禁用掉了WorkManagerInitializer,但实际是在配置中并没有找到想着的配置,而且该异常99%出现在三星手机上,猜想可能是手机系统适配问题。

既然如此,那尝试在AndroidManifest.xml中disable掉该Provider来复现该问题。

<provider
    android:name="androidx.work.impl.WorkManagerInitializer"
    android:authorities="com.starbucks.cn.workmanager-init"
    android:enabled="false" />

添加该配置之后,在启动页面,果然在其它手机上复现了该问题。

try {
    WorkManager.getInstance()
} catch (e: Exception) {
    e.printStackTrace()
    WorkManager.initialize(context.applicationContext, Configuration.Builder().build())
}

在初次使用getInstance()时,通过try-catch捕获一下异常,如果捕获到异常,则调用WorkManager.initialize()方法进行初始化,之后再使用getInstance()则未见异常。

也可以自定义initializer来实现

<provider
    android:authorities="com.starbucks.cn.SbuxWorkManagerInitializer"
    android:name=".ui.widget.SbuxWorkManagerInitializer" />

参考链接

results matching ""

    No results matching ""