Fobi
Fobi

Reputation: 445

Count how many times every app is used in one day using UsageEvents, UsageEvents.Event and MOVE_TO_FOREGROUND

With UsageStatsManager and UsageStats I'm able to obtain the daily usage (in hours, minutes and seconds) of every app on my smartphone. Now I want to know if there is a way to obtain the daily frequency of use (in numbers of times, i.e. 1 time, 2 times, etc) of every app on my smartphone.

Reading the documentation I deduced that this could be achieved using UsageEvents, UsageEvents.Event and MOVE_TO_FOREGROUND. So I wrote the following code:

// Get the app statistics since one day ago from the current time.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR_OF_DAY, -1);

/* Query for events in the given time range. Events are only kept by the system for a few days.
 * NOTE: The last few minutes of the event log will be truncated to prevent abuse by applications. */
UsageEvents queryEvents = mUsageStatsManager.queryEvents(
            cal.getTimeInMillis(),     //begin-time
            System.currentTimeMillis()); //end-time

ArrayList<String> packagesNames = new ArrayList<>();

// I get a list with package names having an event of "MOVE_TO_FOREGROUND"
while (queryEvents.hasNextEvent()) {
        UsageEvents.Event eventAux = new UsageEvents.Event();
        queryEvents.getNextEvent(eventAux);
        if (eventAux.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) {
            packagesNames.add(eventAux.getPackageName());
            System.out.println(eventAux.getPackageName()+" "+eventAux.MOVE_TO_FOREGROUND );
        }
}

// I count the occurrences of each packet name.
Set<String> unique = new HashSet<String>(packagesName);
for (String key : unique) {
        System.out.println(key + ": " + Collections.frequency(packagesName, key));
}

But after several tests I noticed that for example, if I open Whatsapp once, its daily use count is increased by 2 units (and not by 1 unit), while for other apps like Facebook or the default browser, the count is ok.

Is there any bug in the code? Why does it not work for all installed applications? Is there another way to get the same result?

Upvotes: 1

Views: 991

Answers (1)

Kukuh Iman
Kukuh Iman

Reputation: 9

hello i was trying this code, i also got the same problem on whatsapp, but i try to remove this code

System.out.println(eventAux.getPackageName()+" "+eventAux.MOVE_TO_FOREGROUND );

and it work, the count is correct, thank you

Upvotes: -1

Related Questions