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

懵懂的女人 提交于 2019-12-24 09:31:18

问题


With UsageStatsManager and UsageStats I'm able to obtain the daily usage (in houres, minuts 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 times, 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 one time Whatsapp, 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 not it work for all installed applications? Is there another way to get the same result? Thanks in advance.


回答1:


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



来源:https://stackoverflow.com/questions/46650520/count-how-many-times-every-app-is-used-in-one-day-using-usageevents-usageevents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!