├── app ├── .gitignore ├── src │ ├── main │ │ ├── res │ │ │ ├── values │ │ │ │ ├── strings.xml │ │ │ │ ├── colors.xml │ │ │ │ └── themes.xml │ │ │ ├── drawable │ │ │ │ ├── splash_image.png │ │ │ │ ├── splash_screen.xml │ │ │ │ └── ic_launcher_background.xml │ │ │ ├── mipmap-hdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-mdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xxhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xxxhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-anydpi-v26 │ │ │ │ ├── ic_launcher.xml │ │ │ │ └── ic_launcher_round.xml │ │ │ ├── layout │ │ │ │ └── activity_main.xml │ │ │ └── drawable-v24 │ │ │ │ └── ic_launcher_foreground.xml │ │ ├── java │ │ │ └── tech │ │ │ │ └── okcredit │ │ │ │ └── appstartupinstrumentation │ │ │ │ ├── MainActivity.kt │ │ │ │ ├── Application.kt │ │ │ │ └── DummyContentProvider.kt │ │ └── AndroidManifest.xml │ └── test │ │ └── java │ │ └── tech │ │ └── okcredit │ │ └── appstartupinstrumentation │ │ └── ExampleUnitTest.kt ├── proguard-rules.pro └── build.gradle ├── startup ├── .gitignore ├── consumer-rules.pro ├── src │ ├── main │ │ ├── java │ │ │ └── tech │ │ │ │ └── okcredit │ │ │ │ └── startup_instrumentation │ │ │ │ ├── internals │ │ │ │ ├── data │ │ │ │ │ ├── AppUpdateStartStatus.kt │ │ │ │ │ ├── ActivityState.kt │ │ │ │ │ ├── AppLaunchMetrics.kt │ │ │ │ │ └── AppStateInfo.kt │ │ │ │ ├── app_lifecycle │ │ │ │ │ ├── RecordOfActivityHandlerJobs.kt │ │ │ │ │ ├── ProcessLifecycleHandler.kt │ │ │ │ │ └── RecordOfActivityLifecycle.kt │ │ │ │ ├── content_provider │ │ │ │ │ └── AppStartContentProvider.kt │ │ │ │ ├── PreConditionStartUp.kt │ │ │ │ ├── utils │ │ │ │ │ ├── NextDrawListener.kt │ │ │ │ │ └── AppStartUpMeasurementUtils.kt │ │ │ │ ├── GetAppStateInfo.kt │ │ │ │ └── AppStartMeasureLifeCycleCallBacks.kt │ │ │ │ └── AppStartUpTracer.kt │ │ └── AndroidManifest.xml │ └── test │ │ └── java │ │ └── tech │ │ └── okcredit │ │ └── startup_instrumentation │ │ └── PreConditionStartUpUnitTest.kt ├── proguard-rules.pro └── build.gradle ├── settings.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .gitignore ├── app-startup-measure.sh ├── gradle.properties ├── gradlew.bat ├── gradlew ├── README.md └── LICENSE /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /startup/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /startup/consumer-rules.pro: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':startup' 2 | include ':app' 3 | rootProject.name = "App StartUp Instrumentation" 4 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | App StartUp Instrumentation 3 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/okcredit/android-cold-startup-instrumentation/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /app/src/main/res/drawable/splash_image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/okcredit/android-cold-startup-instrumentation/HEAD/app/src/main/res/drawable/splash_image.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/okcredit/android-cold-startup-instrumentation/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/okcredit/android-cold-startup-instrumentation/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/okcredit/android-cold-startup-instrumentation/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/okcredit/android-cold-startup-instrumentation/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/okcredit/android-cold-startup-instrumentation/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/okcredit/android-cold-startup-instrumentation/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/okcredit/android-cold-startup-instrumentation/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/okcredit/android-cold-startup-instrumentation/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/okcredit/android-cold-startup-instrumentation/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/okcredit/android-cold-startup-instrumentation/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sat Apr 24 06:57:34 IST 2021 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | .idea 5 | .idea/* 6 | /.idea/caches 7 | /.idea/libraries 8 | /.idea/modules.xml 9 | /.idea/workspace.xml 10 | /.idea/navEditor.xml 11 | /.idea/assetWizardSettings.xml 12 | .DS_Store 13 | /build 14 | /captures 15 | .externalNativeBuild 16 | .cxx 17 | local.properties 18 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /startup/src/main/java/tech/okcredit/startup_instrumentation/internals/data/AppUpdateStartStatus.kt: -------------------------------------------------------------------------------- 1 | package tech.okcredit.startup_instrumentation.internals.data 2 | 3 | enum class AppUpdateStartStatus { 4 | FIRST_START_AFTER_CLEAR_DATA, 5 | FIRST_START_AFTER_FRESH_INSTALL, 6 | FIRST_START_AFTER_UPGRADE, 7 | NORMAL_START 8 | } 9 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/splash_screen.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #FFBB86FC 4 | #FF6200EE 5 | #FF3700B3 6 | #FF03DAC5 7 | #FF018786 8 | #FF000000 9 | #FFFFFFFF 10 | -------------------------------------------------------------------------------- /app/src/test/java/tech/okcredit/appstartupinstrumentation/ExampleUnitTest.kt: -------------------------------------------------------------------------------- 1 | package tech.okcredit.appstartupinstrumentation 2 | 3 | import org.junit.Assert.* 4 | import org.junit.Test 5 | 6 | /** 7 | * Example local unit test, which will execute on the development machine (host). 8 | * 9 | * See [testing documentation](http://d.android.com/tools/testing). 10 | */ 11 | class ExampleUnitTest { 12 | @Test 13 | fun addition_isCorrect() { 14 | assertEquals(4, 2 + 2) 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /startup/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /startup/src/main/java/tech/okcredit/startup_instrumentation/internals/data/ActivityState.kt: -------------------------------------------------------------------------------- 1 | package tech.okcredit.startup_instrumentation.internals.data 2 | 3 | enum class ActivityState { 4 | /** 5 | * Warm start: the activity was created with no state bundle and then resumed. 6 | */ 7 | CREATED_NO_STATE, 8 | 9 | /** 10 | * Warm start: the activity was created with a state bundle and then resumed. 11 | */ 12 | CREATED_WITH_STATE, 13 | 14 | /** 15 | * A hot start: the activity was started and then resumed 16 | */ 17 | STARTED, 18 | 19 | /** 20 | * A hot start: the activity was resumed. 21 | */ 22 | RESUMED 23 | } 24 | -------------------------------------------------------------------------------- /app-startup-measure.sh: -------------------------------------------------------------------------------- 1 | #!/bin/zsh 2 | 3 | CUMULATIVE_TIME=0 4 | LOOP_COUNT=0 5 | PACKAGE_NAME="tech.okcredit.appstartupinstrumentation" 6 | MAIN_ACTIVITY="tech.okcredit.appstartupinstrumentation.NavigationActivity" 7 | getLaunchTime() { 8 | adb shell am start-activity -W -n $PACKAGE_NAME/$MAIN_ACTIVITY | grep "TotalTime" | cut -d ' ' -f 2 9 | } 10 | 11 | echo ">> Test start <<" 12 | 13 | for i in $(seq 1 25); do 14 | LOOP_COUNT=$((LOOP_COUNT + 1)) 15 | 16 | adb shell am force-stop $PACKAGE_NAME 17 | sleep 1 18 | 19 | THIS_LAUNCH_TIME=$(getLaunchTime) 20 | CUMULATIVE_TIME=$((CUMULATIVE_TIME + THIS_LAUNCH_TIME)) 21 | 22 | echo -n "." 23 | done 24 | 25 | printf "\n>> Test end <<\n" 26 | echo "Average startup time: $((CUMULATIVE_TIME / LOOP_COUNT))ms" -------------------------------------------------------------------------------- /app/src/main/java/tech/okcredit/appstartupinstrumentation/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package tech.okcredit.appstartupinstrumentation 2 | 3 | import android.content.Intent 4 | import android.os.Bundle 5 | import android.view.View 6 | import android.widget.TextView 7 | import androidx.appcompat.app.AppCompatActivity 8 | 9 | class MainActivity : AppCompatActivity() { 10 | override fun onCreate(savedInstanceState: Bundle?) { 11 | super.onCreate(savedInstanceState) 12 | setContentView(R.layout.activity_main) 13 | 14 | findViewById(R.id.hello_world).text = this.hashCode().toString() 15 | 16 | findViewById(R.id.hello_world).setOnClickListener { 17 | startActivity(Intent(this, MainActivity::class.java)) 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /app/src/main/java/tech/okcredit/appstartupinstrumentation/Application.kt: -------------------------------------------------------------------------------- 1 | package tech.okcredit.appstartupinstrumentation 2 | 3 | import android.app.Application 4 | import android.os.Build 5 | import android.util.Log 6 | import tech.okcredit.startup_instrumentation.AppStartUpTracer 7 | 8 | class Application : Application() { 9 | override fun onCreate() { 10 | AppStartUpTracer.start() // Should be at the end of App.onCreate() 11 | super.onCreate() 12 | 13 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 14 | AppStartUpTracer.onAppLaunchListener(this) { appStartUpMetrics -> // Should be at the end of App.onCreate() 15 | Log.v("<<< Unit>() 8 | private val handler = Handler(Looper.getMainLooper()) 9 | 10 | fun joinPost(post: () -> Unit) { 11 | val scheduled = joinedPosts.isNotEmpty() 12 | joinedPosts += post 13 | if (!scheduled) { 14 | handler.post { 15 | for (joinedPost in joinedPosts) { 16 | joinedPost() 17 | } 18 | joinedPosts.clear() 19 | } 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile -------------------------------------------------------------------------------- /startup/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 | 22 | 23 | -------------------------------------------------------------------------------- /startup/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.android.library' 3 | id 'kotlin-android' 4 | } 5 | 6 | android { 7 | compileSdkVersion 30 8 | buildToolsVersion "30.0.2" 9 | 10 | defaultConfig { 11 | minSdkVersion 14 12 | targetSdkVersion 30 13 | versionCode 1 14 | versionName "1.0" 15 | 16 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 17 | consumerProguardFiles "consumer-rules.pro" 18 | } 19 | 20 | buildTypes { 21 | debug { 22 | testCoverageEnabled true 23 | } 24 | } 25 | compileOptions { 26 | sourceCompatibility JavaVersion.VERSION_1_8 27 | targetCompatibility JavaVersion.VERSION_1_8 28 | } 29 | kotlinOptions { 30 | jvmTarget = '1.8' 31 | } 32 | } 33 | 34 | dependencies { 35 | 36 | implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" 37 | implementation 'androidx.appcompat:appcompat:1.2.0' 38 | implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0' 39 | testImplementation 'junit:junit:4.13.2' 40 | } 41 | -------------------------------------------------------------------------------- /app/src/main/java/tech/okcredit/appstartupinstrumentation/DummyContentProvider.kt: -------------------------------------------------------------------------------- 1 | package tech.okcredit.appstartupinstrumentation 2 | 3 | import android.content.ContentProvider 4 | import android.content.ContentValues 5 | import android.database.Cursor 6 | import android.net.Uri 7 | 8 | class DummyContentProvider : ContentProvider() { 9 | override fun onCreate(): Boolean { 10 | Thread.sleep(100) 11 | return true 12 | } 13 | 14 | override fun query( 15 | uri: Uri, 16 | projection: Array?, 17 | selection: String?, 18 | selectionArgs: Array?, 19 | sortOrder: String?, 20 | ): Cursor? { 21 | return null 22 | } 23 | 24 | override fun getType(uri: Uri): String? { 25 | return null 26 | } 27 | 28 | override fun insert(uri: Uri, values: ContentValues?): Uri? { 29 | return null 30 | } 31 | 32 | override fun delete(uri: Uri, selection: String?, selectionArgs: Array?): Int { 33 | return 0 34 | } 35 | 36 | override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array?): Int { 37 | return 0 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 14 | 15 | 16 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | # AndroidX package structure to make it clearer which packages are bundled with the 15 | # Android operating system, and which are packaged with your app"s APK 16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 17 | android.useAndroidX=true 18 | # Automatically convert third-party libraries to use AndroidX 19 | android.enableJetifier=true 20 | # Kotlin code style for this project: "official" or "obsolete": 21 | kotlin.code.style=official -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.android.application' 3 | id 'kotlin-android' 4 | } 5 | 6 | android { 7 | compileSdkVersion 30 8 | buildToolsVersion "30.0.2" 9 | 10 | defaultConfig { 11 | applicationId "tech.okcredit.appstartupinstrumentation" 12 | minSdkVersion 16 13 | targetSdkVersion 30 14 | versionCode 2 15 | versionName "2.0" 16 | 17 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 18 | } 19 | 20 | buildTypes { 21 | release { 22 | minifyEnabled false 23 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 24 | } 25 | } 26 | compileOptions { 27 | sourceCompatibility JavaVersion.VERSION_1_8 28 | targetCompatibility JavaVersion.VERSION_1_8 29 | } 30 | kotlinOptions { 31 | jvmTarget = '1.8' 32 | } 33 | } 34 | 35 | dependencies { 36 | 37 | implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" 38 | implementation 'androidx.core:core-ktx:1.3.2' 39 | implementation 'androidx.appcompat:appcompat:1.2.0' 40 | implementation 'com.google.android.material:material:1.3.0' 41 | implementation 'androidx.constraintlayout:constraintlayout:2.0.4' 42 | testImplementation 'junit:junit:4.13.2' 43 | 44 | implementation project(':startup') 45 | } 46 | -------------------------------------------------------------------------------- /app/src/main/res/values/themes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16 | 17 | 25 | -------------------------------------------------------------------------------- /startup/src/main/java/tech/okcredit/startup_instrumentation/internals/content_provider/AppStartContentProvider.kt: -------------------------------------------------------------------------------- 1 | package tech.okcredit.startup_instrumentation.internals.content_provider 2 | 3 | import android.content.ContentProvider 4 | import android.content.ContentValues 5 | import android.database.Cursor 6 | import android.net.Uri 7 | import android.os.SystemClock 8 | import tech.okcredit.startup_instrumentation.AppStartUpTracer 9 | 10 | class AppStartContentProvider : ContentProvider() { 11 | override fun onCreate(): Boolean { 12 | AppStartUpTracer.contentProviderStartedTime = SystemClock.uptimeMillis() 13 | return true 14 | } 15 | 16 | override fun query( 17 | uri: Uri, 18 | projection: Array?, 19 | selection: String?, 20 | selectionArgs: Array?, 21 | sortOrder: String?, 22 | ): Cursor? { 23 | return null 24 | } 25 | 26 | override fun getType(uri: Uri): String? { 27 | return null 28 | } 29 | 30 | override fun insert(uri: Uri, values: ContentValues?): Uri? { 31 | return null 32 | } 33 | 34 | override fun delete(uri: Uri, selection: String?, selectionArgs: Array?): Int { 35 | return 0 36 | } 37 | 38 | override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array?): Int { 39 | return 0 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /startup/src/main/java/tech/okcredit/startup_instrumentation/internals/app_lifecycle/ProcessLifecycleHandler.kt: -------------------------------------------------------------------------------- 1 | package tech.okcredit.startup_instrumentation.internals.app_lifecycle 2 | 3 | import android.os.Handler 4 | import android.os.Looper 5 | import android.os.SystemClock 6 | import androidx.lifecycle.Lifecycle 7 | import androidx.lifecycle.LifecycleObserver 8 | import androidx.lifecycle.OnLifecycleEvent 9 | import androidx.lifecycle.ProcessLifecycleOwner 10 | import tech.okcredit.startup_instrumentation.AppStartUpTracer.currentAppLaunchProcessed 11 | import tech.okcredit.startup_instrumentation.AppStartUpTracer.isFirstPostExecuted 12 | import tech.okcredit.startup_instrumentation.AppStartUpTracer.lastAppPauseTime 13 | 14 | internal object ProcessLifecycleHandler { 15 | 16 | fun updateAppLifecycle() { 17 | ProcessLifecycleOwner.get().lifecycle.addObserver(object : LifecycleObserver { 18 | @OnLifecycleEvent(Lifecycle.Event.ON_START) 19 | fun onAppStart() { 20 | currentAppLaunchProcessed = false 21 | } 22 | 23 | @OnLifecycleEvent(Lifecycle.Event.ON_STOP) 24 | fun onAppStop() { 25 | currentAppLaunchProcessed = true 26 | lastAppPauseTime = SystemClock.uptimeMillis() 27 | } 28 | }) 29 | 30 | val handler = Handler(Looper.getMainLooper()) 31 | handler.post { 32 | isFirstPostExecuted = true 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | 15 | 18 | 21 | 22 | 23 | 24 | 30 | -------------------------------------------------------------------------------- /startup/src/main/java/tech/okcredit/startup_instrumentation/internals/PreConditionStartUp.kt: -------------------------------------------------------------------------------- 1 | package tech.okcredit.startup_instrumentation.internals 2 | 3 | import tech.okcredit.startup_instrumentation.AppStartUpTracer 4 | 5 | internal object PreConditionStartUp { 6 | 7 | private const val COLD_LAUNCH_MAX_LIMIT = 30_000 8 | 9 | fun isValidAppStartUpMeasure(): Boolean { 10 | return AppStartUpTracer.processForkTime != 0L && AppStartUpTracer.contentProviderStartedTime != 0L && AppStartUpTracer.appOnCreateTime != 0L && 11 | AppStartUpTracer.appOnCreateEndTime != 0L && AppStartUpTracer.firstDrawTime != 0L && AppStartUpTracer.firstDrawTime - AppStartUpTracer.processForkTime < COLD_LAUNCH_MAX_LIMIT 12 | } 13 | 14 | fun findErrorReason(): String { 15 | return when { 16 | AppStartUpTracer.processForkTime == 0L -> { 17 | "Not able to track process start time" 18 | } 19 | AppStartUpTracer.contentProviderStartedTime == 0L -> { 20 | "Not able to track content provider start time" 21 | } 22 | AppStartUpTracer.appOnCreateTime == 0L -> { 23 | "Not able to App created. Please make sure that AppStartUpTracer.start() added before super.onCreate() on App OnCreate." 24 | } 25 | AppStartUpTracer.appOnCreateEndTime == 0L -> { 26 | "Not able to track the end of App.onCreate()" 27 | } 28 | AppStartUpTracer.firstDrawTime == 0L -> { 29 | "Not able to track first draw" 30 | } 31 | AppStartUpTracer.firstDrawTime - AppStartUpTracer.processForkTime >= COLD_LAUNCH_MAX_LIMIT -> { 32 | "Process start to first draw is ${AppStartUpTracer.firstDrawTime - AppStartUpTracer.processForkTime}. " + 33 | "it exceeded 30 Sec. check android.os.Process.getStartUptimeMillis() returning right values" 34 | } 35 | else -> { 36 | "unknown" 37 | } 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /startup/src/main/java/tech/okcredit/startup_instrumentation/internals/utils/NextDrawListener.kt: -------------------------------------------------------------------------------- 1 | package tech.okcredit.startup_instrumentation.internals.utils 2 | 3 | import android.os.Build 4 | import android.os.Handler 5 | import android.os.Looper 6 | import android.view.View 7 | import android.view.ViewTreeObserver 8 | import androidx.annotation.RequiresApi 9 | import java.lang.IllegalStateException 10 | 11 | @RequiresApi(Build.VERSION_CODES.JELLY_BEAN) 12 | class NextDrawListener( 13 | private val view: View, 14 | val onDrawCallback: () -> Unit 15 | ) : ViewTreeObserver.OnDrawListener { 16 | 17 | private val handler = Handler(Looper.getMainLooper()) 18 | var invokedInitialOnDraw = false 19 | 20 | @RequiresApi(Build.VERSION_CODES.JELLY_BEAN) 21 | override fun onDraw() { 22 | if (invokedInitialOnDraw) return 23 | invokedInitialOnDraw = true 24 | onDrawCallback() 25 | handler.post { 26 | if (view.viewTreeObserver.isAlive) { 27 | view.viewTreeObserver.removeOnDrawListener(this) 28 | } 29 | } 30 | } 31 | 32 | companion object { 33 | @RequiresApi(Build.VERSION_CODES.KITKAT) 34 | fun View.onNextDraw(onDrawCallback: () -> Unit) { 35 | if (viewTreeObserver == null) { return } 36 | if (viewTreeObserver.isAlive && isAttachedToWindow) { 37 | addNextDrawListener(onDrawCallback) 38 | } else { 39 | addOnAttachStateChangeListener( 40 | object : View.OnAttachStateChangeListener { 41 | override fun onViewAttachedToWindow(v: View) { 42 | addNextDrawListener(onDrawCallback) 43 | removeOnAttachStateChangeListener(this) 44 | } 45 | 46 | override fun onViewDetachedFromWindow(v: View) = Unit 47 | }) 48 | } 49 | } 50 | 51 | @RequiresApi(Build.VERSION_CODES.JELLY_BEAN) 52 | internal fun View.addNextDrawListener(callback: () -> Unit) { 53 | try { 54 | if (viewTreeObserver == null) { return } 55 | viewTreeObserver.addOnDrawListener( 56 | NextDrawListener(this, callback) 57 | ) 58 | } catch (e: IllegalStateException) { } 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /startup/src/main/java/tech/okcredit/startup_instrumentation/internals/utils/AppStartUpMeasurementUtils.kt: -------------------------------------------------------------------------------- 1 | package tech.okcredit.startup_instrumentation.internals.utils 2 | 3 | import android.app.ActivityManager 4 | import android.content.Context 5 | import android.os.Build 6 | import android.os.Process 7 | import android.os.SystemClock 8 | import android.system.Os 9 | import android.system.OsConstants 10 | import androidx.annotation.RequiresApi 11 | import java.io.BufferedReader 12 | import java.io.FileReader 13 | import java.util.concurrent.ExecutorService 14 | import java.util.concurrent.Executors 15 | import java.util.concurrent.TimeUnit 16 | 17 | internal object AppStartUpMeasurementUtils { 18 | 19 | @RequiresApi(Build.VERSION_CODES.LOLLIPOP) 20 | fun getProcessForkTime(): Long { 21 | val forkRealtime = readProcessForkRealtimeMillis() 22 | val nowRealtime = SystemClock.elapsedRealtime() 23 | val nowUptime = SystemClock.uptimeMillis() 24 | val elapsedRealtime = nowRealtime - forkRealtime 25 | 26 | return nowUptime - elapsedRealtime 27 | } 28 | 29 | @RequiresApi(Build.VERSION_CODES.LOLLIPOP) 30 | private fun readProcessForkRealtimeMillis(): Long { 31 | val myPid = Process.myPid() 32 | val ticksAtProcessStart = readProcessStartTicks(myPid) 33 | val ticksPerSecond = Os.sysconf(OsConstants._SC_CLK_TCK) 34 | return TimeUnit.SECONDS.toMillis(ticksAtProcessStart) / ticksPerSecond 35 | } 36 | 37 | /*** On Linux & Android, there's a file called /proc/[pid]/stat that is readable and contains 38 | stats for each process, including the process start time. 39 | /proc/[pid]/stat is a file with one line of text, where each stat is separated by a space. 40 | However, the second entry is the filename of the executable, which may contain spaces, 41 | so we'll have to jump past it by looking for the first ) character. Once we've done that, 42 | we can split the remaining string by spaces and pick the 20th entry at index 19. ****/ 43 | private fun readProcessStartTicks(pid: Int): Long { 44 | val path = "/proc/$pid/stat" 45 | val stat = BufferedReader(FileReader(path)).use { reader -> 46 | reader.readLine() 47 | } 48 | val fields = stat.substringAfter(") ") 49 | .split(' ') 50 | return fields[19].toLong() 51 | } 52 | 53 | fun getSingleThreadExecutorForLaunchTracker(): ExecutorService { 54 | return Executors.newSingleThreadExecutor { runnable -> 55 | Thread(runnable).apply { 56 | name = "app-launch-tracker-executor" 57 | } 58 | } 59 | } 60 | 61 | fun Context.getProcessInfo(): ActivityManager.RunningAppProcessInfo? { 62 | val activityManager = this.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager 63 | 64 | var processInfo: ActivityManager.RunningAppProcessInfo? = null 65 | 66 | activityManager.runningAppProcesses?.let { runningProcesses -> 67 | for (process in runningProcesses) { 68 | if (process.pid == Process.myPid()) { 69 | processInfo = process 70 | } 71 | } 72 | } 73 | 74 | return processInfo 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /startup/src/main/java/tech/okcredit/startup_instrumentation/internals/data/AppLaunchMetrics.kt: -------------------------------------------------------------------------------- 1 | package tech.okcredit.startup_instrumentation.internals.data 2 | 3 | import android.content.Intent 4 | import tech.okcredit.startup_instrumentation.AppStartUpTracer 5 | 6 | sealed class AppLaunchMetrics { 7 | 8 | data class ErrorRetrievingAppLaunchData(val throwable: Throwable) : AppLaunchMetrics() 9 | 10 | data class ColdStartUpData( 11 | /** 12 | * The Tech metrics regarding cold startup performance. 13 | */ 14 | val startUpMetrics: AppStartUpTracer.AppStartUpMetrics, 15 | 16 | /** 17 | * The Info regarding app state. 18 | */ 19 | val appStateInfo: AppStateInfo, 20 | 21 | /** 22 | * The First Activity name which opened first. 23 | */ 24 | val firstActivityName: String?, 25 | 26 | /** 27 | * Return information about who launched the first activity. 28 | * See [android.app.Activity.getReferrer] 29 | */ 30 | val firstActivityReferrer: String?, 31 | 32 | /** 33 | * The First Activity intent. 34 | */ 35 | val firstActivityIntent: Intent? 36 | ) : AppLaunchMetrics() 37 | 38 | data class WarmAndHotStartUpData( 39 | /** 40 | * The Tech metrics regarding warm and hot startup performance. 41 | */ 42 | val warmAndHotStartUpMetrics: WarmAndHotStartUpMetrics, 43 | 44 | /** 45 | * The Info regarding app state. 46 | */ 47 | val appStateInfo: AppStateInfo, 48 | 49 | /** 50 | * State of activity when user returns back to App. 51 | */ 52 | val activityState: ActivityState, 53 | 54 | /** 55 | * The relative importance level that the system places on this process 56 | * See [android.app.ActivityManager.RunningAppProcessInfo.importance] 57 | */ 58 | val importance: Int?, 59 | 60 | /** 61 | * Duration from last last app stop to resume 62 | */ 63 | val durationFromLastAppStop: Long?, 64 | 65 | /** 66 | * Return name of first activity 67 | */ 68 | val resumeActivityName: String?, 69 | 70 | /** 71 | * Return information about who launched the first activity. 72 | * See [android.app.Activity.getReferrer] 73 | */ 74 | val resumeActivityReferrer: String?, 75 | 76 | /** 77 | * Return information about resumed activity intent. 78 | */ 79 | val resumeActivityIntent: Intent?, 80 | ) : AppLaunchMetrics() { 81 | fun getStartType() : String { 82 | return if (activityState == ActivityState.CREATED_NO_STATE || activityState == ActivityState.CREATED_WITH_STATE) { 83 | "Warm" 84 | } else if (activityState == ActivityState.STARTED || activityState == ActivityState.RESUMED) { 85 | "Hot" 86 | } else { 87 | "Unknown" 88 | } 89 | } 90 | } 91 | } 92 | 93 | data class WarmAndHotStartUpMetrics( 94 | val timeBetweenResumeToFirstDraw: Long, 95 | val timeBetweenCreatedToResume: Long?, 96 | val timeBetweenStartToResume: Long?, 97 | ) 98 | -------------------------------------------------------------------------------- /startup/src/test/java/tech/okcredit/startup_instrumentation/PreConditionStartUpUnitTest.kt: -------------------------------------------------------------------------------- 1 | package tech.okcredit.startup_instrumentation 2 | 3 | import org.junit.Assert.* 4 | import org.junit.Test 5 | import tech.okcredit.startup_instrumentation.internals.PreConditionStartUp 6 | 7 | class PreConditionStartUpUnitTest { 8 | 9 | @Test 10 | fun `should valid only all values are present`() { 11 | AppStartUpTracer.processForkTime = 100 12 | AppStartUpTracer.contentProviderStartedTime = 200 13 | AppStartUpTracer.appOnCreateTime = 300 14 | AppStartUpTracer.appOnCreateEndTime = 400 15 | AppStartUpTracer.firstDrawTime = 500 16 | 17 | assertEquals(PreConditionStartUp.isValidAppStartUpMeasure(), true) 18 | } 19 | 20 | @Test 21 | fun `should not be valid if processForkTime is missing`() { 22 | AppStartUpTracer.processForkTime = 0 23 | AppStartUpTracer.contentProviderStartedTime = 200 24 | AppStartUpTracer.appOnCreateTime = 300 25 | AppStartUpTracer.appOnCreateEndTime = 400 26 | AppStartUpTracer.firstDrawTime = 500 27 | 28 | assertEquals(PreConditionStartUp.isValidAppStartUpMeasure(), false) 29 | } 30 | 31 | @Test 32 | fun `should not be valid if contentProviderStartedTime is missing`() { 33 | AppStartUpTracer.processForkTime = 100 34 | AppStartUpTracer.contentProviderStartedTime = 0 35 | AppStartUpTracer.appOnCreateTime = 300 36 | AppStartUpTracer.appOnCreateEndTime = 400 37 | AppStartUpTracer.firstDrawTime = 500 38 | 39 | assertEquals(PreConditionStartUp.isValidAppStartUpMeasure(), false) 40 | } 41 | 42 | @Test 43 | fun `should not be valid if appOnCreateTime is missing`() { 44 | AppStartUpTracer.processForkTime = 100 45 | AppStartUpTracer.contentProviderStartedTime = 200 46 | AppStartUpTracer.appOnCreateTime = 0 47 | AppStartUpTracer.appOnCreateEndTime = 400 48 | AppStartUpTracer.firstDrawTime = 500 49 | 50 | assertEquals(PreConditionStartUp.isValidAppStartUpMeasure(), false) 51 | } 52 | 53 | @Test 54 | fun `should not be valid if appOnCreateEndTime is missing`() { 55 | AppStartUpTracer.processForkTime = 100 56 | AppStartUpTracer.contentProviderStartedTime = 200 57 | AppStartUpTracer.appOnCreateTime = 300 58 | AppStartUpTracer.appOnCreateEndTime = 0 59 | AppStartUpTracer.firstDrawTime = 500 60 | 61 | assertEquals(PreConditionStartUp.isValidAppStartUpMeasure(), false) 62 | } 63 | 64 | @Test 65 | fun `should not be valid if firstDrawTime is missing`() { 66 | AppStartUpTracer.processForkTime = 100 67 | AppStartUpTracer.contentProviderStartedTime = 200 68 | AppStartUpTracer.appOnCreateTime = 300 69 | AppStartUpTracer.appOnCreateEndTime = 500 70 | AppStartUpTracer.firstDrawTime = 0 71 | 72 | assertEquals(PreConditionStartUp.isValidAppStartUpMeasure(), false) 73 | } 74 | 75 | @Test 76 | fun `should not be valid if startUp time is more than 30 sec`() { 77 | AppStartUpTracer.processForkTime = 100 78 | AppStartUpTracer.contentProviderStartedTime = 200 79 | AppStartUpTracer.appOnCreateTime = 300 80 | AppStartUpTracer.appOnCreateEndTime = 500 81 | AppStartUpTracer.firstDrawTime = 50000 82 | 83 | assertEquals(PreConditionStartUp.isValidAppStartUpMeasure(), false) 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /startup/src/main/java/tech/okcredit/startup_instrumentation/internals/app_lifecycle/RecordOfActivityLifecycle.kt: -------------------------------------------------------------------------------- 1 | package tech.okcredit.startup_instrumentation.internals.app_lifecycle 2 | 3 | import android.app.Activity 4 | import android.content.Intent 5 | import android.os.Build 6 | import android.os.Bundle 7 | import android.os.SystemClock 8 | 9 | internal object RecordOfActivityLifecycle { 10 | 11 | class OnCreateRecord( 12 | val sameMessage: Boolean, 13 | val hasSavedState: Boolean, 14 | val referrer: String?, 15 | val activityName: String, 16 | val intent: Intent?, 17 | val start: Long 18 | ) 19 | 20 | class OnStartRecord(val sameMessage: Boolean, val start: Long) 21 | class OnResumeRecord(val start: Long) 22 | 23 | val createdActivityHashes = mutableMapOf() 24 | val startedActivityHashes = mutableMapOf() 25 | val resumedActivityHashes = mutableMapOf() 26 | 27 | fun recordActivityResumed(activity: Activity): String { 28 | val start = SystemClock.uptimeMillis() 29 | val identityHash = Integer.toHexString(System.identityHashCode(activity)) 30 | if (identityHash in resumedActivityHashes) { 31 | return identityHash 32 | } 33 | resumedActivityHashes[identityHash] = OnResumeRecord(start) 34 | return identityHash 35 | } 36 | 37 | fun recordActivityCreated( 38 | activity: Activity, 39 | savedInstanceState: Bundle? 40 | ) { 41 | val identityHash = Integer.toHexString(System.identityHashCode(activity)) 42 | if (identityHash in createdActivityHashes) { 43 | return 44 | } 45 | 46 | val start = SystemClock.uptimeMillis() 47 | val referrer: String? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { 48 | activity.referrer.toString() 49 | } else { 50 | null 51 | } 52 | 53 | val hasSavedStated = savedInstanceState != null 54 | createdActivityHashes[identityHash] = 55 | OnCreateRecord( 56 | sameMessage = true, 57 | hasSavedState = hasSavedStated, 58 | referrer = referrer, 59 | activityName = activity.localClassName, 60 | intent = activity.intent, 61 | start = start 62 | ) 63 | 64 | RecordOfActivityHandlerJobs.joinPost { 65 | if (identityHash in createdActivityHashes) { 66 | createdActivityHashes[identityHash] = OnCreateRecord( 67 | sameMessage = false, 68 | hasSavedState = hasSavedStated, 69 | referrer = referrer, 70 | activityName = activity.localClassName, 71 | intent = activity.intent, 72 | start = start 73 | ) 74 | } 75 | } 76 | } 77 | 78 | fun recordActivityStarted(activity: Activity) { 79 | val start = SystemClock.uptimeMillis() 80 | val identityHash = Integer.toHexString(System.identityHashCode(activity)) 81 | if (identityHash in startedActivityHashes) { 82 | return 83 | } 84 | startedActivityHashes[identityHash] = OnStartRecord(true, start) 85 | RecordOfActivityHandlerJobs.joinPost { 86 | if (identityHash in startedActivityHashes) { 87 | startedActivityHashes[identityHash] = OnStartRecord(false, start) 88 | } 89 | } 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /startup/src/main/java/tech/okcredit/startup_instrumentation/internals/data/AppStateInfo.kt: -------------------------------------------------------------------------------- 1 | package tech.okcredit.startup_instrumentation.internals.data 2 | 3 | import android.app.ApplicationExitInfo 4 | import android.os.Build 5 | 6 | /** 7 | * Info regarding app updates like app starts after first install, an update, or a crash. 8 | */ 9 | data class AppStateInfo( 10 | val status: AppUpdateStartStatus, 11 | 12 | /** 13 | * See [android.content.pm.PackageInfo.firstInstallTime] 14 | */ 15 | val firstInstallTimeMillis: Long, 16 | 17 | /** 18 | * See [android.content.pm.PackageInfo.lastUpdateTime] 19 | */ 20 | val lastUpdateTimeMillis: Long, 21 | 22 | /** 23 | * Last active time. Updating value from start and pause of every activity 24 | */ 25 | val lastActiveTime: Long, 26 | 27 | /** 28 | * Last cold startup time 29 | */ 30 | val lastColdLaunchTimeMillis: Long, 31 | 32 | /** 33 | * List of all [android.content.pm.PackageInfo.versionName] values for all installs of the app, 34 | * most recent first. 35 | */ 36 | val allInstalledVersionNames: List, 37 | 38 | /** 39 | * List of all [android.content.pm.PackageInfo.versionCode] values for all installs of the app, 40 | * most recent first. 41 | */ 42 | val allInstalledVersionCodes: List, 43 | 44 | /** 45 | * Whether the app ran into Java crash after the last app start. 46 | * 47 | * Always false when [status] is [AppUpdateStartStatus.FIRST_START_AFTER_FRESH_INSTALL] (no prior 48 | * app start). 49 | * 50 | * Null if we couldn't determine when the app last crashed. 51 | */ 52 | val crashedInLastProcess: Boolean?, 53 | 54 | /** 55 | * Message of crash if [crashedInLastProcess] is true 56 | * 57 | * Null if we couldn't determine when the app last crashed. 58 | */ 59 | val lastCrashMessage: String?, 60 | 61 | /** 62 | * Whether the device OS was updated since the last app start, ie whether 63 | * [android.os.Build.FINGERPRINT] changed. 64 | * 65 | * Always false when [status] is [AppUpdateStartStatus.FIRST_START_AFTER_FRESH_INSTALL] (no prior 66 | * app start). 67 | * 68 | * Null if we hadn't saved the fingerprint in the last app start. 69 | */ 70 | val updatedOsSinceLastStart: Boolean?, 71 | 72 | /** 73 | * Describes the information of an application process's death. it only available above API 29 74 | * see [android.app.ApplicationExitInfo] 75 | */ 76 | val lastExitInformation: ApplicationExitInfo? 77 | ) { 78 | /** 79 | * Return last exit info reason 80 | */ 81 | fun getLastExitReason(): String { 82 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R || lastExitInformation == null) { 83 | return "NONE" 84 | } 85 | 86 | when (lastExitInformation.reason) { 87 | ApplicationExitInfo.REASON_UNKNOWN -> { 88 | return "UNKNOWN" 89 | } 90 | ApplicationExitInfo.REASON_EXIT_SELF -> { 91 | return "EXIT_SELF" 92 | } 93 | ApplicationExitInfo.REASON_SIGNALED -> { 94 | return "SIGNALED" 95 | } 96 | ApplicationExitInfo.REASON_LOW_MEMORY -> { 97 | return "LOW_MEMORY" 98 | } 99 | ApplicationExitInfo.REASON_CRASH -> { 100 | return "CRASH" 101 | } 102 | ApplicationExitInfo.REASON_CRASH_NATIVE -> { 103 | return "CRASH_NATIVE" 104 | } 105 | ApplicationExitInfo.REASON_ANR -> { 106 | return "ANR" 107 | } 108 | ApplicationExitInfo.REASON_INITIALIZATION_FAILURE -> { 109 | return "INITIALIZATION_FAILURE" 110 | } 111 | ApplicationExitInfo.REASON_PERMISSION_CHANGE -> { 112 | return "PERMISSION_CHANGE" 113 | } 114 | ApplicationExitInfo.REASON_EXCESSIVE_RESOURCE_USAGE -> { 115 | return "EXCESSIVE_RESOURCE_USAGE" 116 | } 117 | ApplicationExitInfo.REASON_USER_REQUESTED -> { 118 | return "USER_REQUESTED" 119 | } 120 | ApplicationExitInfo.REASON_USER_STOPPED -> { 121 | return "USER_STOPPED" 122 | } 123 | ApplicationExitInfo.REASON_OTHER -> { 124 | return "OTHER" 125 | } 126 | else -> { 127 | return "UNKNOWN_REASON" 128 | } 129 | } 130 | } 131 | } 132 | 133 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # android-app-launch-tracking 2 | This is an instrumentation library for tracking the launch response time of the android app. Launch Response Time is the time from when the system triggers App Launch to when the display has rendered the first frame of the window of the activity brought to the foreground. 3 | 4 | ### Gradle Setup 5 | 6 | ```gradle 7 | repositories { 8 | maven { url 'https://jitpack.io' } 9 | } 10 | 11 | dependencies { 12 | implementation 'com.github.okcredit:android-cold-startup-instrumentation:2.0' 13 | } 14 | ``` 15 | 16 | ### Usage 17 | Add `AppStartUpTracer.start()` (at the start of onCreate) and `AppStartUpTracer.onAppLaunchListener()` (at the end of onCreate) inside Application onCreate method. 18 | 19 | ``` 20 | override fun onCreate() { 21 | AppStartUpTracer.start() //Should be before super.onCreate() 22 | 23 | super.onCreate() 24 | ... 25 | ... 26 | ... 27 | 28 | 29 | AppStartUpTracer.onAppLaunchListener(this) { appStartUpMetrics-> 30 | Log.v("<<< 48 |
49 | 50 | | WarmAndHotStartUpData | Details | 51 | | ------------- | ------------- | 52 | | warmAndHotStartUpMetrics | It Contains hot and warm startup metrics from activity resume/create to draw. | 53 | | activityState | State of activity when user returns back to App.

CREATED_NO_STATE(Warm Launch) - The activity was created with no state bundle and then resumed
CREATED_WITH_STATE(Warm Launch) - The activity was created with a state bundle and then resumed
STARTED(Hot Launch) - The activity already created. it was started and then resumed when user launch the app
RESUMED(Hot Launch) - The activity already created and started. it was then just resumed when user launch the app | 54 | | appStateInfo | It Contains information regarding app updates like app starts after the first install, an update, first install after clearing data or a crash. it also tracks reason for last app exit, first Install time, last updated time, last cold startup time, version details of all installed versions | 55 | | importance | The relative importance level that the system places on this process. See details [here](https://developer.android.com/reference/android/app/ActivityManager.RunningAppProcessInfo#importance) | 56 | | durationFromLastAppStop | Duration from last app stop to launch | 57 | | resumeActivityName | Name of launch activity | 58 | | resumeActivityReferrer | Information about who launched the first activity. See details [here] | 59 | | resumeActivityIntent | Intent of resumed activity | 60 | 61 | 62 | 63 | Note: it gives result only post Lollipop devices(21+) 64 | 65 | ### App Cold Startup 66 | 67 | A Cold Launch is what happens when the App Launch requires a Process Start. This library is tracking process start to first draw and duration between below phases 68 | 69 | - **Process Fork to Content Provider** : Time Duration between App process forked from Zygote and First Initialization of content provider. Creating the app object and Launching the main thread will be happening here. developers have little influence on the improvement here. 70 | 71 | - **Content Provider to App OnCreate()** : Time Duration between First Initialization of the content provider to Start of App.OnCreate(). it includes All time taken for Content providers in the app. 72 | 73 | - **App OnCreate() Start to App OnCreate() End** : Time Duration between Start of App.OnCreate() to End of App.OnCreate(). it includes time taken for App.OnCreate() 74 | 75 | - **App OnCreate() End to First Draw of the frame** : Time Duration between End of App.OnCreate() to First Draw of the frame. it includes time taken for Initial activity initialisation, inflating the first layout, onMeasure() and onDraw() of for initial layout. 76 | 77 | 78 | Screenshot 2021-07-16 at 4 38 24 PM 79 | 80 | ### App Hot and Warm Startup 81 | 82 | A Hot Launch is what happens when the process was alive and the activity that is being resumed needs to first be started, i.e. was previously stopped but not destroyed. A Warm Launch is what happens when the process was alive and the activity that is being resumed needs to first be created, i.e. it was previously destroyed or never created. 83 | 84 | 85 | ### Acknowledgements 86 | 87 | - Thanks to [py - Pierre Yves Ricau](https://github.com/pyricau) for this detailed [article series](https://dev.to/pyricau/android-vitals-what-time-is-it-2oih) about cold startup. 88 | 89 | - Thanks to [Square Tart](https://github.com/square/tart). it helps to get code snippet for this library. 90 | 91 | ### License 92 | 93 | Copyright 2021 OkCredit. 94 | 95 | Licensed under the Apache License, Version 2.0 (the "License"); 96 | you may not use this file except in compliance with the License. 97 | You may obtain a copy of the License at 98 | 99 | http://www.apache.org/licenses/LICENSE-2.0 100 | 101 | Unless required by applicable law or agreed to in writing, software 102 | distributed under the License is distributed on an "AS IS" BASIS, 103 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 104 | See the License for the specific language governing permissions and 105 | limitations under the License. 106 | -------------------------------------------------------------------------------- /startup/src/main/java/tech/okcredit/startup_instrumentation/AppStartUpTracer.kt: -------------------------------------------------------------------------------- 1 | package tech.okcredit.startup_instrumentation 2 | 3 | import android.app.Application 4 | import android.content.Intent 5 | import android.os.Build 6 | import android.os.Process 7 | import android.os.SystemClock 8 | import android.util.Log 9 | import androidx.annotation.RequiresApi 10 | import org.jetbrains.annotations.NonNls 11 | import tech.okcredit.startup_instrumentation.internals.AppStartMeasureLifeCycleCallBacks 12 | import tech.okcredit.startup_instrumentation.internals.app_lifecycle.ProcessLifecycleHandler 13 | import tech.okcredit.startup_instrumentation.internals.data.AppLaunchMetrics 14 | import tech.okcredit.startup_instrumentation.internals.utils.AppStartUpMeasurementUtils 15 | import tech.okcredit.startup_instrumentation.internals.utils.AppStartUpMeasurementUtils.getSingleThreadExecutorForLaunchTracker 16 | 17 | /** 18 | * Singleton object centralizing all app start metrics and data. 19 | */ 20 | object AppStartUpTracer { 21 | 22 | /** 23 | * The SystemClock.uptimeMillis() at which this process was started 24 | */ 25 | var processForkTime = 0L 26 | 27 | /** 28 | * The SystemClock.uptimeMillis() at which content provider is started. 29 | * Tracking from [tech.okcredit.startup_instrumentation.internals.AppStartContentProvider] which initialize first ContentProvider. 30 | */ 31 | var contentProviderStartedTime: Long = 0L 32 | 33 | /** 34 | * The SystemClock.uptimeMillis() at which start of App.OnCrate. 35 | * Tracking from [tech.okcredit.startup_instrumentation.AppStartUpTracer.start] 36 | */ 37 | var appOnCreateTime = 0L 38 | 39 | /** 40 | * The SystemClock.uptimeMillis() at which end of App.OnCrate. 41 | */ 42 | var appOnCreateEndTime = 0L 43 | 44 | /** 45 | * The SystemClock.uptimeMillis() of first frame draw 46 | */ 47 | var firstDrawTime = 0L 48 | 49 | /** 50 | * The SystemClock.uptimeMillis() of first activity created time 51 | */ 52 | var firstActivityCreatedTime = 0L 53 | 54 | /** 55 | * First Activity name 56 | */ 57 | var firstActivityName: String? = null 58 | 59 | /** 60 | * Return information about who launched the first activity. 61 | * See [android.app.Activity.getReferrer] 62 | */ 63 | var firstActivityReferrer: String? = null 64 | 65 | /** 66 | * Intent of first activity 67 | */ 68 | var firstActivityIntent: Intent? = null 69 | 70 | /** 71 | * The SystemClock.uptimeMillis() of first activity resume 72 | */ 73 | var firstActivityResumeTime = 0L 74 | 75 | /** 76 | * Return has AppLaunch Processed after app resume. 77 | */ 78 | internal var currentAppLaunchProcessed = true 79 | 80 | /** 81 | * Return First Handler.post() executed. 82 | */ 83 | var isFirstPostExecuted = false 84 | 85 | /** 86 | * Return the last App Pause time in millis. 87 | */ 88 | var lastAppPauseTime: Long? = null 89 | 90 | data class AppStartUpMetrics( 91 | val totalTime: Long = firstDrawTime - processForkTime, 92 | val processForkToContentProvider: Long = contentProviderStartedTime - processForkTime, 93 | val contentProviderToAppStart: Long = appOnCreateTime - contentProviderStartedTime, 94 | val applicationOnCreateTime: Long = appOnCreateEndTime - appOnCreateTime, 95 | val appOnCreateEndToFirstActivityCreate: Long = firstActivityCreatedTime - appOnCreateEndTime, 96 | val firstActivityCreateToResume: Long = firstActivityResumeTime - firstActivityCreatedTime, 97 | val firstActivityCreateToDraw: Long = firstDrawTime - firstActivityCreatedTime, 98 | val firstActivityResumeToDraw: Long = firstDrawTime - firstActivityResumeTime, 99 | val appOnCreateEndToFirstDraw: Long = firstDrawTime - appOnCreateEndTime 100 | ) { 101 | @NonNls 102 | override fun toString(): String { 103 | return """Cold StartUp Time : $totalTime 104 | PROCESS_FORK_TO_CONTENT_PROVIDER : $processForkToContentProvider 105 | CONTENT_PROVIDER_TO_APP_START: $contentProviderToAppStart 106 | APP_ON_CREATE_TIME: $applicationOnCreateTime 107 | APP_ON_CREATE_END_TO_FIRST_ACTIVITY_CREATE: $appOnCreateEndToFirstActivityCreate, 108 | FIRST_ACTIVITY_CREATE_TO_RESUME: $firstActivityCreateToResume, 109 | FIRST_ACTIVITY_CREATE_TO_DRAW: $firstActivityCreateToDraw, 110 | FIRST_ACTIVITY_RESUME_TO_DRAW: $firstActivityResumeToDraw, 111 | APP_ON_CREATE_END_TO_FIRST_DRAW: $appOnCreateEndToFirstDraw, 112 | """ 113 | } 114 | } 115 | 116 | /** 117 | * Uses for tracking App OnCreate Start. Call this before super.onCreate() on App OnCreate. 118 | */ 119 | fun start() { 120 | appOnCreateTime = SystemClock.uptimeMillis() 121 | } 122 | 123 | /** 124 | * Uses for tracking App OnCreate Stop. Call this at the end of App OnCreate. 125 | */ 126 | @Deprecated("No Longer Used, Use new onAppLaunchListeners() method", ReplaceWith("AppStartUpTracer.onAppLaunchListeners(context, callback)", "tech.okcredit.startup_instrumentation.AppStartUpTracer")) 127 | fun stop(context: Application, responseCallback: (AppStartUpMetrics) -> Unit) { 128 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 129 | getSingleThreadExecutorForLaunchTracker().execute { 130 | val appStartMeasureLifeCycleCallBacks = AppStartMeasureLifeCycleCallBacks( 131 | context = context, 132 | firstDrawColdStartUpCallback = responseCallback, 133 | appLaunchCallback = {} 134 | ) 135 | context.registerActivityLifecycleCallbacks(appStartMeasureLifeCycleCallBacks) 136 | 137 | appOnCreateEndTime = SystemClock.uptimeMillis() 138 | setProcessData() 139 | } 140 | } 141 | } 142 | 143 | /** 144 | * Uses for tracking AppLaunch. Call this at the end of App OnCreate. 145 | */ 146 | @RequiresApi(Build.VERSION_CODES.LOLLIPOP) 147 | fun onAppLaunchListener(context: Application, responseCallback: (AppLaunchMetrics) -> Unit) { 148 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 149 | ProcessLifecycleHandler.updateAppLifecycle() 150 | 151 | getSingleThreadExecutorForLaunchTracker().execute { 152 | val appStartMeasureLifeCycleCallBacks = AppStartMeasureLifeCycleCallBacks( 153 | context = context, 154 | firstDrawColdStartUpCallback = {}, 155 | appLaunchCallback = responseCallback 156 | ) 157 | 158 | context.registerActivityLifecycleCallbacks(appStartMeasureLifeCycleCallBacks) 159 | 160 | appOnCreateEndTime = SystemClock.uptimeMillis() 161 | setProcessData() 162 | } 163 | } 164 | } 165 | 166 | @RequiresApi(Build.VERSION_CODES.LOLLIPOP) 167 | private fun setProcessData() { 168 | processForkTime = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 169 | Process.getStartUptimeMillis() 170 | } else { 171 | AppStartUpMeasurementUtils.getProcessForkTime() 172 | } 173 | /*** 174 | * https://dev.to/pyricau/android-vitals-when-did-my-app-start-24p4 175 | * Process.getStartUptimeMillis() is sometimes way off. 176 | * The interval between content provider start was greater 177 | * than 30 sec for 0.5% of app starts. 178 | * This might be due to some systems keeping a pool 179 | * of pre forked zygotes to accelerate app start. 180 | * falling back process Start time to contentProvider StartedTime. 181 | */ 182 | Log.d("<<< 30_000) { 184 | processForkTime = contentProviderStartedTime 185 | } 186 | } 187 | } 188 | -------------------------------------------------------------------------------- /startup/src/main/java/tech/okcredit/startup_instrumentation/internals/GetAppStateInfo.kt: -------------------------------------------------------------------------------- 1 | package tech.okcredit.startup_instrumentation.internals 2 | 3 | import android.app.ActivityManager 4 | import android.app.Application 5 | import android.app.ApplicationExitInfo 6 | import android.content.Context 7 | import android.os.Build 8 | import android.os.SystemClock 9 | import tech.okcredit.startup_instrumentation.internals.data.AppStateInfo 10 | import tech.okcredit.startup_instrumentation.internals.data.AppUpdateStartStatus 11 | import java.lang.Exception 12 | import java.util.* 13 | 14 | /** 15 | * Collect info regarding app updates like app starts after first install, an update, or a crash. 16 | */ 17 | internal class GetAppStateInfo private constructor( 18 | private val application: Application 19 | ) { 20 | 21 | private val preferences by lazy { 22 | application.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE) 23 | } 24 | 25 | private fun readAndUpdate(): AppStateInfo { 26 | val appPackageInfo = application.packageManager.getPackageInfo(application.packageName, 0)!! 27 | 28 | var allVersionNamesString: String 29 | var allVersionCodesString: String 30 | val status: AppUpdateStartStatus 31 | val crashedInLastProcess: Boolean? 32 | var lastCrashMessage: String? = null 33 | val lastProcessCrashElapsedRealtime: Long? 34 | val updatedOsSinceLastStart: Boolean? 35 | val versionName = appPackageInfo.versionName ?: "null" 36 | 37 | @Suppress("DEPRECATION") 38 | val longVersionCode = if (Build.VERSION.SDK_INT >= 28) { 39 | appPackageInfo.longVersionCode 40 | } else { 41 | appPackageInfo.versionCode.toLong() 42 | } 43 | val longVersionCodeString = longVersionCode.toString() 44 | 45 | if (!preferences.contains(VERSION_NAME_KEY)) { 46 | status = if (appPackageInfo.firstInstallTime != appPackageInfo.lastUpdateTime) { 47 | crashedInLastProcess = null 48 | updatedOsSinceLastStart = null 49 | 50 | AppUpdateStartStatus.FIRST_START_AFTER_CLEAR_DATA 51 | } else { 52 | crashedInLastProcess = false 53 | updatedOsSinceLastStart = false 54 | 55 | AppUpdateStartStatus.FIRST_START_AFTER_FRESH_INSTALL 56 | } 57 | allVersionNamesString = versionName 58 | allVersionCodesString = longVersionCodeString 59 | } else { 60 | val previousLongVersionCode = if (preferences.contains(LONG_VERSION_CODE_KEY)) { 61 | preferences.getLong(LONG_VERSION_CODE_KEY, -1) 62 | } else { 63 | preferences.getInt(VERSION_CODE_KEY, -1) 64 | } 65 | allVersionNamesString = 66 | preferences.getString(ALL_VERSION_NAMES_KEY, versionName)!! 67 | allVersionCodesString = 68 | preferences.getString(ALL_VERSION_CODES_KEY, longVersionCodeString)!! 69 | 70 | if (previousLongVersionCode != longVersionCode) { 71 | status = AppUpdateStartStatus.FIRST_START_AFTER_UPGRADE 72 | allVersionNamesString = "$versionName, $allVersionNamesString" 73 | allVersionCodesString = "$longVersionCodeString, $allVersionCodesString" 74 | } else { 75 | status = AppUpdateStartStatus.NORMAL_START 76 | } 77 | 78 | updatedOsSinceLastStart = 79 | preferences.getString(BUILD_FINGERPRINT_KEY, UNKNOWN_BUILD_FINGERPRINT)!! 80 | .let { fingerprint -> 81 | if (fingerprint == UNKNOWN_BUILD_FINGERPRINT) { 82 | null 83 | } else fingerprint != Build.FINGERPRINT 84 | } 85 | 86 | lastProcessCrashElapsedRealtime = preferences.getLong(CRASH_REALTIME_KEY, UNKNOWN_CRASH) 87 | 88 | crashedInLastProcess = if (lastProcessCrashElapsedRealtime == UNKNOWN_CRASH) { 89 | null 90 | } else { 91 | lastCrashMessage = preferences.getString(CRASH_MESSAGE, null) 92 | lastProcessCrashElapsedRealtime != NO_CRASH 93 | } 94 | } 95 | 96 | preferences.edit() 97 | .putLong(LONG_VERSION_CODE_KEY, longVersionCode) 98 | .putString(VERSION_NAME_KEY, versionName) 99 | .putString(ALL_VERSION_NAMES_KEY, allVersionNamesString) 100 | .putString(ALL_VERSION_CODES_KEY, allVersionCodesString) 101 | .putLong(CRASH_REALTIME_KEY, NO_CRASH) 102 | .putString(BUILD_FINGERPRINT_KEY, Build.FINGERPRINT) 103 | .apply() 104 | 105 | val allVersionNames = allVersionNamesString.split(", ") 106 | val allVersionCodes = allVersionCodesString.split(", ") 107 | .map { if (it.isEmpty().not()) it.toInt() else -1 } 108 | 109 | val lastColdLaunchTime = preferences.getLong(LAST_COLD_LAUNCH_TIME, -1L) 110 | val lastActivityTime = preferences.getLong(LAST_ACTIVITY_TIME, 0L) 111 | val lastExitInformation = getLastExitInformation() 112 | 113 | return AppStateInfo( 114 | status = status, 115 | firstInstallTimeMillis = appPackageInfo.firstInstallTime, 116 | lastUpdateTimeMillis = appPackageInfo.lastUpdateTime, 117 | lastActiveTime = lastActivityTime, 118 | lastColdLaunchTimeMillis = lastColdLaunchTime, 119 | allInstalledVersionNames = allVersionNames, 120 | allInstalledVersionCodes = allVersionCodes, 121 | crashedInLastProcess = crashedInLastProcess, 122 | lastCrashMessage = lastCrashMessage, 123 | updatedOsSinceLastStart = updatedOsSinceLastStart, 124 | lastExitInformation = lastExitInformation 125 | ) 126 | } 127 | 128 | private fun getLastExitInformation(): ApplicationExitInfo? { 129 | try { 130 | val am = application.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager 131 | val exitList = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { 132 | am.getHistoricalProcessExitReasons(application.packageName, 0, 1) 133 | } else { 134 | return null 135 | } 136 | if (exitList.isEmpty()) { 137 | return null 138 | } 139 | return exitList.first() 140 | } catch (e: Exception) { 141 | return null 142 | } 143 | } 144 | 145 | private fun onAppCrashing(exception: Throwable) { 146 | preferences.edit() 147 | .putLong(CRASH_REALTIME_KEY, SystemClock.elapsedRealtime()) 148 | .putString(CRASH_MESSAGE, exception.message) 149 | .apply() 150 | } 151 | 152 | private fun recordColdStart() { 153 | preferences.edit() 154 | .putLong(LAST_COLD_LAUNCH_TIME, System.currentTimeMillis()) 155 | .apply() 156 | } 157 | 158 | companion object { 159 | private const val PREF_NAME = "appUpgradeInfoPref" 160 | private const val VERSION_CODE_KEY = "app_version_code" 161 | private const val LONG_VERSION_CODE_KEY = "app_long_version_code" 162 | private const val VERSION_NAME_KEY = "app_version_name" 163 | private const val ALL_VERSION_NAMES_KEY = "app_all_version_names" 164 | private const val ALL_VERSION_CODES_KEY = "app_all_version_codes" 165 | private const val LAST_ACTIVITY_TIME = "last_activity_time" 166 | private const val CRASH_REALTIME_KEY = "crash_realtime" 167 | private const val CRASH_MESSAGE = "crash_message" 168 | private const val BUILD_FINGERPRINT_KEY = "build_fingerprint" 169 | private const val LAST_COLD_LAUNCH_TIME = "last_cold_launch_time" 170 | private const val NO_CRASH = -1L 171 | private const val UNKNOWN_CRASH = -2L 172 | private const val UNKNOWN_BUILD_FINGERPRINT = "UNKNOWN_BUILD_FINGERPRINT" 173 | 174 | fun Application.recordColdStartAndTrackAppUpgrade(): AppStateInfo { 175 | val detector = GetAppStateInfo(this) 176 | 177 | val defaultExceptionHandler = Thread.getDefaultUncaughtExceptionHandler() 178 | Thread.setDefaultUncaughtExceptionHandler { thread, exception -> 179 | detector.onAppCrashing(exception) 180 | defaultExceptionHandler?.uncaughtException(thread, exception) 181 | } 182 | 183 | val data = detector.readAndUpdate() 184 | detector.recordColdStart() 185 | return data 186 | } 187 | 188 | fun Application.recordLastActivity() { 189 | val preferences = this.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE) 190 | 191 | Timer().schedule(object : TimerTask() { 192 | override fun run() { 193 | preferences.edit() 194 | .putLong(LAST_ACTIVITY_TIME, System.currentTimeMillis()) 195 | .apply() 196 | } 197 | }, 1000) 198 | } 199 | } 200 | } 201 | -------------------------------------------------------------------------------- /startup/src/main/java/tech/okcredit/startup_instrumentation/internals/AppStartMeasureLifeCycleCallBacks.kt: -------------------------------------------------------------------------------- 1 | package tech.okcredit.startup_instrumentation.internals 2 | 3 | import android.app.Activity 4 | import android.app.ActivityManager 5 | import android.app.Application 6 | import android.os.* 7 | import androidx.annotation.RequiresApi 8 | import tech.okcredit.startup_instrumentation.AppStartUpTracer 9 | import tech.okcredit.startup_instrumentation.AppStartUpTracer.currentAppLaunchProcessed 10 | import tech.okcredit.startup_instrumentation.AppStartUpTracer.isFirstPostExecuted 11 | import tech.okcredit.startup_instrumentation.AppStartUpTracer.lastAppPauseTime 12 | import tech.okcredit.startup_instrumentation.internals.GetAppStateInfo.Companion.recordColdStartAndTrackAppUpgrade 13 | import tech.okcredit.startup_instrumentation.internals.GetAppStateInfo.Companion.recordLastActivity 14 | import tech.okcredit.startup_instrumentation.internals.app_lifecycle.RecordOfActivityLifecycle.createdActivityHashes 15 | import tech.okcredit.startup_instrumentation.internals.app_lifecycle.RecordOfActivityLifecycle.recordActivityCreated 16 | import tech.okcredit.startup_instrumentation.internals.app_lifecycle.RecordOfActivityLifecycle.recordActivityResumed 17 | import tech.okcredit.startup_instrumentation.internals.app_lifecycle.RecordOfActivityLifecycle.recordActivityStarted 18 | import tech.okcredit.startup_instrumentation.internals.app_lifecycle.RecordOfActivityLifecycle.resumedActivityHashes 19 | import tech.okcredit.startup_instrumentation.internals.app_lifecycle.RecordOfActivityLifecycle.startedActivityHashes 20 | import tech.okcredit.startup_instrumentation.internals.data.AppLaunchMetrics 21 | import tech.okcredit.startup_instrumentation.internals.data.AppStateInfo 22 | import tech.okcredit.startup_instrumentation.internals.data.ActivityState 23 | import tech.okcredit.startup_instrumentation.internals.data.WarmAndHotStartUpMetrics 24 | import tech.okcredit.startup_instrumentation.internals.utils.AppStartUpMeasurementUtils 25 | import tech.okcredit.startup_instrumentation.internals.utils.AppStartUpMeasurementUtils.getProcessInfo 26 | import tech.okcredit.startup_instrumentation.internals.utils.NextDrawListener.Companion.onNextDraw 27 | import java.lang.IllegalStateException 28 | 29 | @RequiresApi(Build.VERSION_CODES.KITKAT) 30 | internal class AppStartMeasureLifeCycleCallBacks( 31 | private val context: Application, 32 | private val firstDrawColdStartUpCallback: (AppStartUpTracer.AppStartUpMetrics) -> Unit, 33 | private val appLaunchCallback: (AppLaunchMetrics) -> Unit 34 | ) : 35 | Application.ActivityLifecycleCallbacks { 36 | 37 | private var firstDrawInvoked = false 38 | private var firstActivityCreated = false 39 | private var firstActivityResumed = false 40 | 41 | override fun onActivityPreResumed(activity: Activity) { 42 | recordActivityResumed(activity) 43 | } 44 | 45 | @RequiresApi(Build.VERSION_CODES.LOLLIPOP) 46 | override fun onActivityResumed(activity: Activity) { 47 | val identityHash = recordActivityResumed(activity) 48 | 49 | if (!firstActivityResumed) { 50 | firstActivityResumed = true 51 | AppStartUpTracer.firstActivityResumeTime = SystemClock.uptimeMillis() 52 | } 53 | 54 | 55 | AppStartUpMeasurementUtils.getSingleThreadExecutorForLaunchTracker().execute { 56 | val hadResumedActivity = resumedActivityHashes.size > 1 57 | if (!hadResumedActivity && !currentAppLaunchProcessed) { 58 | currentAppLaunchProcessed = true 59 | 60 | val processInfo: ActivityManager.RunningAppProcessInfo? = 61 | activity.getProcessInfo() 62 | 63 | when { 64 | isFirstPostExecuted -> { // Hot and Warm StartUp 65 | //Activity is getting resumed without create at times (0.00003% launch). Assuming state is started here. Need to figureout the reason behind it 66 | if (!createdActivityHashes.containsKey(identityHash)) { 67 | return@execute 68 | } 69 | val onCreateRecord = createdActivityHashes.getValue(identityHash) 70 | 71 | val temperature = if (onCreateRecord.sameMessage) { 72 | if (onCreateRecord.hasSavedState) { 73 | ActivityState.CREATED_WITH_STATE 74 | } else { 75 | ActivityState.CREATED_NO_STATE 76 | } 77 | } else { 78 | if (!startedActivityHashes.containsKey(identityHash)) { 79 | //Activity is getting resumed without start at times (0.02% launch). Assuming state is started here. Need to figureout the reason behind it 80 | ActivityState.STARTED 81 | } else { 82 | val onStartRecord = startedActivityHashes.getValue(identityHash) 83 | if (onStartRecord.sameMessage) { 84 | ActivityState.STARTED 85 | } else { 86 | ActivityState.RESUMED 87 | } 88 | } 89 | } 90 | 91 | val appStateInfo = context.recordColdStartAndTrackAppUpgrade() 92 | 93 | activity.window?.decorView?.onNextDraw { 94 | if (!resumedActivityHashes.containsKey(identityHash)) { return@onNextDraw } 95 | if (!startedActivityHashes.containsKey(identityHash)) { return@onNextDraw } 96 | appLaunchCallback.invoke( 97 | AppLaunchMetrics.WarmAndHotStartUpData( 98 | warmAndHotStartUpMetrics = WarmAndHotStartUpMetrics( 99 | timeBetweenResumeToFirstDraw = SystemClock.uptimeMillis() - resumedActivityHashes.getValue( 100 | identityHash 101 | ).start, 102 | timeBetweenCreatedToResume = resumedActivityHashes.getValue( 103 | identityHash 104 | ).start - createdActivityHashes.getValue(identityHash).start, 105 | timeBetweenStartToResume = resumedActivityHashes.getValue( 106 | identityHash 107 | ).start - startedActivityHashes.getValue(identityHash).start, 108 | ), 109 | appStateInfo = appStateInfo, 110 | activityState = temperature, 111 | durationFromLastAppStop = lastAppPauseTime?.let { SystemClock.uptimeMillis() - it }, 112 | importance = processInfo?.importance, 113 | resumeActivityName = onCreateRecord.activityName, 114 | resumeActivityReferrer = onCreateRecord.referrer, 115 | resumeActivityIntent = onCreateRecord.intent 116 | ) 117 | ) 118 | } 119 | } 120 | processInfo?.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND -> { 121 | val appStateInfo: AppStateInfo = context.recordColdStartAndTrackAppUpgrade() 122 | 123 | activity.window?.decorView?.onNextDraw { 124 | AppStartUpTracer.firstDrawTime = SystemClock.uptimeMillis() 125 | 126 | if (PreConditionStartUp.isValidAppStartUpMeasure()) { 127 | appLaunchCallback.invoke( 128 | AppLaunchMetrics.ColdStartUpData( 129 | startUpMetrics = AppStartUpTracer.AppStartUpMetrics(), 130 | appStateInfo = appStateInfo, 131 | firstActivityIntent = AppStartUpTracer.firstActivityIntent, 132 | firstActivityName = AppStartUpTracer.firstActivityName, 133 | firstActivityReferrer = AppStartUpTracer.firstActivityReferrer, 134 | ) 135 | ) 136 | } else { 137 | appLaunchCallback.invoke( 138 | AppLaunchMetrics.ErrorRetrievingAppLaunchData( 139 | IllegalStateException(PreConditionStartUp.findErrorReason()) 140 | ) 141 | ) 142 | } 143 | } 144 | } 145 | } 146 | } 147 | context.recordLastActivity() 148 | } 149 | } 150 | 151 | override fun onActivityPaused(activity: Activity) { 152 | resumedActivityHashes -= Integer.toHexString(System.identityHashCode(activity)) 153 | 154 | AppStartUpMeasurementUtils.getSingleThreadExecutorForLaunchTracker().execute { 155 | context.recordLastActivity() 156 | } 157 | } 158 | 159 | override fun onActivityPreStarted(activity: Activity) { 160 | recordActivityStarted(activity) 161 | } 162 | 163 | override fun onActivityStarted(activity: Activity) { 164 | recordActivityStarted(activity) 165 | } 166 | 167 | override fun onActivityStopped(activity: Activity) { 168 | startedActivityHashes -= Integer.toHexString(System.identityHashCode(activity)) 169 | } 170 | 171 | override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {} 172 | 173 | override fun onActivityPreCreated(activity: Activity, savedInstanceState: Bundle?) { 174 | recordActivityCreated(activity, savedInstanceState) 175 | } 176 | 177 | override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { 178 | recordActivityCreated(activity, savedInstanceState) 179 | 180 | if (!firstActivityCreated) { 181 | firstActivityCreated = true 182 | 183 | AppStartUpTracer.firstActivityCreatedTime = SystemClock.uptimeMillis() 184 | AppStartUpTracer.firstActivityName = activity.localClassName 185 | 186 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { 187 | AppStartUpTracer.firstActivityReferrer = activity.referrer.toString() 188 | } 189 | AppStartUpTracer.firstActivityIntent = activity.intent 190 | } 191 | 192 | if (!firstDrawInvoked) { 193 | activity.window?.decorView?.onNextDraw { 194 | if (firstDrawInvoked) return@onNextDraw 195 | firstDrawInvoked = true 196 | AppStartUpTracer.firstDrawTime = SystemClock.uptimeMillis() 197 | 198 | if (PreConditionStartUp.isValidAppStartUpMeasure()) { 199 | firstDrawColdStartUpCallback.invoke(AppStartUpTracer.AppStartUpMetrics()) 200 | } 201 | } 202 | } 203 | } 204 | 205 | override fun onActivityDestroyed(activity: Activity) { 206 | createdActivityHashes -= Integer.toHexString(System.identityHashCode(activity)) 207 | } 208 | } 209 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------