I have created a Service in which I check for foreground activity using 'UsageEvents'.
private void getForegroundActivity() {
String packageName = "";
String className = "";
Calendar cal_begin = Calendar.getInstance();
cal_begin.set(Calendar.YEAR, -1);
long _begTime = cal_begin.getTimeInMillis();
long _endTime = System.currentTimeMillis();
UsageStatsManager usageStatsManager = (UsageStatsManager) this.getSystemService(Context.USAGE_STATS_SERVICE);
if (usageStatsManager != null) {
UsageEvents queryEvents = usageStatsManager.queryEvents(_begTime, _endTime);
if (queryEvents != null) {
UsageEvents.Event event = new UsageEvents.Event();
while (queryEvents.hasNextEvent()) {
UsageEvents.Event eventAux = new UsageEvents.Event();
queryEvents.getNextEvent(eventAux);
if (eventAux.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) {
event = eventAux;
}
}
packageName = event.getPackageName();
className = event.getClassName();
}
The above code works fine and gives proper foreground activity, but after some time(let's say 2-3 hours later), the 'queryEvents(_begTime, _endTime)
'returns '0'(zero) counts !!
Is there some other way of using usageStatsManager.queryEvents()
in Service ?
Any other pointers, ideas are appreciated.
The events returned by queryEvents()
are kept by the system only for a few days. So, you might have to maintain a local database to maintain those stats locally. There is no problem in your code.
For more information about queryEvents()
method and UsageStatsManager, checkout the below link :