Android应用统计-使用时长及次数统计(二)

关键字: 应用统计 Android源码 应用使用时长 应用使用次数

上篇文章主要讲解了如何获取关于系统统计应用使用记录的数据,包括系统初始数据events,系统统计数据Usage,以及通过反射获取的应用启动次数mLuanchCounts。本文将进一步说明系统数据的结构以及相关数据的记录方法。

Events文件

在 手机/data/system/usagestats(/user_id/TimeStamp) 这一文件夹中保存着关于系统记录的每一个activity的使用记录。每一个文件记录一天的数据,文件名为当天开始记录的时间戳,一般为早上8:00,每天到了8点钟都会重新新建另一文件进行记录。目测,是由于时区问题导致本应从零点开始的记录变成了八点。其主要格式如下:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<usagestats version="1" endTime="36503806">
    <packages>
        <package lastTimeActive="-1499212800000" lastTimeActiveSystem="30396792" package="com.android.providers.telephony" timeActive="0" lastEvent="0" beginIdleTime="601202961" />
        <package lastTimeActive="-1499212800000" lastTimeActiveSystem="35845563" package="com.android.providers.media" timeActive="0" lastEvent="0" beginIdleTime="606649836" />
        <package lastTimeActive="-1499212800000" lastTimeActiveSystem="35845563" package="com.android.providers.downloads" timeActive="0" lastEvent="0" beginIdleTime="606649836" />
        <package lastTimeActive="-1499212800000" lastTimeActiveSystem="30420851" package="com.android.providers.applications" timeActive="0" lastEvent="0" beginIdleTime="601225121" />
        <package lastTimeActive="-1499212800000" lastTimeActiveSystem="35832034" package="com.android.defcontainer" timeActive="0" lastEvent="0" beginIdleTime="606636305" />
        <package lastTimeActive="-1499212800000" lastTimeActiveSystem="23280068" package="com.android.stk" timeActive="0" lastEvent="0" beginIdleTime="598593891" />
        <package lastTimeActive="-1499212800000" lastTimeActiveSystem="30397034" package="com.android.printspooler" timeActive="0" lastEvent="0" beginIdleTime="601202961" />
        <package lastTimeActive="35844112" lastTimeActiveSystem="35844112" package="com.estrongs.android.pop" timeActive="190" lastEvent="2" beginIdleTime="606648382" />
        <package lastTimeActive="-1499212800000" lastTimeActiveSystem="30419146" package="com.android.keychain" timeActive="0" lastEvent="0" beginIdleTime="601223425" />
        <package lastTimeActive="-1499212800000" lastTimeActiveSystem="30399122" package="cn.trinea.android.developertools" timeActive="0" lastEvent="0" beginIdleTime="601203258" />
        <package lastTimeActive="-1499212800000" lastTimeActiveSystem="30396792" package="com.android.phone" timeActive="0" lastEvent="0" beginIdleTime="601202961" />
        <package lastTimeActive="-1499212800000" lastTimeActiveSystem="30420851" package="com.android.providers.userdictionary" timeActive="0" lastEvent="0" beginIdleTime="601225121" />
        <package lastTimeActive="36109708" lastTimeActiveSystem="36109708" package="com.android.systemui" timeActive="2262" lastEvent="2" beginIdleTime="606913979" />
        <package lastTimeActive="-1499212800000" lastTimeActiveSystem="30394681" package="com.android.exchange" timeActive="0" lastEvent="0" beginIdleTime="601198560" />
        <package lastTimeActive="-1499212800000" lastTimeActiveSystem="30407696" package="com.android.bluetooth" timeActive="0" lastEvent="0" beginIdleTime="601211967" />
        <package lastTimeActive="-1499212800000" lastTimeActiveSystem="30420851" package="com.android.providers.contacts" timeActive="0" lastEvent="0" beginIdleTime="601225121" />
    </packages>
    <configurations>
        <config lastTimeActive="30391702" timeActive="30" count="1" fs="1065353216" locale="zh-CN" touch="1" key="1" keyHid="1" hardKeyHid="2" nav="1" navHid="2" ori="1" scrLay="268435810" width="360" height="640" sw="360" density="320" />
        <config lastTimeActive="30391712" timeActive="10" count="1" fs="1065353216" locale="zh-CN" touch="3" key="1" keyHid="1" hardKeyHid="2" nav="1" navHid="2" ori="1" scrLay="268435810" width="360" height="640" sw="360" density="320" />
        <config lastTimeActive="30391713" timeActive="0" count="1" active="true" fs="1065353216" locale="zh-CN" touch="3" key="1" keyHid="1" hardKeyHid="2" nav="1" navHid="2" ori="1" scrLay="268435810" ui="17" width="360" height="640" sw="360" density="320" />
    </configurations>
    <event-log>
        <event time="28204060" package="com.estrongs.android.pop" class="com.estrongs.android.pop.app.InstallMonitorActivity" type="1" />
        <event time="28204136" package="com.estrongs.android.pop" class="com.estrongs.android.pop.app.InstallMonitorActivity" type="2" />
        <event time="28572043" package="com.estrongs.android.pop" class="com.estrongs.android.pop.app.InstallMonitorActivity" type="1" />
        <event time="28572093" package="com.estrongs.android.pop" class="com.estrongs.android.pop.app.InstallMonitorActivity" type="2" />
        <event time="28572101" package="com.wingbu.debug" class="com.wingbu.debug.DebugMainActivity" type="1" />
        <event time="28575595" package="com.wingbu.debug" class="com.wingbu.debug.DebugMainActivity" type="2" />
        <event time="28575642" package="com.wingbu.debug" class="com.wingbu.debug.statistics.UseTime.UseTimeActivity" type="1" />
        <event time="28758957" package="com.wingbu.debug" class="com.wingbu.debug.statistics.UseTime.UseTimeActivity" type="2" />
        <event time="28758999" package="com.wingbu.debug" class="com.wingbu.debug.statistics.UseTime.UseTimeDetailActivity" type="1" />
        <event time="28762433" package="com.wingbu.debug" class="com.wingbu.debug.statistics.UseTime.UseTimeDetailActivity" type="2" />
        <event time="30391673" package="android" type="5" fs="1065353216" locale="zh-CN" touch="1" key="1" keyHid="1" hardKeyHid="2" nav="1" navHid="2" ori="1" scrLay="268435810" width="360" height="640" sw="360" density="320" />
        <event time="30391703" package="android" type="5" fs="1065353216" touch="3" />
        <event time="30391713" package="android" type="5" fs="1065353216" ui="17" />
    </event-log>
</usagestats>

Event

例如
<event time="28572101" package="com.wingbu.debug" class="com.wingbu.debug.DebugMainActivity" type="1" />

用于每一次使用一个activity都进行记录,记录的粒度为activity(也包含每一条config),记录于系统的文件中,但是只记录距离今天7天之内的详细的Events数据,对于超过7天的数据,系统仅仅记录统计过后的数据,而不再保留详细的每一个event,记录其中包含的信息包括(请特别留意时间戳这一字段):Event源码链接

    public static final class Event {

        /**
         * No event type.
         */
        public static final int NONE = 0;

        /**
         * An event type denoting that a component moved to the foreground.
         * 当一个activity位于前台,为当前展示界面的时候,event的类型
         */
        public static final int MOVE_TO_FOREGROUND = 1;

        /**
         * An event type denoting that a component moved to the background.
         * 当一个activity位于后台,不为当前展示界面的时候,event的类型
         */
        public static final int MOVE_TO_BACKGROUND = 2;

        /**
         * An event type denoting that a component was in the foreground when the stats
         * rolled-over. This is effectively treated as a {@link #MOVE_TO_BACKGROUND}.
         * {@hide}
         * 因为event为每天记录在同一个文件中,当一个activity发生在需要记录的时候,如果需要另起一个文件进行记录,event的类型即为END_OF_DAY ,为当天最后一个event,接下来另起一文件进行记录。
         */
        public static final int END_OF_DAY = 3;

        /**
         * An event type denoting that a component was in the foreground the previous day.
         * This is effectively treated as a {@link #MOVE_TO_FOREGROUND}.
         * {@hide}
         *  类似的,每天文件记录,需要承接上一天的event,此类型为CONTINUE_PREVIOUS_DAY 
         */
        public static final int CONTINUE_PREVIOUS_DAY = 4;

       /**
         * An event type denoting that the device configuration has changed.
         * 当设备的configuration改变时,event的类型
         */
        public static final int CONFIGURATION_CHANGE = 5;

        /**
         * {@hide}
         * event所属的应用包名
         */
        public String mPackage;

        /**
         * {@hide}
         * event所属的类名,通常是activity名
         */
        public String mClass;

        /**
         * {@hide}
         * event记录的时间戳,文章开头列举的文件内容事例来看,显然这个时间戳不是绝对时间,而是相对时间,需加上文件名的时间戳,才是event发生的真实时间戳。
         */
        public long mTimeStamp;

        /**
         * event的类型,如前面代码中所显示的5种
         * {@hide}
         */
        public int mEventType;

        /**
         * Only present for {@link #CONFIGURATION_CHANGE} event types.
         * {@hide}
         */
        public Configuration mConfiguration;

    }

Configuration

这里就不展开讲述configuration标签的数据,此数据在统计中使用的概率不大,有兴趣的同学可自行查阅了解即可。具体参考连接如下:
记录文件中所使用的类:ConfigurationStats源码链接
Configuration说明链接
Configuration源码链接

UsageStats

对于UsageStats,用于记录系统中每一个应用的使用情况,记录的粒度为package,每一个UsageStats记录一个Package在一段时间内的使用信息,正如代码中所显示的,此类中大部分字段都是隐藏的,无法访问,其中就包括本文中比较关注的使用次数。但是并不要紧,正如上篇文章中讲到的,可以使用反射获取,但是,其实这一字段的值并不可靠,在接下来的文章中会有详细的说明。
部分源码如下:UsageStats 源码链接

/**
 * Contains usage statistics for an app package for a specific
 * time range.
 */
public final class UsageStats implements Parcelable {

    /**
     * {@hide}
     */
    public String mPackageName;

    /**
     * {@hide}
     */
    public long mBeginTimeStamp;

    /**
     * {@hide}
     */
    public long mEndTimeStamp;

    /**
     * {@hide}
     * 对于一个应用,最近一次的使用时间戳
     */
    public long mLastTimeUsed;

    /**
     * 对于一个应用,位于前台,被用户使用的总时长
     * {@hide}
     */
    public long mTotalTimeInForeground;

    /**
     * 对于一个应用,被用户使用的次数
     * {@hide}
     */
    public int mLaunchCount;

    /**
     * {@hide}
     */
    public int mLastEvent;
}

UsageStatsManager

最后来说一下UsageStatsManager ,系统提供给外部获取应用使用历史和统计信息的API。可以根据日,周,月,年四个时间范围进行查询。查询的数据包括:UsageStats(2个),Event(1个),Configurations(1个)
UsageStatsManager 源码链接

/**
     * Gets application usage stats for the given time range, aggregated by the specified interval.
     * <p>The returned list will contain a {@link UsageStats} object for each package that
     * has data for an interval that is a subset of the time range given. To illustrate:</p>
     * <pre>
    * intervalType = INTERVAL_YEARLY
     * beginTime = 2013
     * endTime = 2015 (exclusive)
     *
     * Results:
     * 2013 - com.example.alpha
     * 2013 - com.example.beta
     * 2014 - com.example.alpha
     * 2014 - com.example.beta
     * 2014 - com.example.charlie
     * </pre>
     *
     * @param intervalType The time interval by which the stats are aggregated.
     * @param beginTime The inclusive beginning of the range of stats to include in the results.
     * @param endTime The exclusive end of the range of stats to include in the results.
     * @return A list of {@link UsageStats} or null if none are available.
     *
     * @see #INTERVAL_DAILY
     * @see #INTERVAL_WEEKLY
     * @see #INTERVAL_MONTHLY
     * @see #INTERVAL_YEARLY
     * @see #INTERVAL_BEST
     */
    public List<UsageStats> queryUsageStats(int intervalType, long beginTime, long endTime) {
        try {
            @SuppressWarnings("unchecked")
            ParceledListSlice<UsageStats> slice = mService.queryUsageStats(intervalType, beginTime,
                    endTime, mContext.getOpPackageName());
            if (slice != null) {
                return slice.getList();
            }
        } catch (RemoteException e) {
            // fallthrough and return null.
        }
        return Collections.emptyList();
    }

    /**
     * Gets the hardware configurations the device was in for the given time range, aggregated by
     * the specified interval. The results are ordered as in
     * {@link #queryUsageStats(int, long, long)}.
     *
     * @param intervalType The time interval by which the stats are aggregated.
     * @param beginTime The inclusive beginning of the range of stats to include in the results.
     * @param endTime The exclusive end of the range of stats to include in the results.
     * @return A list of {@link ConfigurationStats} or null if none are available.
     */
    public List<ConfigurationStats> queryConfigurations(int intervalType, long beginTime,
            long endTime) {
        try {
            @SuppressWarnings("unchecked")
            ParceledListSlice<ConfigurationStats> slice = mService.queryConfigurationStats(
                   intervalType, beginTime, endTime, mContext.getOpPackageName());
           if (slice != null) {
                return slice.getList();
            }
        } catch (RemoteException e) {
           // fallthrough and return the empty list.
        }
        return Collections.emptyList();
    }

    /**
     * Query for events in the given time range. Events are only kept by the system for a few
     * days.
     * <p />
     * <b>NOTE:</b> The last few minutes of the event log will be truncated to prevent abuse
     * by applications.
     *
     * @param beginTime The inclusive beginning of the range of events to include in the results.
     * @param endTime The exclusive end of the range of events to include in the results.
     * @return A {@link UsageEvents}.
     */
    public UsageEvents queryEvents(long beginTime, long endTime) {
        try {
            UsageEvents iter = mService.queryEvents(beginTime, endTime,
                    mContext.getOpPackageName());
            if (iter != null) {
                return iter;
            }
        } catch (RemoteException e) {
            // fallthrough and return null
        }
        return sEmptyResults;
    }

    /**
     * A convenience method that queries for all stats in the given range (using the best interval
     * for that range), merges the resulting data, and keys it by package name.
     * See {@link #queryUsageStats(int, long, long)}.
     *
     * @param beginTime The inclusive beginning of the range of stats to include in the results.
     * @param endTime The exclusive end of the range of stats to include in the results.
     * @return A {@link java.util.Map} keyed by package name, or null if no stats are
     *         available.
     */
    public Map<String, UsageStats> queryAndAggregateUsageStats(long beginTime, long endTime) {
        List<UsageStats> stats = queryUsageStats(INTERVAL_BEST, beginTime, endTime);
        if (stats.isEmpty()) {
            return Collections.emptyMap();
        }

        ArrayMap<String, UsageStats> aggregatedStats = new ArrayMap<>();
        final int statCount = stats.size();
        for (int i = 0; i < statCount; i++) {
            UsageStats newStat = stats.get(i);
            UsageStats existingStat = aggregatedStats.get(newStat.getPackageName());
            if (existingStat == null) {
                aggregatedStats.put(newStat.mPackageName, newStat);
            } else {
                existingStat.add(newStat);
            }
        }
        return aggregatedStats;
    }
}

结语:

本文主要介绍了统计数据的具体信息,以及系统关于查询获取系统统计信息的api的部分相关源码。接下来的文章将主要介绍系统是如何记录并统计app使用情况的,并分析相关源码,针对该源码,分析其逻辑。

转载请注明出处。

github:UseTimeStatistic
参考文献:
相关源码链接
developer官网说明
Android5.1应用统计源码分析
Android5.1应用打开次数获取

上一篇:Android应用统计-使用时长及次数统计(一)
下一篇:Android应用统计-使用时长及次数统计(三)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,100评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,362评论 6 343
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,569评论 25 707
  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 10,507评论 6 13
  • 这几天又想老大了,这些年把他放在家里,一直都是爷爷奶奶照顾,孩子过了十一个生日,我们一直都是缺席者。 ...
    笑颜如花瑞阅读 193评论 0 0