1

使用 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 或默认浏览器等其他应用程序,计数是可以的。

代码中是否有任何错误?为什么它不适用于所有已安装的应用程序?有没有其他方法可以获得相同的结果?

4

1 回答 1

-1

您好,我正在尝试此代码,我在 whatsapp 上也遇到了同样的问题,但我尝试删除此代码

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

它工作,计数是正确的,谢谢

于 2019-07-23T12:12:42.613 回答