Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get how long an activity is active in foreground on Android

How to get the amount of time an activity was in foreground in Android. For Ex. If WhatsApp was used 1 hour today, how to get that WhatsApp was active for one hour, programmatically.

like image 371
Aneez Avatar asked Dec 10 '16 15:12

Aneez


2 Answers

The App usage statistics API allows app developers to collect statistics related to usage of the applications. This API provides more detailed usage information than the deprecated getRecentTasks() method.

To use this API, you must first declare the android.permission.PACKAGE_USAGE_STATS permission in your manifest. The user must also enable access for this app through Settings > Security > Apps with usage access.

To collect the statistics of the app usage, you need to first get the instance of UsageStatsManager by the following code:

mUsageStatsManager = (UsageStatsManager) getActivity()
       .getSystemService(Context.USAGE_STATS_SERVICE);

Then you can retrieve the statistics of the app usage by the following method:

Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, -1);
List<UsageStats> queryUsageStats = mUsageStatsManager
        .queryUsageStats(UsageStatsManager.INTERVAL_DAILY, cal.getTimeInMillis(),
                System.currentTimeMillis());

The first argument of the queryUsageStats() is used for the time interval by which the stats are aggregated. The second and the third arguments are used for specifying the beginning and the end of the range of the stats to include in the results.

Here is a basic app code on GitHub showing how to use App usage statistics API to let users collect statistics related to usage of the applications.

Note: android.app.usage required API level 21 or above.

like image 191
Priyank Patel Avatar answered Sep 29 '22 20:09

Priyank Patel


Android have a built-in tool for that named "dumpsys".
Most of it's features are for developers throw ADB, but for your purposes you should dig into UsageStatsManager which will provide you the data you need about other apps.

like image 43
Nir Duan Avatar answered Sep 29 '22 20:09

Nir Duan