有了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或默认浏览器,这个计数是可以的。
代码中有没有bug?为什么它不适用于所有已安装的应用程序?有没有其他方法可以得到同样的结果?
发布于 2019-07-23 20:12:43
您好,我正在尝试此代码,我在whatsapp上也遇到了同样的问题,但我尝试删除此代码
System.out.println(eventAux.getPackageName()+" "+eventAux.MOVE_TO_FOREGROUND );它工作了,计数是正确的,谢谢
https://stackoverflow.com/questions/46650520
复制相似问题