Add ability to get and set idle state of apps

Add am shell command to set and get idle
Add public API to check if an app is idle

Bug: 20534955
Bug: 20493806
Change-Id: Ib48b3fe847c71f05ef3905563f6e903cf060c498
diff --git a/core/java/android/app/usage/IUsageStatsManager.aidl b/core/java/android/app/usage/IUsageStatsManager.aidl
index 4ed1489..23659e3 100644
--- a/core/java/android/app/usage/IUsageStatsManager.aidl
+++ b/core/java/android/app/usage/IUsageStatsManager.aidl
@@ -30,4 +30,6 @@
     ParceledListSlice queryConfigurationStats(int bucketType, long beginTime, long endTime,
             String callingPackage);
     UsageEvents queryEvents(long beginTime, long endTime, String callingPackage);
+    void setAppIdle(String packageName, boolean idle, int userId);
+    boolean isAppIdle(String packageName, int userId);
 }
diff --git a/core/java/android/app/usage/UsageStatsManager.java b/core/java/android/app/usage/UsageStatsManager.java
index bc6099a..8a01d66 100644
--- a/core/java/android/app/usage/UsageStatsManager.java
+++ b/core/java/android/app/usage/UsageStatsManager.java
@@ -19,6 +19,7 @@
 import android.content.Context;
 import android.content.pm.ParceledListSlice;
 import android.os.RemoteException;
+import android.os.UserHandle;
 import android.util.ArrayMap;
 
 import java.util.Collections;
@@ -217,4 +218,20 @@
         }
         return aggregatedStats;
     }
+
+    /**
+     * Returns whether the specified app is currently considered idle. This will be true if the
+     * app hasn't been used directly or indirectly for a period of time defined by the system. This
+     * could be of the order of several hours or days.
+     * @param packageName The package name of the app to query
+     * @return whether the app is currently considered idle
+     */
+    public boolean isAppIdle(String packageName) {
+        try {
+            return mService.isAppIdle(packageName, UserHandle.myUserId());
+        } catch (RemoteException e) {
+            // fall through and return default
+        }
+        return false;
+    }
 }
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 62685a1..559e452 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -2097,6 +2097,11 @@
         android:protectionLevel="signature|development|appop" />
     <uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" />
 
+    <!-- @hide Allows an application to change the app idle state of an app.
+         <p>Not for use by third-party applications. -->
+    <permission android:name="android.permission.CHANGE_APP_IDLE_STATE"
+        android:protectionLevel="signature" />
+
     <!-- @SystemApi Allows an application to collect battery statistics -->
     <permission android:name="android.permission.BATTERY_STATS"
         android:protectionLevel="signature|system|development" />