使用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或默认浏览器,计数是好。
代码中是否有任何错误?为什么它不适用于所有已安装的应用程序?有没有其他方法可以得到相同的结果? 提前谢谢。
答案 0 :(得分:0)
你好,我在尝试这段代码,在whatsapp上也遇到了同样的问题,但是我尝试删除此代码
System.out.println(eventAux.getPackageName()+" "+eventAux.MOVE_TO_FOREGROUND );
工作正常,计数正确,谢谢