Mohammed Ali
Mohammed Ali

Reputation: 27

Best way to count how much time user spend on your app (Kotlin)

I want to count the time that the user spent in my app then store it and when the user uses the app again we add the new time

there are multiple activities in my app and I'm using MVVM so I think it's best to put the logic in the MVVM

the problem is how to count time

any ideas??

Upvotes: 0

Views: 1262

Answers (1)

Tenfour04
Tenfour04

Reputation: 93789

In the view's onStart() tell the view model to start counting time, and in onStop() tell it to stop and persist it.

In the view model, when told to start counting time, store the value of System.currentTimeMillis() in a property. When told to stop, subtract that value from another call to System.currentTimeMillis() and persist it to the model by adding it to the previously recorded value retrieved from the model.

Edit based on comment:

Here's how you can use a coroutine to create a counter that updates a LiveData periodically. Since delays in coroutines aren't perfectly precise, I have it fire four times a second to prevent the timer from noticeably losing or gaining a second from time to time.

private val _secondsUpTime = MutableLiveData<Int>()
val secondsUpTime: LiveData<Int> = _secondsUpTime

private var startTime = -1L
private var counterJob: Job? = null

fun notifyAppStarted() {
    startTime = System.currentTimeMillis()
    counterJob = viewModelScope.launch {
        val lastPersistedLifetime = repo.lifetimeMillis
        while (true) {
            val totalTime = System.currentTimeMillis() - startTime + lastPersistedLifetime
            _secondsUpTime.value = (totalTime / 1000).toInt()
            delay(250)
        }
    }
}

fun notifyAppStopped() {
    if (startTime < 0) {
        Log.e(TAG, "Tried to notify app stopped without notifying app started first.")
        return
    }
    counterJob?.cancel()
    val totalTime = System.currentTimeMillis() - startTime + repo.lifetimeMillis
    repo.lifetimeMillis = totalTime // persist to the repository
}

Upvotes: 2

Related Questions