通过UsageStatsManager 和UsageStats,我能够获取智能手机上每个应用程序的每日使用情况(以小时、分钟和秒为单位)。现在我想知道是否有一种方法可以获得我智能手机上每个应用程序的每日使用频率(以次数为单位,即1次、2次等)。
阅读文档后,我推断这可以使用UsageEvents、UsageEvents.Event 和MOVE_TO_FOREGROUND 来实现。所以我写了下面的代码:
// 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));
}
但经过几次测试后,我注意到,例如,如果我打开一次 Whatsapp,其每日使用次数会增加 2 个单位(而不是 1 个单位),而对于 Facebook 或默认浏览器等其他应用程序,该次数还可以。
代码中是否有任何错误?为什么它不适用于所有已安装的应用程序?还有其他方法可以得到相同的结果吗?
最佳答案
你好,我正在尝试这段代码,我在 Whatsapp 上也遇到了同样的问题,但我尝试删除这段代码
System.out.println(eventAux.getPackageName()+" "+eventAux.MOVE_TO_FOREGROUND );
成功了,计数正确,谢谢
关于java - 使用UsageEvents、UsageEvents.Event 和 MOVE_TO_FOREGROUND 计算每个应用一天内的使用次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46650520/