Middle
How to track the earliest entry point in the application?
sobes.tech AI
Answer from AI
You can create a property in the Application class that will store the initialization time.
class MyApplication : Application() {
companion object {
private var _startTime: Long = 0L
val START_TIME: Long
get() = _startTime
}
override fun onCreate() {
super.onCreate()
_startTime = System.currentTimeMillis() // Record the application start time
}
}
Alternatively, use a library with a custom ContentProvider for more precise measurement before Application.onCreate starts.
package com.example.myapp
import android.app.Application
import android.content.ContentProvider
import android.content.ContentValues
import android.database.Cursor
import android.net.Uri
import android.util.Log
class StartupTimeProvider : ContentProvider() {
companion object {
init {
// This block executes before Application.onCreate
Log.d("StartupTimeProvider", "Trace start: ${System.currentTimeMillis()}")
}
}
override fun onCreate(): Boolean {
return true // ContentProvider must always return true in onCreate
}
// Other ContentProvider methods should be implemented,
// but are not used in this case.
override fun query(uri: Uri, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor? {
return null
}
override fun getType(uri: Uri): String? {
return null
}
override fun insert(uri: Uri, values: ContentValues?): Uri? {
return null
}
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int {
return 0
}
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int {
return 0
}
}
You need to register the ContentProvider in AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MyApp">
<!-- Register provider to track startup -->
<provider
android:name=".StartupTimeProvider"
android:authorities="${applicationId}.startup"
android:exported="false"
android:initOrder="1" />
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The parameter android:initOrder="1" ensures that this provider is initialized first among all application providers.