Android Track App Launch Count/Session

Apr 17, 2018

I would like to keep track of how many times my app/activity has been launched/used. A common use-case is I want to do/show something on the Nth launch.

Should I track launch at onCreate?

onCreate get called when

  • Activity Launch
  • Orientation Change
  • This activity launch another activity and user press home button at toolbar

onCreate won't trigger when

  • This activity launch another activity and user press back button (hardware key)
  • Press home (hardway key) to home screen and relaunch the app

Personally I don't think onCreate is reliable for this purpose.

Track user session at onResume

Personally, I would track app launch at onResume since it's getting called in every scenario (refer to Android Activity Lifecycle) when the activity is shown. The downside is that it might be called too many times (when user return from screen timeout/sleep, etc.)

Rather than tracking how many times the app/activity is launched, I track how many sessions the user use the app (and each session could be an hour). I track the first launch date and last session date as well.

@Synchronized fun appSessionCount(sharedPref: SharedPreferences): Boolean {    val now = LocalDateTime.now(ZoneOffset.UTC)    val firstSeconds = sharedPref.getLong(KEY_FIRST_LAUNCH_DATE, 0)    if (firstSeconds == 0L) {        sharedPref.edit {            putLong(KEY_FIRST_LAUNCH_DATE, now.atZone(ZoneOffset.UTC).toEpochSecond())        }    }    val seconds = sharedPref.getLong(KEY_LAST_SESSION_DATE, 0)    val lastDate = if (seconds > 0) LocalDateTime.ofInstant(Instant.ofEpochSecond(seconds), ZoneOffset.UTC) else null    var count = sharedPref.getLong(KEY_SESSION_COUNT, 0)    // first time or 1 hour ago    if (lastDate == null || Duration.between(lastDate, now).toHours() >= 1) {        sharedPref.edit {            putLong(KEY_SESSION_COUNT, count + 1)            putLong(KEY_LAST_SESSION_DATE, now.atZone(ZoneOffset.UTC).toEpochSecond())        }        return true    }    return false}

I run the code at onResume of my main activity.

class MainActivity : AppCompatActivity() {    lateinit var sharedPref: SharedPreferences    override fun onCreate(savedInstanceState: Bundle?) {        sharedPref = getSharedPreferences("LuaApp", Context.MODE_PRIVATE)    }    override fun onResume() {        super.onResume()        appSessionCount(sharedPref)    }}

NOTE: I use android-ktx for SharedPreferences

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.