Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to determine the current foreground (running) application (using a service?)

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

like image 689
Faas Avatar asked Nov 10 '22 21:11

Faas


1 Answers

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.

like image 172
Atiq Avatar answered Nov 14 '22 22:11

Atiq