Android知识Android开发经验谈

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

2017-12-10  本文已影响0人  Wingbu

关键字: 应用统计 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应用统计-使用时长及次数统计(三)

上一篇下一篇

猜你喜欢

热点阅读