其他
使用 Jetpack App Startup 库减少应用启动时间
作者 / Yacine Rezgui
Jetpack App Startup
https://developer.android.google.cn/topic/libraries/app-startup
延迟初始化组件
https://developer.android.google.cn/topic/libraries/app-startup#disable-individual
如何使用
配置 Gradle
为了在您的依赖库或应用中使用 App Startup,您需要在 Gradle 文件中添加如下依赖项:
repositories {
google()
maven()
}
dependencies {
implementation "androidx.startup:startup-runtime:1.0.0"
}
定义 Initializer
interface Initializer<out T: Any> {
fun create(context: Context): T
fun dependencies(): List<Class<out Initializer<*>>>
}
Initializer https://developer.android.google.cn/topic/libraries/app-startup#implement-initializers
class WorkManagerInitializer : Initializer<WorkManager> {
override fun create(context: Context): WorkManager {
val configuration = Configuration.Builder()
.setMinimumLoggingLevel(Log.DEBUG)
.build()
WorkManager.initialize(context, configuration)
return WorkManager.getInstance(context)
}
// 此组件无需任何依赖
override fun dependencies() = emptyList<Class<out Initializer<*>>>()
}
提示: 此示例为纯粹说明性质,该 Initializer 实际上应该由 WorkManager 依赖库定义。
<provider
android:name="androidx.startup.InitializationProvider"
android:authorities="${applicationId}.androidx-startup"
android:exported="false"
tools:node="merge">
<!-- This entry makes WorkManagerInitializer discoverable. -->
<meta-data android:name="com.example.WorkManagerInitializer"
android:value="androidx.startup" />
</provider>
工作原理
延迟初始化
<provider
android:name="androidx.startup.InitializationProvider"
android:authorities="${applicationId}.androidx-startup"
android:exported="false"
tools:node="merge">
<!-- 禁用即时初始化 -->
<meta-data android:name="com.example.WorkManagerInitializer"
tools:node="remove" />
</provider>
// 此处返回一个 WorkManager 的实例
AppInitializer.getInstance(context)
.initializeComponent(WorkManagerInitializer.class);
详细文档 https://developer.android.google.cn/topic/libraries/app-startup#disable-individual
最后
文档 https://developer.android.google.cn/topic/libraries/app-startup 反馈问题 https://issuetracker.google.com/components/823348#basic
推荐阅读