安卓:每小时获取使用情况统计

8

我使用安卓的UsageStats功能,但是最小的时间间隔只有DAILY INTERVAL

long time = System.currentTimeMillis();
List<UsageStats> appList = manager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - DAY_IN_MILLI_SECONDS, time);

我该如何每小时获取UsageStats


所以你需要每小时运行你的代码。 - user10351180
1
我读到,即使您选择了持续五分钟的时间框架,如果您选择了INTERVAL_WEEKLY作为intervalType,则会获取该间隔内的所有统计信息。 - Rougher
@Rougher 你的问题解决了吗?如果我现在提供正确的答案,对你有帮助吗?我在这个领域工作了很多。 - Md. Sabbir Ahmed
嘿,@SabbirAhmed。我仍在寻找解决方案。非常感谢任何帮助。 - Rougher
@Rougher 好的,我会尽力帮助你。 - Md. Sabbir Ahmed
请检查答案。 - Md. Sabbir Ahmed
4个回答

11
所有功劳归功于这个答案。我从那里学到了很多。
我们必须调用queryEvents(long begin_time, long end_time)方法,因为它将提供从begin_timeend_time的所有数据。它通过foregroundbackground事件而不是像queryUsageStats()方法一样提供总使用时间来给出每个应用程序的数据。因此,使用前景和背景事件时间戳,我们可以计算启动应用程序的次数,并找出每个应用程序的使用持续时间。
收集最近1小时应用程序使用数据的实现

首先,在AndroidManifest.xml文件中添加以下行,并请求用户获取使用访问权限。

<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" />

在任何方法内添加以下行。
    long hour_in_mil = 1000*60*60; // In Milliseconds
    long end_time = System.currentTimeMillis();
    long start_time = end_time - hour_in_mil;

然后,调用方法 getUsageStatistics()
    getUsageStatistics(start_time, end_time);

getUsageStatistics方法

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
void getUsageStatistics(long start_time, long end_time) {

    UsageEvents.Event currentEvent;
  //  List<UsageEvents.Event> allEvents = new ArrayList<>();
    HashMap<String, AppUsageInfo> map = new HashMap<>();
    HashMap<String, List<UsageEvents.Event>> sameEvents = new HashMap<>();

    UsageStatsManager mUsageStatsManager = (UsageStatsManager)
            context.getSystemService(Context.USAGE_STATS_SERVICE);

    if (mUsageStatsManager != null) {
        // Get all apps data from starting time to end time
        UsageEvents usageEvents = mUsageStatsManager.queryEvents(start_time, end_time);

        // Put these data into the map
        while (usageEvents.hasNextEvent()) {
            currentEvent = new UsageEvents.Event();
            usageEvents.getNextEvent(currentEvent);
            if (currentEvent.getEventType() == UsageEvents.Event.ACTIVITY_RESUMED ||
                    currentEvent.getEventType() == UsageEvents.Event.ACTIVITY_PAUSED) {
              //  allEvents.add(currentEvent);
                String key = currentEvent.getPackageName();
                if (map.get(key) == null) {
                    map.put(key, new AppUsageInfo(key));
                    sameEvents.put(key,new ArrayList<UsageEvents.Event>());
                }
                sameEvents.get(key).add(currentEvent);
            }
        }

        // Traverse through each app data which is grouped together and count launch, calculate duration
        for (Map.Entry<String,List<UsageEvents.Event>> entry : sameEvents.entrySet()) {
            int totalEvents = entry.getValue().size();
            if (totalEvents > 1) {
                for (int i = 0; i < totalEvents - 1; i++) {
                    UsageEvents.Event E0 = entry.getValue().get(i);
                    UsageEvents.Event E1 = entry.getValue().get(i + 1);

                    if (E1.getEventType() == 1 || E0.getEventType() == 1) {
                        map.get(E1.getPackageName()).launchCount++;
                    }

                    if (E0.getEventType() == 1 && E1.getEventType() == 2) {
                        long diff = E1.getTimeStamp() - E0.getTimeStamp();
                        map.get(E0.getPackageName()).timeInForeground += diff;
                    }
                }
            }

    // If First eventtype is ACTIVITY_PAUSED then added the difference of start_time and Event occuring time because the application is already running.
            if (entry.getValue().get(0).getEventType() == 2) {
                long diff = entry.getValue().get(0).getTimeStamp() - start_time;
                map.get(entry.getValue().get(0).getPackageName()).timeInForeground += diff;
            }
            
    // If Last eventtype is ACTIVITY_RESUMED then added the difference of end_time and Event occuring time because the application is still running .
            if (entry.getValue().get(totalEvents - 1).getEventType() == 1) {
                long diff = end_time - entry.getValue().get(totalEvents - 1).getTimeStamp();
                map.get(entry.getValue().get(totalEvents - 1).getPackageName()).timeInForeground += diff;
            }
        }
    
    smallInfoList = new ArrayList<>(map.values());

    // Concatenating data to show in a text view. You may do according to your requirement
    for (AppUsageInfo appUsageInfo : smallInfoList)
    {
        // Do according to your requirement
        strMsg = strMsg.concat(appUsageInfo.packageName + " : " + appUsageInfo.launchCount + "\n\n");
    }

    TextView tvMsg = findViewById(R.id.MA_TvMsg);
    tvMsg.setText(strMsg);
       
    } else {
        Toast.makeText(context, "Sorry...", Toast.LENGTH_SHORT).show();
    }

}

AppUsageInfo.class

import android.graphics.drawable.Drawable;

class AppUsageInfo {
    Drawable appIcon; // You may add get this usage data also, if you wish.
    String appName, packageName;
    long timeInForeground;
    int launchCount;

    AppUsageInfo(String pName) {
        this.packageName=pName;
    }
}

如何定制这些代码以收集每小时的数据?

如果您想获取每小时的数据,请更改end_timestart_time值以获取每小时的数据。例如:如果我要收集过去每小时的数据(对于过去2小时的数据),我会执行以下操作。

    long end_time = System.currentTimeMillis();
    long start_time = end_time - (1000*60*60);

    getUsageStatistics(start_time, end_time);

    end_time =  start_time;
    start_time = start_time - hour_in_mil;

    getUsageStatistics(start_time, end_time);

然而,您可以使用 Handler 跳过反复编写 start_timeend_time 以更改这些变量的值。每次收集一小时的数据后,将完成一个任务,并在自动更改变量的值后再次调用 getUsageStatistics 方法。
注意:也许您将无法检索超过过去7.5天的数据,因为系统仅保留了几天的事件

2
@SabbirAhmed,太好了!我只是因为API 29中的弃用,将UsageEvents.Event.MOVE_TO_FOREGROUND更改为UsageEvents.Event.ACTIVITY_RESUMED,将UsageEvents.Event.MOVE_TO_BACKGROUND更改为UsageEvents.Event.ACTIVITY_PAUSED。 - Rougher
@Rougher 非常愉快地能帮到你。同时感谢这个信息(关于 API 29 中的弃用)。 - Md. Sabbir Ahmed

0
    Calendar cal = (Calendar) Calendar.getInstance().clone();
    //I used this and it worked, only for 7 days and a half ago 
    if (daysAgo == 0) {
        //Today - I only count from 00h00m00s today to present

        end = cal.getTimeInMillis();
        start = LocalDate.now().toDateTimeAtStartOfDay().toInstant().getMillis();
    } else {
        long todayStartOfDayTimeStamp = LocalDate.now().toDateTimeAtStartOfDay().toInstant().getMillis();
        if (mDaysAgo == -6) {
            //6 days ago, only get events in time -7 days to -7.5 days

            cal.setTimeInMillis(System.currentTimeMillis());
            cal.add(Calendar.DATE, daysAgo + 1);
            end = cal .getTimeInMillis();
            start = end - 43200000;
        } else {
            //get events from 00h00m00s to  23h59m59s
            //Current calendar point to 0h0m today
            cal.setTimeInMillis(todayStartOfDayTimeStamp);
            cal.add(Calendar.DATE, daysAgo + 1);
            end = calendar.getTimeInMillis();
            cal.add(Calendar.DATE, -1);
            start = calendar.getTimeInMillis();
        }
    }

-2

我认为这是不可能的,即使你在一个时间间隔中请求数据,看起来数据也是存储在桶中,最小的桶是一天。 在UsageStatsManager文档中,它说:

在时间间隔中间请求数据将包括该间隔。

此外,INTERVAL_BEST不是真正的时间间隔,它只是选择给定时间范围内可用间隔之一。在UsageStatsManager.java源代码中,它说:

/**
 * The number of available intervals. Does not include {@link #INTERVAL_BEST}, since it
 * is a pseudo interval (it actually selects a real interval).
 * {@hide}
 */
public static final int INTERVAL_COUNT = 4;

我在我的帖子评论中写了它。 - Rougher

-3

是的,Android提供了最小的INTERVAL_DAILY。但为了获得最佳结果,您可以使用INTERVAL_BEST。在queryUsageStats(int,long,long)中,Android为给定时间范围提供了最佳间隔计时器。

编码愉快...


我看到了INTERVAL_BEST,但我不明白如何知道时间间隔是多少?我想每小时得到类似这样的东西:whatsapp - 30分钟,youtube - 25分钟,facebook - 5分钟。 - Rougher

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接