I use UsageStats
feature of Android, but the smallest interval is DAILY INTERVAL
.
long time = System.currentTimeMillis();
List<UsageStats> appList = manager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - DAY_IN_MILLI_SECONDS, time);
How can I get UsageStats
in an hourly interval?
Yes, Android is providing minimum
INTERVAL_DAILY
. But for the best result, you can useINTERVAL_BEST
. Android is giving the best interval timer for the given time range inqueryUsageStats(int, long, long)
.Happy coding...
All credit goes to this answer. I have learned from that one.
How can we collect app usage data for customized time range (e.g. for per 1 hour)?
We have to call
queryEvents(long begin_time, long end_time)
method as it will provide us all data starting frombegin_time
toend_time
. It give us each app data throughforeground
andbackground
events instead of total spent time likequeryUsageStats()
method. So, using foreground and background events time stamp, we can count the number of times an app has been launched and also can find out the usage duration for each app.Implementation to Collect Last 1 Hour App Usage Data
At first, add the following line in the
AndroidManifest.xml
file and also request user to get permission of usage access.Add the following lines inside any method
Then, call the method
getUsageStatistics()
getUsageStatistics methiod
AppUsageInfo.class
How can I customize these codes to collect per 1 hour data?
As you want to get per hour data, please change the
end_time
andstart_time
value for every hour data. For instance: If I would try to collect past per hour data (for past 2 hour data). I would do the following thing.However, you may use a
Handler
to skip repeatedly writingstart_time
andend_time
to change value of these variables. Each time data will be collected for one hour, a task will be completed and after automatically changing the values of the variables, you will again call thegetUsageStatistics
method.Note: Maybe, you will not be able to retrieve data for more than past 7.5 days as events are only kept by the system for a few days.
I don't think it's possible, even if you ask for data in the middle of an interval, it looks like the data is stored in buckets and the minimum bucket is a day. In UsageStatsManager documentation, it says:
Also,
INTERVAL_BEST
is not a real interval, it just selects one of the available intervals for the given time range. In UsageStatsManager.java source code, it says: