androidforegroundusage-statisticsusagestatsmanager

How to detect an application foreground time?


How to find the spent time of android application used in foreground. i have used UsageStatsManager but it doesn't return the list of packages.
sample code used from this link


Solution

  • I think the best option is to use lifecycle callback methods of your activities. The start time is onCreate() of the first activity you show to your user. The end time may be a bit more tricky. First of all, if you have multiple activities, user can exit any of them, so you need to track the currently opened activity and send the end-time only if the next activity doesn't appear. The second problem is which callback method should you use? onPause() isn't guaranteed to be called, and onDestroy() won't be called until the application is cleared from recents. So probablt onStop() is the right place.

    Or you can use the callbacks of your application. Just derive from Application class and use it's callbacks for your time tracking.