[JAVA] How to use UsageStatsManager in Android Studio (How to check the startup time of other apps)

Premise

Windows 10 Android Studio latest version Java

** This method worked fine on my smartphone as of 02/27/2020. ** ** ** There may be specification changes, so if you copy and paste it and it doesn't work, please refer to the official document. ** **

Thing you want to do

I needed to get how many other apps were running that day. For example, the image below is an app called ActionDash, which shows the launch times of other apps.

In conclusion, you can use UsageStatsManager.

UsageStatsManager

Authority relationship

First, write it in ʻAndroidManifest.xml` as below.

AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="****">

    <!--Added the two lines below-->
    <uses-permission android:name="android.permission.PACKAGE_USAGE_STATS"
        tools:ignore="ProtectedPermissions" />

    <application>
         <!--abridgement-->
    </application>

</manifest>

Next, perform a permission check. Use a special method instead of the usual permission method.

private boolean checkReadStatsPermission() {
  //Get AppOpsManager
  AppOpsManager aom = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
  // GET_USAGE_Get STATS status
  int mode = aom.checkOp(AppOpsManager.OPSTR_GET_USAGE_STATS, android.os.Process.myUid(), getPackageName());
  if (mode == AppOpsManager.MODE_DEFAULT) {
    //If the AppOps status is the default, perform a normal permission check.
    //False for ordinary apps
    return checkPermission("android.permission.PACKAGE_USAGE_STATS", android.os.Process.myPid(), android.os.Process.myUid()) == PackageManager.PERMISSION_GRANTED;
  }
  //Only allowed is true if the AppOps state is not the default
  return mode == AppOpsManager.MODE_ALLOWED;
}

Finally, there is a request for permission. Please note that this is also different from the usual method.

if (!checkReadStatsPermission()) {
  startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));
}

Use UsageStatsManager

The explanation is included in the source code. This source code gets the app usage time for the day.


public class UsageStatsClass {
  // Log.d()And the name to identify it as the output of this class
  private static final String TAG = UsageStatsClass.class.getSimpleName();
  //Substitute Context of MainActivity
  private Context context;

  public UsageStatsClass(Context mContext) {
    //Substitute context
    context = mContext;
  }

  //Object called UsageStats is information of one application(App usage time, etc.)Is included
  //That is, one Usage Stats is assigned to each app.
  private List<UsageStats> getUsageStatsObject() {
    // getSystemService()To get UsageStatsManager
    //UsageStatsManager is for getting usage information of the application
    UsageStatsManager usageStatsManager =
            (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);

    //Get the current time as a Calendar object
    Calendar calendar = Calendar.getInstance();
    //Set the calendar time to midnight
    //As a result, the time information contained in the calendar will be from the current time to today's midnight.
    calendar.set(Calendar.HOUR_OF_DAY, 0);

    // queryUsageStats(Unit of time to get,The beginning of the time to get, the end of the time to get)
    //Unit of time to get:Daily(INTERVAL_DAILY), Weekly(INTERVAL_WEEKLY), Monthly(INTERVAL_MONTHLY)、
    //Yearly(INTERVAL_YEARLY), Automatic selection(INTERVAL_BEST)There is
    // 
    //The beginning of time to get:The starting point of the time zone of the data you want to acquire. This time, it's midnight of the day.
    //End of time to get:The end of the time zone for the data you want to retrieve. This time, the current time.
    return usageStatsManager.queryUsageStats(
            UsageStatsManager.INTERVAL_DAILY,
            calendar.getTimeInMillis(),
            System.currentTimeMillis());
  }

  //Function to execute from the outside
  public void readOneDayUsageStats() {
    //Get usage information for each app as a List
    List<UsageStats> usageStats = getUsageStatsObject();

    //Get usage information of one app in usageStat by using for statement
    for (UsageStats usageStat : usageStats) {
      //If you have never used the app, skip it
      if (usageStat.getTotalTimeInForeground() == 0) {
        continue;
      }

      //Output the acquired information with Logcat
      // package name : getPackageName() :The app's unique ID
      // total time displayed : getTotalTimeInForeground() :Total time the app was displayed on the screen
      // first time : getFirstTimeStamp() :Returns the start time of the acquired data in milliseconds
      // getStringDate()Is used to convert milliseconds into a human-friendly form.
      // end time : getLastTimeUsed() :Returns the end time of the retrieved data in milliseconds
      // getStringDate()Is used to convert milliseconds into a human-friendly form.
      Log.d(TAG, "packageName: " + usageStat.getPackageName() + "\ttotalTimeDisplayed: " + usageStat.getTotalTimeInForeground()
          + "\tfirstTime: " + getStringDate(usageStat.getFirstTimeStamp()) + "\tlastTime: " + getStringDate(usageStat.getLastTimeUsed()));
    }
  }

  //Convert long type milliseconds to String type human-friendly form
  private String getStringDate(long milliseconds) {
    final DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.JAPANESE);
    final Date date = new Date(milliseconds);
    return df.format(date);
  }
}

Execution result

The time is displayed for each app. You did it!

D/UsageStatsClass: packageName: com.huawei.android.launcher	totalTimeDisplayed: 3769989	firstTime: 2020/02/27 00:00:02	lastTime: 2020/02/27 15:59:00
D/UsageStatsClass: packageName: jp.naver.line.android	totalTimeDisplayed: 805413	firstTime: 2020/02/27 00:00:02	lastTime: 2020/02/27 15:34:36
D/UsageStatsClass: packageName: com.discord	totalTimeDisplayed: 4247	firstTime: 2020/02/27 00:00:02	lastTime: 2020/02/27 15:43:05
D/UsageStatsClass: packageName: com.microsoft.office.outlook	totalTimeDisplayed: 43011	firstTime: 2020/02/27 00:00:02	lastTime: 2020/02/27 14:19:16
D/UsageStatsClass: packageName: com.google.android.packageinstaller	totalTimeDisplayed: 2444	firstTime: 2020/02/27 00:00:02	lastTime: 2020/02/27 15:59:02
D/UsageStatsClass: packageName: com.google.android.apps.photos	totalTimeDisplayed: 283917	firstTime: 2020/02/27 00:00:02	lastTime: 2020/02/27 13:38:33
D/UsageStatsClass: packageName: com.spotify.music	totalTimeDisplayed: 6267989	firstTime: 2020/02/27 00:00:02	lastTime: 2020/02/27 13:56:21
D/UsageStatsClass: packageName: jp.mineo.app.phone	totalTimeDisplayed: 70175	firstTime: 2020/02/27 00:00:02	lastTime: 2020/02/27 13:59:50
D/UsageStatsClass: packageName: com.google.android.apps.translate	totalTimeDisplayed: 8170	firstTime: 2020/02/27 00:00:02	lastTime: 2020/02/27 15:04:14
D/UsageStatsClass: packageName: ch.bitspin.timely	totalTimeDisplayed: 798142	firstTime: 2020/02/27 00:00:02	lastTime: 2020/02/27 11:17:25
D/UsageStatsClass: packageName: com.android.settings	totalTimeDisplayed: 21715	firstTime: 2020/02/27 00:00:02	lastTime: 2020/02/27 14:32:32

References

Recommended Posts

How to use UsageStatsManager in Android Studio (How to check the startup time of other apps)
How to use ExpandableListView in Android Studio
Android development, how to check null in the value of JSON object
How to check the database of apps deployed on Heroku
How to check the logs in the Docker container
3 ways to import the library in Android Studio
Use the JDK used in Android Studio in the terminal
Output of how to use the slice method
How to use JQuery in js.erb of Rails6
How to check Rails commands in the terminal
How to check the latest version of io.spring.platform to describe in pom.xml of Spring (STS)
How to set the display time to Japan time in Rails
[Android Studio] [Java] How to fix the screen vertically
How to use CommandLineRunner in Spring Batch of Spring Boot
[Android] How to get the setting language of the terminal
How to use git with the power of jgit in an environment without git commands
Summary of how to use the proxy set in IE when connecting with Java
How to correctly check the local HTML file in the browser
How to use the getter / setter method (in object orientation)
How to take a screenshot with the Android Studio emulator
How to set chrony when the time shifts in CentOS7
Refer to C ++ in the Android Studio module (Java / kotlin)
How to create a placeholder part to use in the IN clause
How to get values in real time with TextWatcher (Android)
How to implement one-line display of TextView in Android development
How to derive the last day of the month in Java
How to check the extension and size of uploaded files
How to use the link_to method
How to use Lombok in Spring
How to use the include? method
[Sprint Boot] How to use 3 types of SqlParameterSource defined in org.springframework.jdbc.core.namedparam
How to use the wrapper class
How to use setDefaultCloseOperation () of JFrame
[Swift UI] How to get the startup status of the application [iOS]
How to use InjectorHolder in OpenAM
How to get the id of PRIMAY KEY auto_incremented in MyBatis
How to use classes in Java?
Method definition location Summary of how to check When defined in the project and Rails / Gem
How to check for the contents of a java fixed-length string
How to get the length of an audio file in java
How to increment the value of Map in one line in Java
[Android] Develop a service that allows university students to check the operating status of buses circulating in the university.
How to set the indent to 2 single-byte spaces in the JAXB implementation of the JDK
The story of releasing the Android app to the Play Store for the first time.
What wasn't fair use in the diversion of Java APIs on Android
How to change the maximum and maximum number of POST data in Spark
How to find the total number of pages when paging in Java
How to constrain the action of the transition destination when not logged in
How to change the value of a variable at a breakpoint in intelliJ
I tried to make full use of the CPU core in Ruby
How to get the absolute path of a directory running in Java
Is it possible to put the library (aar) in the Android library (aar) and use it?
How to implement the email authentication function at the time of user registration
[Rails] How to solve the time lag of created_at after save method
Multilingual Locale in Java How to use Locale
[Java] How to use the File class
How to use custom helpers in rails
[Java] How to use the hasNext function
How to use named volume in docker-compose.yml
[Java] How to use the HashMap class
Use ViewModel to rotate Android apps roughly