androidkotlinchronometer

One Chronometer for all Activities


I am making a simple app where there is the main activity which has buttons that lead to new activities. These activities all have the same bottom sheet with a stopwatch. I want to be able to start the stopwatch in one activity, go to main activity then to another activity and it is still counting.

Essentially, I want to have one common stopwatch for all the activities.

What would be the easiest approach to this?

I am writing my app in Kotlin.

Thank you for your help!


Solution

  • Essentially what you wish to achieve is to have an object that outlives the scope of activity/fragment, and is accessible within the app.

    For this, you can instantiate objects within the 'Application' scope. For your case, given you wish to have only one object, you can very well utilise the 'Singleton' pattern. Here's a simple explanation of Singleton pattern, along with a sample implementation of the same in Kotlin-> https://blog.mindorks.com/how-to-create-a-singleton-class-in-kotlin

    Use this object as a data source in your code. In your case, it would contain functions to reset the timer, start the timer etc.