简体   繁体   English

使用 UsageEvents、UsageEvents.Event 和 MOVE_TO_FOREGROUND 计算每个应用程序在一天内使用的次数

[英]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.使用 UsageStatsManager 和 UsageStats,我可以获得智能手机上每个应用程序的每日使用情况(以小时、分钟和秒为单位)。 Now I want to know if there is a way to obtain the daily frequency of use (in numbers of times, ie 1 time, 2 times, etc) of every app on my smartphone.现在我想知道是否有办法获得我智能手机上每个应用程序的每日使用频率(以次数为单位,即1次、2次等)。

Reading the documentation I deduced that this could be achieved using UsageEvents, UsageEvents.Event and MOVE_TO_FOREGROUND.阅读文档我推断这可以使用 UsageEvents、UsageEvents.Event 和 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.但是经过几次测试,我注意到,例如,如果我打开一次 Whatsapp,它的每日使用计数会增加 2 个单位(而不是 1 个单位),而对于 Facebook 或默认浏览器等其他应用程序,计数还可以。

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?有没有另一种方法可以获得相同的结果?

hello i was trying this code, i also got the same problem on whatsapp, but i try to remove this code你好,我正在尝试此代码,我在 whatsapp 上也遇到了同样的问题,但我尝试删除此代码

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

and it work, the count is correct, thank you它有效,计数正确,谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM