How to Get the Time spent on an application in Android Programmatically

Apps with usage access settings Activity Classes :- package com.example.android.appusagestatistics; import android.app.Activity; import android.app.usage.UsageStats; import android.app.usage.UsageStatsManager; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; import java.text.DateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import android.text.format.DateUtils; import android.util.ArrayMap; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import … Read more

How to count app usage time while app is on foreground?

I’ve solved the issue. Adding difference of current time and timestamp of current running app going foreground does the trick. I just added the following code before the return statement: UsageEvents.Event lastEvent = allEvents.get(allEvents.size() – 1); if(lastEvent.getEventType() == UsageEvents.Event.ACTIVITY_RESUMED) { int diff = (int)System.currentTimeMillis() – (int)lastEvent.getTimeStamp(); diff /= 1000; Integer prev = appUsageMap.get(lastEvent.getPackageName()); if(prev == … Read more

How to check if “android.permission.PACKAGE_USAGE_STATS” permission is given?

Special permissions that are granted by the user in the system settings (usage stats access, notification access, …) are handled by AppOpsManager, which was added in Android 4.4. Note that besides user granting you access in the system settings you typically need a permission in the Android manifest (or some component), without that your app … Read more