🚀【Jetpack】Android App Startup 加快 APP 啟動時間 範例💨
Android App Startup 是一個 Android 應用程式的啟動過程。當使用者啟動應用程式時,系統會執行一系列的初始化步驟,並載入相關的資源和數據,最後顯示應用程式的主畫面。這過程保證了應用程式的正確運作,並確保了使用者體驗的流暢性。
文章目錄
- 定義全域方法
- 創建 WorkManage
- 初始化依賴庫
- 初始化Application
- AndroidManifest.xml
- Developer Documents App Startup
1.定義全域方法
Sync.kt
object Sync {
fun initialize(context: Context) {
AppInitializer.getInstance(context)
.initializeComponent(SyncInitializer::class.java)
}
}
2.創建 WorkManage
TimeWorkManage.kt
class TimeWorkManage(context: Context, workerParameters: WorkerParameters) : Worker(context, workerParameters) {
override fun doWork(): Result {
Log.d("LocalDateTime", LocalDateTime.now().toString())
return Result.success()
}
}
3.初始化依賴庫
SyncInitializer.kt
class SyncInitializer : Initializer<Sync> {
override fun create(context: Context): Sync {
WorkManager.getInstance(context).apply {
enqueueUniqueWork(
"timeWork",
ExistingWorkPolicy.KEEP,
OneTimeWorkRequest.from(TimeWorkManage::class.java),
)
}
return Sync
}
override fun dependencies(): MutableList<Class<out Initializer<*>>> = mutableListOf(WorkManagerInitializer::class.java)
}
4.初始化Application
MyApplication.kt
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
Sync.initialize(this)
}
}
5.AndroidManifest.xml
application name 指定為 MyApplication
provider 聲明 meta-data
<application
android:name=".MyApplication"
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.JetpackDemo"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:configChanges="orientation|keyboard|layoutDirection|screenSize"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="androidx.startup.InitializationProvider"
android:authorities="${applicationId}.androidx-startup"
android:exported="false"
tools:node="merge">
<meta-data
android:name="com.example.jetpackdemo.SyncInitializer"
android:value="androidx.startup"
tools:node="remove" />
</provider>
</application>
6.Developer Documents App Startup
Open in Documents App Startup