Android 应用使用情况统计
本篇文章简单记录下android中usageStatsManager的简单使用.
UsageStatsManager提供对设备使用历史记录和统计信息的访问,时间周期为days, weeks, months, and years.
它可以帮助开发者了解用户在设备上使用应用程序的情况,包括应用程序的启动次数、使用时长等。
1: 权限申请
<uses-permission
android:name=".PACKAGE_USAGE_STATS"
tools:ignore="ProtectedPermissions" />
2: 授予权限
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
startActivity(intent);
3: 获取应用使用时长
获取UsageStatsManager实例;
UsageStatsManager usageStatsManager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
获取当前时间和过去一段时间的时间戳
Calendar calendar = ();
long endTime = ();
(Calendar.DAY_OF_WEEK, -1);
long startTime = ();
查询应用使用时长
List usageStatsList = (UsageStatsManager.INTERVAL_DAILY, startTime, endTime);
遍历应用使用时长列表
for (UsageStats usageStats : usageStatsList) {
// 获取应用包名
String packageName = ();
// 获取应用使用时长(以毫秒为单位)
long totalTimeInForeground = ();
if (totalTimeInForeground>0)
// 输出应用包名和使用时长
(“XXXX”, "pkgName: " + packageName + ", totalTimeInForeground: " + totalTimeInForeground/1000);
}
getTotalTimeInForeground 方法是获取应用在前台的使用时长,单位毫秒.
queryUsageStats 可以指定时间间隔查询:
/**
* An interval type that spans a day. See {@link #queryUsageStats(int, long, long)}.
*/
public static final int INTERVAL_DAILY = 0;
/**
* An interval type that spans a week. See {@link #queryUsageStats(int, long, long)}.
*/
public static final int INTERVAL_WEEKLY = 1;
/**
* An interval type that spans a month. See {@link #queryUsageStats(int, long, long)}.
*/
public static final int INTERVAL_MONTHLY = 2;
/**
* An interval type that spans a year. See {@link #queryUsageStats(int, long, long)}.
*/
public static final int INTERVAL_YEARLY = 3;
/**
* An interval type that will use the best fit interval for the given time range.
* See {@link #queryUsageStats(int, long, long)}.
*/
public static final int INTERVAL_BEST = 4;
4: 测试输出
2024-02-19 16:29:10.489 13045-13045/ D/XXXX: Package Name: , Total Time: 7
2024-02-19 16:29:10.489 13045-13045/ D/XXXX: Package Name: , Total Time: 336
2024-02-19 16:29:10.490 13045-13045/ D/XXXX: Package Name: android, Total Time: 103
2024-02-19 16:29:10.490 13045-13045/ D/XXXX: Package Name: , Total Time: 2585
2024-02-19 16:29:10.490 13045-13045/ D/XXXX: Package Name: , Total Time: 12
2024-02-19 16:29:10.490 13045-13045/ D/XXXX: Package Name: , Total Time: 170
2024-02-19 16:29:10.490 13045-13045/ D/XXXX: Package Name: , Total Time: 49
2024-02-19 16:29:10.490 13045-13045/ D/XXXX: Package Name: , Total Time: 2557
2024-02-19 16:29:10.490 13045-13045/ D/XXXX: Package Name: , Total Time: 9
2024-02-19 16:29:10.490 13045-13045/ D/XXXX: Package Name: , Total Time: 9
2024-02-19 16:29:10.490 13045-13045/ D/XXXX: Package Name: , Total Time: 106
2024-02-19 16:29:10.490 13045-13045/ D/XXXX: Package Name: , Total Time: 2