Android App Usage Statistics Sample

repository·master·Indexed 18 days ago

https://github.com/googlesamples/android-appusagestatistics

A sample Android application demonstrating how to use the App usage statistics API and UsageStatsManager to collect and display application usage data. Includes guidance on declaring the android.permission.PACKAGE_USAGE_STATS permission and using the queryUsageStats() method.

Tokens
546
Snippets
2
Records
3
Agent score
14%

What's inside android-appusagestatistics

  1. Configure permissions for App usage statistics

    master

    To use the App usage statistics API, you must declare the android.permission.PACKAGE_USAGE_STATS permission in your AndroidManifest.xml.

    Additionally, this is a sensitive permission that requires explicit user consent. The user must manually enable access for your application by navigating to: Settings > Security > Apps with usage access.

  2. Retrieve app usage statistics using UsageStatsManager

    master

    To collect application usage statistics, follow these steps:

    1. Get the UsageStatsManager instance: Access the system service using Context.USAGE_STATS_SERVICE.
    2. Query the statistics: Use the queryUsageStats() method. This method requires three parameters:
      • interval: The time interval by which the statistics are aggregated (e.g., UsageStatsManager.INTERVAL_DAILY).
      • beginTime: The start of the time range (in milliseconds).
      • endTime: The end of the time range (in milliseconds).

    This method returns a List<UsageStats> containing the usage data for the specified period.

    // 1. Get the UsageStatsManager instance
    mUsageStatsManager = (UsageStatsManager) getActivity()
           .getSystemService(Context.USAGE_STATS_SERVICE);
    
    // 2. Query the statistics (e.g., for the last year)
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.YEAR, -1);
    List<UsageStats> queryUsageStats = mUsageStatsManager
            .queryUsageStats(UsageStatsManager.INTERVAL_DAILY, cal.getTimeInMillis(),
                    System.currentTimeMillis());