How to find out the app (Whats App) usage duration?

Rishabh Bhardwaj picture Rishabh Bhardwaj · Sep 21, 2015 · Viewed 8.7k times · Source

I've been looking around trying to figure out a way to find out how much time I spend on Whatsapp. I found a couple of apps on the Playstore:

https://play.google.com/store/apps/details?id=com.agrvaibhav.AppUsageTracking&hl=en

The size of such apps is less than 1MB, so I'm guessing its a fairly easy piece of code, but I can't find a way anywhere.

All links either provide a way to let me know how much my own app is being used, or they say this is a possible intrusion of privacy [bizarre!].

The code * # * # 7 8 6 # * # * supposedly is supposed to work, but crashes every time I try.

I have searched hard and can't find a solution anywhere. One possible way I thought of is by running a service that tracks all open apps - but I'm not sure if that's possible in Android.

Answer

Rishabh Bhardwaj picture Rishabh Bhardwaj · Nov 12, 2015

Yes, Usage Stats API is the answer. Struggled to figure it out initially, but I have finally managed to do so.

The permission required is :

<uses-permission
android:name="android.permission.PACKAGE_USAGE_STATS"
tools:ignore="ProtectedPermissions" />

Code to get app usage:

 final UsageStatsManager usageStatsManager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);// Context.USAGE_STATS_SERVICE);
            Calendar beginCal = Calendar.getInstance();
            beginCal.set(Calendar.DAY_OF_MONTH, 11);
            beginCal.set(Calendar.MONTH, 10);
            beginCal.set(Calendar.YEAR, 2015);

            Calendar endCal = Calendar.getInstance();
            endCal.set(Calendar.DAY_OF_MONTH, 12);
            endCal.set(Calendar.MONTH, 10);
            endCal.set(Calendar.YEAR, 2015);

final List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, beginCal.getTimeInMillis(), endCal.getTimeInMillis());
System.out.println("results for " + beginCal.getTime().toGMTString() + " - " + endCal.getTime().toGMTString());
for (UsageStats app : queryUsageStats) {
    System.out.println(app.getPackageName() + " | " + (float) (app.getTotalTimeInForeground() / 1000));
}

Open permissions using :

Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
startActivity(intent);

This question helped figure it all out. Better documentation on the Android website would have helped greatly.

Here are a couple of links that helped me:

https://github.com/googlesamples/android-AppUsageStatistics

How to use UsageStatsManager?