Jetpack Startup
startup 版本:1.0.0
Startup
App Startup 库提供了一种在应用程序启动时初始化组件的简单、高效的方法
添加依赖
implementation("androidx.startup:startup-runtime:1.0.0")
创建初始化类
- 以 WorkManager 为例
val work_version = "2.5.0"
implementation("androidx.work:work-runtime-ktx:$work_version")
- WorkManagerInitializer
class WorkManagerInitializer : Initializer<WorkManager> {
override fun create(context: Context): WorkManager {
val config = Configuration.Builder().build()
WorkManager.initialize(context, config)
return WorkManager.getInstance(context)
}
override fun dependencies(): MutableList<Class<out Initializer<*>>> {
//不依赖其它库
return mutableListOf()
}
}
配置 AndroidManifest.xml
<!-- 移除默认初始化 -->
<provider
android:name="androidx.work.impl.WorkManagerInitializer"
android:authorities="${applicationId}.workmanager-init"
tools:node="remove" />
<provider
android:name="androidx.startup.InitializationProvider"
android:authorities="${applicationId}.androidx-startup"
android:exported="false"
tools:node="merge">
<meta-data android:name="cn.wthee.compose.startup.WorkManagerInitializer"
android:value="androidx.startup" />
</provider>
获取实例
val workInstance = AppInitializer.getInstance(context).initializeComponent(WorkManagerInitializer::class.java)