1

I know how to track time when out of the current app. For instance I could start recording time the moment my app loads another app - then if the user comes back to my app in the onResume i can end the time and calculate duration.

The problem is if the user loads the other app from my app, then presses the home button and goes and uses other apps. I don't want to track that time. I only want to track the time used in a specific app. How do I do this?

The use case of this is that this app is an education app that tracks how much time you spend in certain education apps. If the student was to close the education app and play a game app instead, I would not want to count that as valid time.

Spentak
  • 3,359
  • 3
  • 21
  • 31
  • possible duplicate of [Android: How can I get the current foreground activity (from a service)?](http://stackoverflow.com/questions/3873659/android-how-can-i-get-the-current-foreground-activity-from-a-service) – 323go Sep 23 '13 at 18:35

2 Answers2

2

Something very similar was asked previously on StackOverflow, and I think you might be able to use this answer:

https://stackoverflow.com/a/4753333/762442

In short, you can use the activity manager to get a list of running tasks, and since it always returns the active task first, you'll be able to - somewhat - achieve what you're asking for.

I don't think you'll be able to track the exact time spent in each application, but you'll be able to track how long each application has been active. I don't know if that's enough for you.

Community
  • 1
  • 1
Michell Bak
  • 13,182
  • 11
  • 64
  • 121
  • To a degree, yes. But what appears at the top of the results isn't necessarily the top app, or at least not meaningfully so - for example, on at least some Android versions that can report the soft keyboard IME, rather than the app on behalf of which it is accepting input. – Chris Stratton Sep 23 '13 at 18:40
  • Yeah, it's far from a perfect solution. But I think it's the closest he can get using Android's API's. – Michell Bak Sep 23 '13 at 18:41
  • This solution works. I basically run a loop every minute or so to detect if the top running app is the approved app. If not we stop the time then restart my app (effectively kicking them out of the un-approved app) – Spentak Sep 23 '13 at 21:09
1

There is no way you can do this. You can track only your Activities time.

Yaroslav Mytkalyk
  • 16,950
  • 10
  • 72
  • 99