6

I am building an application which needs to determine the time an app has been running, so I can show the user statistics of the apps he / she uses. I found multiple solutions online but al those have their flaws.

Here are the two best options I found:

  • Using a polling mechanism with a service. This solution seems battery inefficient and depends on a deprecated method (since API level 21):

    getRunningTasks(int maximum)

  • Using the new "App usage statistics" introduces in Lollipop, but this solution will only work with devices running android > 5.0. But I want to support older devices as well.

I have also searched for a intent firing when a app starts or stops but there seems to be none (see Summary). This post confirms that. Also I found a class: ActivityLifecycleCallbacks which gets callbacks when a activity changes it state. But this is only for internal (read inside your own application) use.

So my idea is to use a service to poll the current foreground app on devices which are running version other than lollipop and use the new API on devices running lollipop or greater. But is this "service" idea the best option because as I said before it seems battery inefficient? Maybe there are better options?

Faas

Community
  • 1
  • 1
Faas
  • 417
  • 1
  • 4
  • 14
  • if all your concerns are about deprecated methods, just put a build version check and use methods accordingly. – DroidDev Dec 15 '14 at 12:27
  • No my concerns are about if this "service" idea is a good solution for the problem. I want the most efficient solution for this problem and in my opinion this "service" idea is far from efficient. – Faas Dec 15 '14 at 12:52

1 Answers1

0

1st option is definitely bad as it is deprecated.

I would rather suggest you to use android.app.usage

What the app you cite is probably doing is wasting a lot of CPU time, RAM, and battery life, polling ActivityManager continuously.

Bear in mind that what you propose to track, if you plan on having anyone other than the user access it, borders on privacy violations of the type that got CarrierIQ in a fair amount of trouble.

Atiq
  • 396
  • 1
  • 3
  • 10
  • Hi, I'm working on similar thing in Android. You suggested using android.app.usage, but this is introduced in API 21, so won't work for API < 21. Do you have a workaround for older APIs. I'm indeed, using a service continuously, though I realize it's a bad option, I haven't had much success finding any other way to do this. – gaurav jain Dec 15 '14 at 16:14
  • you can try using ./adb shell dumpsys usagestats However, for dumpsys you need the android.permission.DUMP, which I believe cannot be used unless the app is in the system partition. – Atiq Dec 16 '14 at 05:30