Android:每小时获取 UsageStats

Rou*_*her 3 java android usage-statistics

我使用UsageStatsAndroid 的功能,但最小间隔是DAILY INTERVAL.

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

我怎样才能进入UsageStats每小时的间隔?

Sab*_*med 6

所有功劳都归功于这个答案。我从那个人那里学到了。

我们如何收集自定义时间范围内的应用使用数据(例如每 1 小时)?

我们必须调用queryEvents(long begin_time, long end_time)方法,因为它将为我们提供从begin_time到 的所有数据end_time。它通过foregroundbackground事件为我们提供每个应用程序数据,而不是像queryUsageStats()方法那样的总花费时间。因此,使用前台和后台事件时间戳,我们可以计算应用程序启动的次数,还可以找出每个应用程序的使用时长。

收集过去 1 小时应用程序使用数据的实施

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

<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" />
Run Code Online (Sandbox Code Playgroud)

在任何方法中添加以下行

    long hour_in_mil = 1000*60*60; // In Milliseconds
    long end_time = System.currentTimeMillis();
    long start_time = end_time - hour_in_mil;
Run Code Online (Sandbox Code Playgroud)

然后调用方法 getUsageStatistics()

    getUsageStatistics(start_time, end_time);
Run Code Online (Sandbox Code Playgroud)

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();
    }

}
Run Code Online (Sandbox Code Playgroud)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

由于您想获取每小时数据,请更改每小时数据的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);
Run Code Online (Sandbox Code Playgroud)

但是,您可以使用 aHandler跳过重复写入start_timeend_time更改这些变量的值。每次收集数据一小时,将完成一项任务,在自动更改变量值后,您将再次调用该getUsageStatistics方法。

注意:也许,您将无法检索超过过去 7.5 天的数据,因为事件仅由系统保留几天

  • @SabbirAhmedת 伟大的解决方案!由于API 29中的弃用,我仅将UsageEvents.Event.MOVE_TO_FOREGROUND更改为UsageEvents.Event.ACTIVITY_RESUMED,将UsageEvents.Event.MOVE_TO_BACKGROUND更改为UsageEvents.Event.ACTIVITY_PAUSED (2认同)