BatteryStats: Remove isolated UIDs from /proc/uid_cputime when they are not in use anymore

Bug:22225933
Change-Id: I384a3c37ad45af981cca5fc3e92643da948d48d0
diff --git a/core/java/com/android/internal/os/BatteryStatsImpl.java b/core/java/com/android/internal/os/BatteryStatsImpl.java
index 8b4b994..f421189 100644
--- a/core/java/com/android/internal/os/BatteryStatsImpl.java
+++ b/core/java/com/android/internal/os/BatteryStatsImpl.java
@@ -183,6 +183,7 @@
     public interface ExternalStatsSync {
         void scheduleSync(String reason);
         void scheduleWifiSync(String reason);
+        void scheduleCpuSyncDueToRemovedUid(int uid);
     }
 
     public final MyHandler mHandler;
@@ -2522,13 +2523,28 @@
         mIsolatedUids.put(isolatedUid, appUid);
     }
 
-    public void removeIsolatedUidLocked(int isolatedUid, int appUid) {
+    /**
+     * Schedules a read of the latest cpu times before removing the isolated UID.
+     * @see #removeIsolatedUidLocked(int)
+     */
+    public void scheduleRemoveIsolatedUidLocked(int isolatedUid, int appUid) {
         int curUid = mIsolatedUids.get(isolatedUid, -1);
         if (curUid == appUid) {
-            mIsolatedUids.delete(isolatedUid);
+            if (mExternalSync != null) {
+                mExternalSync.scheduleCpuSyncDueToRemovedUid(isolatedUid);
+            }
         }
     }
 
+    /**
+     * This should only be called after the cpu times have been read.
+     * @see #scheduleRemoveIsolatedUidLocked(int, int)
+     */
+    public void removeIsolatedUidLocked(int isolatedUid) {
+        mIsolatedUids.delete(isolatedUid);
+        mKernelUidCpuTimeReader.removeUid(isolatedUid);
+    }
+
     public int mapUid(int uid) {
         int isolated = mIsolatedUids.get(uid, -1);
         return isolated > 0 ? isolated : uid;