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

I am creating an application that should determine the running time of the application, so I can show user statistics of the applications that it uses. I found several solutions on the Internet, but they all have their drawbacks.

Here are the two best options I've found:

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

    getRunningTasks(int maximum)

  • Using the new "Application Usage Statistics " is introduced in Lollipop, but this solution will only work with devices running Android> 5.0. But I also want to support older devices.

I also looked for the intention to shoot when the application starts or stops, but it seems to be none (see the summary). This post confirms this. I also found a class: ActivityLifecycleCallbacks , which receives callbacks when the activity state changes. But this is only for internal use (read inside your own application).

So, my idea is to use the service to poll the current foreground application on devices running a version other than lollipop, and use the new API on devices running on candy or more. But is this a β€œservice” idea a better option because, as I said, it seems like an inefficient battery? Maybe there are better options?

Faas

+5
source share
1 answer

Option 1 is definitely bad as it is deprecated.

I would prefer you use android.app.usage

What the application you are quoting is likely to do is spend a lot of time on the processor, RAM and battery life, constantly monitoring the ActivityManager.

Keep in mind that what you propose to track, if you plan to have anyone other than the user, access to it borders on privacy violations of the type that received CarrierIQ, to a sufficient extent.

+1
source

Source: https://habr.com/ru/post/1209097/


All Articles