@capgo/capacitor-android-usagestatsmanager

中文文档
8.2.14发布于 2026/11/02MPL-2.0TypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 4580

Exposes the Android's UsageStatsManager SDK to Capacitor

原始使用文档
文档目录18 节
  1. ➡️ Get started for free
  2. Key features
  3. Description
  4. Why Android UsageStatsManager?
  5. Usage
  6. Documentation
  7. Compatibility
  8. Install
  9. API
  10. queryAndAggregateUsageStats(...)
  11. queryUsageStats(...)
  12. queryEvents(...)
  13. isUsageStatsPermissionGranted()
  14. openUsageStatsSettings()
  15. queryAllPackages(...)
  16. getPluginVersion()
  17. Interfaces
  18. Type Aliases

@capgo/capacitor-android-usagestatsmanager

Read Android app usage statistics from your Capacitor app with the UsageStatsManager API: screen time per app, usage intervals and raw usage events. Built for digital wellbeing, parental control and analytics apps.

Capgo - Build Capacitor apps with AI, ship updates instantly

Capgo: push fixes to your Capacitor users in minutes, build signed iOS and Android apps without a Mac, and roll back in one click.

➡️ Get started for free

14-day unlimited free trial. No credit card required

🤖 Building with an AI coding agent? Install Capgo skills so Claude Code, Codex, Cursor, Copilot, or Gemini CLI know how to install and use @capgo/capacitor-android-usagestatsmanager in your Capacitor app: npx skills add Cap-go/capgo-skills. Then ask your agent: "Add @capgo/capacitor-android-usagestatsmanager to my Capacitor app and wire it up." Agent setup guides · Hosted MCP

@capgo/capacitor-android-usagestatsmanager for Capacitor apps

Key features

  • Aggregated usage: queryAndAggregateUsageStats() returns per-app usage for a time range.
  • Interval stats: queryUsageStats() returns stats for daily, weekly, monthly or yearly intervals.
  • Raw events: queryEvents() reads the usage event log for a time range.
  • Installed apps: queryAllPackages() lists packages installed on the device.
  • Permission helpers: isUsageStatsPermissionGranted() and openUsageStatsSettings() guide users to grant usage access.
  • Platforms: Android. Android only. Web methods throw.

Description

Exposes the Android's UsageStatsManager SDK to Capacitor

Why Android UsageStatsManager?

The only plugin exposing Android's UsageStatsManager API to Capacitor - this Android API was not supported by any plugin before:

  • App usage tracking - Monitor which apps users open and for how long
  • Screen time analytics - Build parental controls and digital wellbeing features
  • Exact-window events - Query raw lifecycle events when you need foreground time clipped to a specific range
  • Package information - Query all installed apps on the device
  • Time-based queries - Get usage stats for any time range

Perfect for parental control apps, digital wellbeing tools, productivity trackers, and screen time managers.

Usage

Requires the following permissions in your AndroidManifest.xml:

<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS"
    tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"
    tools:ignore="QueryAllPackagesPermission" />

Documentation

The most complete doc is available here: https://capgo.app/docs/plugins/android-usagestatsmanager/

Compatibility

Plugin versionCapacitor compatibilityMaintained
v8.*.*v8.*.*✅
v7.*.*v7.*.*On demand
v6.*.*v6.*.*❌
v5.*.*v5.*.*❌

Note: The major version of this plugin follows the major version of Capacitor. Use the version that matches your Capacitor installation (e.g., plugin v8 for Capacitor 8). Only the latest major version is actively maintained.

Install

You can use our AI-Assisted Setup to install the plugin. Add the Capgo skills to your AI tool using the following command:

npx skills add https://github.com/cap-go/capacitor-skills --skill capacitor-plugins

Then use the following prompt:

Use the `capacitor-plugins` skill from `cap-go/capacitor-skills` to install the `@capgo/capacitor-android-usagestatsmanager` plugin in my project.

If you prefer Manual Setup, install the plugin by running the following commands and follow the platform-specific instructions below:

npm install @capgo/capacitor-android-usagestatsmanager
npx cap sync

API

Capacitor plugin for accessing Android UsageStatsManager API.

queryAndAggregateUsageStats(...)

queryAndAggregateUsageStats(options: UsageStatsOptions) => Promise<Record<string, UsageStats>>

Queries and aggregates usage stats for the given time range.

Android reads pre-aggregated daily/weekly/monthly/yearly buckets and sums every bucket that intersects [beginTime, endTime), without clipping to it. totalTimeInForeground can therefore include usage from outside the window. Use queryUsageStats for the unmerged per-interval buckets, or queryEvents for timestamped lifecycle events in the requested range.

ParamTypeDescription
optionsUsageStatsOptions- The time range options for the query

Returns: Promise<Record<string, UsageStats>>

Since: 1.0.0


queryUsageStats(...)

queryUsageStats(options: QueryUsageStatsOptions) => Promise<QueryUsageStatsResult>

Queries usage stats for the given interval type and time range.

Wraps Android UsageStatsManager.queryUsageStats. Unlike queryAndAggregateUsageStats, this does not merge buckets: the result is one UsageStats object per package per overlapping interval. Android may expand [beginTime, endTime) to the nearest whole interval period, so totalTimeInForeground can include usage from outside the window.

On Android R (API 30) and above, the OS returns no data while the user is locked; this plugin then resolves { stats: [] }, which must not be treated as zero foreground usage.

This uses the same PACKAGE_USAGE_STATS permission as queryAndAggregateUsageStats.

ParamTypeDescription
optionsQueryUsageStatsOptions- The interval type, time range, and optional package filter

Returns: Promise<QueryUsageStatsResult>

Since: 8.1.3


queryEvents(...)

queryEvents(options: QueryEventsOptions) => Promise<QueryEventsResult>

Queries the raw usage event log for the given time range.

Returns lifecycle events whose timestamps fall in [beginTime, endTime). Android does not emit a synthetic event for "already in foreground at beginTime" or "still in foreground at endTime". To measure duration across those boundaries, pass an earlier beginTime as lookback and clip locally: treat an unmatched pause as starting at the window start, and an unmatched resume as ending at the window end.

Android retains events for only a few days. Older ranges may return an incomplete or empty list; that is not the same as zero foreground usage. On Android R (API 30) and above, the OS also returns no events while the user is locked; this plugin then resolves { events: [] }, which likewise must not be treated as zero foreground usage.

Callers can sum resumed-to-paused intervals from the returned events. Do not treat DEVICE_SHUTDOWN as a pause: it is a reset marker, not an interval close. This uses the same PACKAGE_USAGE_STATS permission as queryAndAggregateUsageStats.

Only lifecycle events are returned, to keep the bridge payload small:

  • 1 — ACTIVITY_RESUMED / MOVE_TO_FOREGROUND
  • 2 — ACTIVITY_PAUSED / MOVE_TO_BACKGROUND
  • 23 — ACTIVITY_STOPPED
  • 26 — DEVICE_SHUTDOWN (device-wide reset marker; still returned when packageName is set. Android typically reports package "android". packageName is omitted if the OS does not attach one. The timestamp is the last UsageStats persist before shutdown, not the actual power-off. Open resume events without a matching pause between this marker and the next boot have unknown duration and must be ignored.)
ParamTypeDescription
optionsQueryEventsOptions- The time range and optional package filter

Returns: Promise<QueryEventsResult>

Since: 8.1.3


isUsageStatsPermissionGranted()

isUsageStatsPermissionGranted() => Promise<UsageStatsPermissionResult>

Checks if the usage stats permission is granted.

Returns: Promise<UsageStatsPermissionResult>

Since: 1.0.0


openUsageStatsSettings()

openUsageStatsSettings() => Promise<void>

Open the usage stats settings screen. This will open the usage stats settings screen, which allows the user to grant the usage stats permission. This will always open the settings screen, even if the permission is already granted.

Since: 1.0.0


queryAllPackages(...)

queryAllPackages(options?: QueryAllPackagesOptions | undefined) => Promise<{ packages: PackageInfo[]; }>

Queries all installed packages on the device. Requires the QUERY_ALL_PACKAGES permission.

ParamTypeDescription
optionsQueryAllPackagesOptions- Optional query settings

Returns: Promise<{ packages: PackageInfo[]; }>

Since: 1.2.0


getPluginVersion()

getPluginVersion() => Promise<{ version: string; }>

Get the native Capacitor plugin version.

Returns: Promise<{ version: string; }>

Since: 1.0.0


Interfaces

UsageStats

Usage statistics for an Android app.

PropTypeDescription
firstTimeStampnumberThe first timestamp of the usage stats.
lastTimeStampnumberThe last timestamp of the usage stats.
lastTimeForegroundServiceUsednumberOnly available on Android Q (API level 29) and above. Will be undefined on lower Android versions.
lastTimeUsednumberThe last time the app was used.
lastTimeVisiblenumberOnly available on Android Q (API level 29) and above. Will be undefined on lower Android versions.
packageNamestringThe name of the package.
totalForegroundServiceUsednumberOnly available on Android Q (API level 29) and above. Will be undefined on lower Android versions.
totalTimeInForegroundnumberThe total time the app was in the foreground.
totalTimeVisiblenumberOnly available on Android Q (API level 29) and above. Will be undefined on lower Android versions.

UsageStatsOptions

Options for querying usage statistics.

PropTypeDescriptionSince
beginTimenumberThe inclusive beginning of the range of stats to include in the results. Defined in terms of "Unix time"
endTimenumberThe exclusive end of the range of stats to include in the results. Defined in terms of "Unix time"
packageNamestringOptional package name. When set, only stats for this package are returned. Omit to return stats for every package (previous behavior). An empty string is rejected.8.1.3

QueryUsageStatsResult

Result of a queryUsageStats call.

PropTypeDescription
statsUsageStats[]Usage stats buckets in the requested range, ordered as returned by the OS. The same package can appear more than once when multiple intervals overlap.

QueryUsageStatsOptions

Options for querying per-interval usage statistics.

PropTypeDescription
intervalTypenumberInterval type from android.app.usage.UsageStatsManager: - 0 — INTERVAL_DAILY - 1 — INTERVAL_WEEKLY - 2 — INTERVAL_MONTHLY - 3 — INTERVAL_YEARLY - 4 — INTERVAL_BEST
beginTimenumberThe inclusive beginning of the range of stats to include in the results. Defined in terms of "Unix time"
endTimenumberThe exclusive end of the range of stats to include in the results. Defined in terms of "Unix time"
packageNamestringOptional package name. When set, only stats for this package are returned. An empty string is rejected.

QueryEventsResult

Result of a queryEvents call.

PropTypeDescription
eventsUsageEvent[]Lifecycle usage events in the requested range, ordered as returned by the OS.

UsageEvent

Represents a single usage event.

queryEvents currently populates className, timeStamp, and eventType. packageName is set when Android attaches one (DEVICE_SHUTDOWN usually uses "android") and omitted otherwise. Other fields remain optional for compatibility.

PropTypeDescription
packageNamestringPackage name of the app. Omitted when Android does not attach a package. DEVICE_SHUTDOWN typically uses "android".
classNamestringClass name (might be null)
timeStampnumberTimestamp in milliseconds since epoch
eventTypenumberEvent type constant from android.app.usage.UsageEvents.Event. queryEvents returns lifecycle types only: - 1 — ACTIVITY_RESUMED / MOVE_TO_FOREGROUND - 2 — ACTIVITY_PAUSED / MOVE_TO_BACKGROUND - 23 — ACTIVITY_STOPPED - 26 — DEVICE_SHUTDOWN (reset marker, not an interval close)
configurationanyConfiguration object (requires API 28+)
shortcutIdstringShortcut ID (requires API 28+)
standbyBucketnumberApp standby bucket (requires API 28+)
notificationChannelIdstringNotification channel ID (requires API 29+)
instanceIdnumberInstance ID (requires API 30+)
taskRootPackageNamestringTask root package name (requires API 31+)
taskRootClassNamestringTask root class name (requires API 31+)

QueryEventsOptions

Options for querying the raw usage event log.

PropTypeDescription
beginTimenumberThe inclusive beginning of the range of events to include in the results. Defined in terms of "Unix time"
endTimenumberThe exclusive end of the range of events to include in the results. Defined in terms of "Unix time"
packageNamestringOptional package name. When set, only events for this package are returned, plus device-wide DEVICE_SHUTDOWN events. An empty string is rejected. Keeps the Capacitor bridge payload small when you care about one app.

UsageStatsPermissionResult

Result of a usage stats permission check.

PropTypeDescription
grantedbooleanWhether the usage stats permission is granted.

PackageInfo

Represents basic information about an installed package.

PropTypeDescriptionSince
packageNamestringPackage name
appNamestringApp display name
versionNamestringVersion name string
versionCodenumberVersion code number
firstInstallTimenumberFirst install time in milliseconds since epoch
lastUpdateTimenumberLast update time in milliseconds since epoch
categorynumberApplication category from ApplicationInfo.category. Only available on Android 8.0 (API level 26) and above. Common values: - 0 — undefined - 1 — game - 2 — audio - 3 — video - 4 — image - 5 — social - 6 — news - 7 — maps - 8 — productivity8.0.33
iconstringApp icon as a base64 data URL (data:image/png;base64,...). Only present when queryAllPackages({ includeIcon: true }) is used.8.0.33

QueryAllPackagesOptions

Options for querying installed packages.

PropTypeDescriptionDefault
includeIconbooleanWhen true, includes each app's launcher icon as a base64 data URL. Defaults to false because icons significantly increase the response size.false

Type Aliases

Record

Construct a type with a set of properties K of type T

{ [P in K]: T; }

版本与发布记录

@capgo/capacitor-android-usagestatsmanager 共发布 77 个版本,首次发布于 2025/04/11;过去 12 个月发布了 53 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
8.2.14latest2026/11/026 天前
8.2.132026/10/2613 天前
8.2.122026/10/1920 天前
8.2.112026/10/1525 天前
8.2.102026/10/1327 天前
8.2.92026/10/1228 天前

其他发布通道:lts-v6 → 6.0.0。

关于 @capgo/capacitor-android-usagestatsmanager 的常见问题

@capgo/capacitor-android-usagestatsmanager 是什么?

Exposes the Android's UsageStatsManager SDK to Capacitor

如何安装 @capgo/capacitor-android-usagestatsmanager?

在项目目录运行 npm install @capgo/capacitor-android-usagestatsmanager,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@capacitor/core(>=8.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@capgo/capacitor-android-usagestatsmanager 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@capgo/capacitor-android-usagestatsmanager 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@capgo/capacitor-android-usagestatsmanager 可以商用吗?

@capgo/capacitor-android-usagestatsmanager 使用 MPL-2.0 许可。弱 Copyleft:可以商用,也可以和闭源代码一起使用;但如果分发时修改了 MPL 授权的文件,这些文件的修改需以 MPL 开源。以上为概括,不构成法律意见,请以许可原文为准。

@capgo/capacitor-android-usagestatsmanager 的下载量有多少?

根据 npm 官方下载统计,@capgo/capacitor-android-usagestatsmanager 在 2026/10/09 – 2026/11/07 这 30 天内被下载 4,580 次,日均约 153 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@capgo/capacitor-android-usagestatsmanager 还在维护吗?

最新版本 8.2.14 发布于 2026/11/02(6 天前);至今共发布 77 个版本,其中过去 12 个月发布了 53 个;首次发布于 2025/04/11。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。