Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/398.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 安卓:每小时获取USAGests_Java_Android_Usage Statistics - Fatal编程技术网

Java 安卓:每小时获取USAGests

Java 安卓:每小时获取USAGests,java,android,usage-statistics,Java,Android,Usage Statistics,我使用安卓的UsageStats功能,但最小的间隔是每日间隔 long time = System.currentTimeMillis(); List<UsageStats> appList = manager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - DAY_IN_MILLI_SECONDS, time); long time=System.currentTimeMillis(); List appList=

我使用安卓的
UsageStats
功能,但最小的间隔是
每日间隔

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

如何在每小时间隔内获取
USAGests

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


快乐编码…

我不认为这是可能的,即使你在间隔中间要求数据,看起来数据是存储在桶里,最小桶是一天。 在文件中,它说:

在时间间隔中间的数据请求将包括该间隔。 而且,

INTERVAL\u BEST
不是一个真正的间隔,它只是为给定的时间范围选择一个可用的间隔。在里面 源代码,它说:

/**
 * 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;
所有的功劳都归于他。我从中吸取了教训

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

我们必须调用该方法,因为它将为我们提供从
begin\u time
end\u time
的所有数据。它通过
前台
后台
事件提供每个应用程序的数据,而不是总花费时间的方法。因此,使用前台和后台事件时间戳,我们可以计算一个应用程序启动的次数,还可以找出每个应用程序的使用持续时间

收集最近1小时应用程序使用数据的实施

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

<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" />
然后,调用方法
getUsageStatistics()

妊娠统计法

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

由于要获取每小时数据,请更改每小时数据的
结束时间
开始时间
值。例如:如果我试图收集过去每小时的数据(过去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);
但是,您可以使用
处理程序
跳过重复写入
开始时间
结束时间
来更改这些变量的值。每次收集一小时的数据时,将完成一项任务,在自动更改变量的值后,您将再次调用
getUsageStatistics
方法


注意:可能在过去的7.5天内,您无法检索数据。

我看到了INTERVAL\u的最佳状态,但我不明白如何知道什么是INTERVAL?我希望每小时都能得到这样的东西:whatsapp-30分钟,youtube-25分钟,facebook-5分钟。所以你需要每小时运行你的代码。我读到,即使你选择的时间框架持续五分钟,如果你选择INTERVAL\u WEEKLY作为intervalType,你会得到该时间间隔内的所有统计数据。@你的问题解决了吗?如果我现在提供正确的答案,对你有帮助吗?我在这方面做了很多工作。我仍然在寻找解决方案。感谢您的每一个帮助。@拉夫尔:好的,我会尽我最大的努力帮助您。这是我在帖子的评论中写的。@SabbirAhmedת伟大的解决方案!我只将UsageEvents.Event.MOVE_TO_前台更改为UsageEvents.Event.ACTIVITY_继续,将UsageEvents.Event.MOVE_TO_后台更改为UsageEvents.Event.ACTIVITY_由于API中的不推荐而暂停29@Rougher很高兴能帮助你。也感谢您提供这些信息(API 29中的弃用)。
    getUsageStatistics(start_time, end_time);
@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();
    }

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