blob: af9d4c8c69b6e5406b3e14229de194f323e9c34d [file] [log] [blame]
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Amith Yamasaniaf575b92015-05-29 15:35:26 -070019import android.Manifest;
Sudheer Shankadc589ac2016-11-10 15:30:17 -080020import android.app.ActivityManager;
Dianne Hackborn85e35642017-01-12 15:10:57 -080021import android.app.ActivityManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070022import android.app.AlarmManager;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070023import android.content.BroadcastReceiver;
Adam Lesinski31c05d12015-06-09 17:34:04 -070024import android.content.ContentResolver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070025import android.content.Context;
26import android.content.Intent;
27import android.content.IntentFilter;
28import android.content.pm.ApplicationInfo;
29import android.content.pm.PackageManager;
Amith Yamasaniaf575b92015-05-29 15:35:26 -070030import android.content.pm.PackageManager.NameNotFoundException;
Adam Lesinski31c05d12015-06-09 17:34:04 -070031import android.database.ContentObserver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070032import android.hardware.Sensor;
Nick Vaccaro20feaea2015-09-17 17:22:44 -070033import android.hardware.SensorEvent;
34import android.hardware.SensorEventListener;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -070035import android.hardware.SensorManager;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070036import android.hardware.TriggerEvent;
37import android.hardware.TriggerEventListener;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -070038import android.location.Location;
39import android.location.LocationListener;
40import android.location.LocationManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -070041import android.location.LocationRequest;
Dianne Hackborn88c41352016-04-07 15:18:58 -070042import android.net.ConnectivityManager;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070043import android.net.INetworkPolicyManager;
Dianne Hackborn88c41352016-04-07 15:18:58 -070044import android.net.NetworkInfo;
Adam Lesinski31c05d12015-06-09 17:34:04 -070045import android.net.Uri;
Dianne Hackbornfd854ee2015-07-13 18:00:37 -070046import android.os.BatteryStats;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070047import android.os.Binder;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -070048import android.os.Bundle;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070049import android.os.Environment;
50import android.os.FileUtils;
51import android.os.Handler;
52import android.os.IDeviceIdleController;
Yao Chenca5edbb2016-01-13 14:44:36 -080053import android.os.IMaintenanceActivityListener;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070054import android.os.Looper;
55import android.os.Message;
56import android.os.PowerManager;
Kweku Adamsb396ccf2018-09-17 16:37:15 -070057import android.os.PowerManager.ServiceType;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070058import android.os.PowerManagerInternal;
Dianne Hackbornb6683c42015-06-18 17:40:33 -070059import android.os.Process;
Yao Chenca5edbb2016-01-13 14:44:36 -080060import android.os.RemoteCallbackList;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070061import android.os.RemoteException;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -070062import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070063import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070064import android.os.ShellCallback;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -070065import android.os.ShellCommand;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070066import android.os.SystemClock;
67import android.os.UserHandle;
Adam Lesinski31c05d12015-06-09 17:34:04 -070068import android.provider.Settings;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070069import android.util.ArrayMap;
70import android.util.ArraySet;
Adam Lesinski31c05d12015-06-09 17:34:04 -070071import android.util.KeyValueListParser;
Dianne Hackbornfd854ee2015-07-13 18:00:37 -070072import android.util.MutableLong;
73import android.util.Pair;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070074import android.util.Slog;
Dianne Hackbornfd854ee2015-07-13 18:00:37 -070075import android.util.SparseArray;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070076import android.util.SparseBooleanArray;
77import android.util.TimeUtils;
78import android.util.Xml;
Amith Yamasani520d8f22015-05-08 16:36:21 -070079
Sudheer Shanka326b3112017-11-27 14:40:57 -080080import com.android.internal.annotations.GuardedBy;
Kweku Adams00e3a372018-09-28 16:57:09 -070081import com.android.internal.annotations.VisibleForTesting;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070082import com.android.internal.app.IBatteryStats;
83import com.android.internal.os.AtomicFile;
84import com.android.internal.os.BackgroundThread;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060085import com.android.internal.util.DumpUtils;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070086import com.android.internal.util.FastXmlSerializer;
87import com.android.internal.util.XmlUtils;
88import com.android.server.am.BatteryStatsService;
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -070089import com.android.server.net.NetworkPolicyManagerInternal;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -070090import com.android.server.wm.ActivityTaskManagerInternal;
Amith Yamasani520d8f22015-05-08 16:36:21 -070091
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070092import org.xmlpull.v1.XmlPullParser;
93import org.xmlpull.v1.XmlPullParserException;
94import org.xmlpull.v1.XmlSerializer;
95
96import java.io.ByteArrayOutputStream;
97import java.io.File;
98import java.io.FileDescriptor;
99import java.io.FileInputStream;
100import java.io.FileNotFoundException;
101import java.io.FileOutputStream;
102import java.io.IOException;
103import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100104import java.nio.charset.StandardCharsets;
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700105import java.util.Arrays;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700106
107/**
108 * Keeps track of device idleness and drives low power mode based on that.
Kweku Adams00e3a372018-09-28 16:57:09 -0700109 *
110 * Test: atest com.android.server.DeviceIdleControllerTest
Kweku Adamsf596cfc2018-10-04 15:15:22 -0700111 *
112 * Current idling state machine (as of Android 9 Pie). This can be visualized using Graphviz:
113
114 digraph {
115 subgraph deep {
116 label="deep";
117
118 STATE_ACTIVE [label="STATE_ACTIVE\nScreen on OR Charging OR Alarm going off soon"]
119 STATE_INACTIVE [label="STATE_INACTIVE\nScreen off AND Not charging"]
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700120 STATE_QUICK_DOZE_DELAY [
121 label="STATE_QUICK_DOZE_DELAY\n"
122 + "Screen off AND Not charging\n"
123 + "Location, motion detection, and significant motion monitoring turned off"
124 ]
Kweku Adamsf596cfc2018-10-04 15:15:22 -0700125 STATE_IDLE_PENDING [
126 label="STATE_IDLE_PENDING\nSignificant motion monitoring turned on"
127 ]
128 STATE_SENSING [label="STATE_SENSING\nMonitoring for ANY motion"]
129 STATE_LOCATING [
130 label="STATE_LOCATING\nRequesting location, motion monitoring still on"
131 ]
132 STATE_IDLE [
133 label="STATE_IDLE\nLocation and motion detection turned off\n"
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700134 + "Significant motion monitoring state unchanged"
Kweku Adamsf596cfc2018-10-04 15:15:22 -0700135 ]
136 STATE_IDLE_MAINTENANCE [label="STATE_IDLE_MAINTENANCE\n"]
137
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700138 STATE_ACTIVE -> STATE_INACTIVE [
139 label="becomeInactiveIfAppropriateLocked() AND Quick Doze not enabled"
140 ]
141 STATE_ACTIVE -> STATE_QUICK_DOZE_DELAY [
142 label="becomeInactiveIfAppropriateLocked() AND Quick Doze enabled"
143 ]
Kweku Adamsf596cfc2018-10-04 15:15:22 -0700144
145 STATE_INACTIVE -> STATE_ACTIVE [
146 label="handleMotionDetectedLocked(), becomeActiveLocked()"
147 ]
148 STATE_INACTIVE -> STATE_IDLE_PENDING [label="stepIdleStateLocked()"]
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700149 STATE_INACTIVE -> STATE_QUICK_DOZE_DELAY [
150 label="becomeInactiveIfAppropriateLocked() AND Quick Doze enabled"
151 ]
Kweku Adamsf596cfc2018-10-04 15:15:22 -0700152
153 STATE_IDLE_PENDING -> STATE_ACTIVE [
154 label="handleMotionDetectedLocked(), becomeActiveLocked()"
155 ]
156 STATE_IDLE_PENDING -> STATE_SENSING [label="stepIdleStateLocked()"]
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700157 STATE_IDLE_PENDING -> STATE_QUICK_DOZE_DELAY [
158 label="becomeInactiveIfAppropriateLocked() AND Quick Doze enabled"
159 ]
Kweku Adamsf596cfc2018-10-04 15:15:22 -0700160
161 STATE_SENSING -> STATE_ACTIVE [
162 label="handleMotionDetectedLocked(), becomeActiveLocked()"
163 ]
164 STATE_SENSING -> STATE_LOCATING [label="stepIdleStateLocked()"]
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700165 STATE_SENSING -> STATE_QUICK_DOZE_DELAY [
166 label="becomeInactiveIfAppropriateLocked() AND Quick Doze enabled"
167 ]
Kweku Adamsf596cfc2018-10-04 15:15:22 -0700168 STATE_SENSING -> STATE_IDLE [
169 label="stepIdleStateLocked()\n"
170 + "No Location Manager OR (no Network provider AND no GPS provider)"
171 ]
172
173 STATE_LOCATING -> STATE_ACTIVE [
174 label="handleMotionDetectedLocked(), becomeActiveLocked()"
175 ]
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700176 STATE_LOCATING -> STATE_QUICK_DOZE_DELAY [
177 label="becomeInactiveIfAppropriateLocked() AND Quick Doze enabled"
178 ]
Kweku Adamsf596cfc2018-10-04 15:15:22 -0700179 STATE_LOCATING -> STATE_IDLE [label="stepIdleStateLocked()"]
180
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700181 STATE_QUICK_DOZE_DELAY -> STATE_ACTIVE [
182 label="handleMotionDetectedLocked(), becomeActiveLocked()"
183 ]
184 STATE_QUICK_DOZE_DELAY -> STATE_IDLE [label="stepIdleStateLocked()"]
185
Kweku Adamsf596cfc2018-10-04 15:15:22 -0700186 STATE_IDLE -> STATE_ACTIVE [label="handleMotionDetectedLocked(), becomeActiveLocked()"]
187 STATE_IDLE -> STATE_IDLE_MAINTENANCE [label="stepIdleStateLocked()"]
188
189 STATE_IDLE_MAINTENANCE -> STATE_ACTIVE [
190 label="handleMotionDetectedLocked(), becomeActiveLocked()"
191 ]
192 STATE_IDLE_MAINTENANCE -> STATE_IDLE [
193 label="stepIdleStateLocked(), exitMaintenanceEarlyIfNeededLocked()"
194 ]
195 }
196
197 subgraph light {
198 label="light"
199
200 LIGHT_STATE_ACTIVE [
201 label="LIGHT_STATE_ACTIVE\nScreen on OR Charging OR Alarm going off soon"
202 ]
203 LIGHT_STATE_INACTIVE [label="LIGHT_STATE_INACTIVE\nScreen off AND Not charging"]
204 LIGHT_STATE_PRE_IDLE [
205 label="LIGHT_STATE_PRE_IDLE\n"
206 + "Delay going into LIGHT_STATE_IDLE due to some running jobs or alarms"
207 ]
208 LIGHT_STATE_IDLE [label="LIGHT_STATE_IDLE\n"]
209 LIGHT_STATE_WAITING_FOR_NETWORK [
210 label="LIGHT_STATE_WAITING_FOR_NETWORK\n"
211 + "Coming out of LIGHT_STATE_IDLE, waiting for network"
212 ]
213 LIGHT_STATE_IDLE_MAINTENANCE [label="LIGHT_STATE_IDLE_MAINTENANCE\n"]
214 LIGHT_STATE_OVERRIDE [
215 label="LIGHT_STATE_OVERRIDE\nDevice in deep doze, light no longer changing states"
216 ]
217
218 LIGHT_STATE_ACTIVE -> LIGHT_STATE_INACTIVE [
219 label="becomeInactiveIfAppropriateLocked()"
220 ]
221 LIGHT_STATE_ACTIVE -> LIGHT_STATE_OVERRIDE [label="deep goes to STATE_IDLE"]
222
223 LIGHT_STATE_INACTIVE -> LIGHT_STATE_ACTIVE [label="becomeActiveLocked()"]
224 LIGHT_STATE_INACTIVE -> LIGHT_STATE_PRE_IDLE [label="active jobs"]
225 LIGHT_STATE_INACTIVE -> LIGHT_STATE_IDLE [label="no active jobs"]
226 LIGHT_STATE_INACTIVE -> LIGHT_STATE_OVERRIDE [label="deep goes to STATE_IDLE"]
227
228 LIGHT_STATE_PRE_IDLE -> LIGHT_STATE_ACTIVE [label="becomeActiveLocked()"]
229 LIGHT_STATE_PRE_IDLE -> LIGHT_STATE_IDLE [
230 label="stepLightIdleStateLocked(), exitMaintenanceEarlyIfNeededLocked()"
231 ]
232 LIGHT_STATE_PRE_IDLE -> LIGHT_STATE_OVERRIDE [label="deep goes to STATE_IDLE"]
233
234 LIGHT_STATE_IDLE -> LIGHT_STATE_ACTIVE [label="becomeActiveLocked()"]
235 LIGHT_STATE_IDLE -> LIGHT_STATE_WAITING_FOR_NETWORK [label="no network"]
236 LIGHT_STATE_IDLE -> LIGHT_STATE_IDLE_MAINTENANCE
237 LIGHT_STATE_IDLE -> LIGHT_STATE_OVERRIDE [label="deep goes to STATE_IDLE"]
238
239 LIGHT_STATE_WAITING_FOR_NETWORK -> LIGHT_STATE_ACTIVE [label="becomeActiveLocked()"]
240 LIGHT_STATE_WAITING_FOR_NETWORK -> LIGHT_STATE_IDLE_MAINTENANCE
241 LIGHT_STATE_WAITING_FOR_NETWORK -> LIGHT_STATE_OVERRIDE [
242 label="deep goes to STATE_IDLE"
243 ]
244
245 LIGHT_STATE_IDLE_MAINTENANCE -> LIGHT_STATE_ACTIVE [label="becomeActiveLocked()"]
246 LIGHT_STATE_IDLE_MAINTENANCE -> LIGHT_STATE_IDLE [
247 label="stepLightIdleStateLocked(), exitMaintenanceEarlyIfNeededLocked()"
248 ]
249 LIGHT_STATE_IDLE_MAINTENANCE -> LIGHT_STATE_OVERRIDE [label="deep goes to STATE_IDLE"]
250
251 LIGHT_STATE_OVERRIDE -> LIGHT_STATE_ACTIVE [
252 label="handleMotionDetectedLocked(), becomeActiveLocked()"
253 ]
254 }
255 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700256 */
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700257public class DeviceIdleController extends SystemService
258 implements AnyMotionDetector.DeviceIdleCallback {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700259 private static final String TAG = "DeviceIdleController";
260
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700261 private static final boolean DEBUG = false;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700262
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700263 private static final boolean COMPRESS_TIME = false;
Amith Yamasani520d8f22015-05-08 16:36:21 -0700264
Dianne Hackborn953fc942016-03-29 15:36:24 -0700265 private static final int EVENT_BUFFER_SIZE = 100;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800266
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700267 private AlarmManager mAlarmManager;
268 private IBatteryStats mBatteryStats;
Dianne Hackborn85e35642017-01-12 15:10:57 -0800269 private ActivityManagerInternal mLocalActivityManager;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700270 private ActivityTaskManagerInternal mLocalActivityTaskManager;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700271 private PowerManagerInternal mLocalPowerManager;
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700272 private PowerManager mPowerManager;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700273 private INetworkPolicyManager mNetworkPolicyManager;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700274 private SensorManager mSensorManager;
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700275 private Sensor mMotionSensor;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700276 private LocationRequest mLocationRequest;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700277 private Intent mIdleIntent;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700278 private Intent mLightIdleIntent;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700279 private AnyMotionDetector mAnyMotionDetector;
Makoto Onukie4918212018-02-06 11:30:15 -0800280 private final AppStateTracker mAppStateTracker;
Dianne Hackbornb6843652016-02-22 12:20:13 -0800281 private boolean mLightEnabled;
282 private boolean mDeepEnabled;
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700283 private boolean mQuickDozeActivated;
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700284 private boolean mForceIdle;
Dianne Hackborn88c41352016-04-07 15:18:58 -0700285 private boolean mNetworkConnected;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700286 private boolean mScreenOn;
287 private boolean mCharging;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700288 private boolean mNotMoving;
289 private boolean mLocating;
290 private boolean mLocated;
Joe LaPenna23d681b2015-08-27 15:12:11 -0700291 private boolean mHasGps;
292 private boolean mHasNetworkLocation;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700293 private Location mLastGenericLocation;
294 private Location mLastGpsLocation;
Amith Yamasani396a10c2018-01-19 10:58:07 -0800295 // Current locked state of the screen
296 private boolean mScreenLocked;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700297
298 /** Device is currently active. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700299 @VisibleForTesting
300 static final int STATE_ACTIVE = 0;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700301 /** Device is inactive (screen off, no motion) and we are waiting to for idle. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700302 @VisibleForTesting
303 static final int STATE_INACTIVE = 1;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700304 /** Device is past the initial inactive period, and waiting for the next idle period. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700305 @VisibleForTesting
306 static final int STATE_IDLE_PENDING = 2;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700307 /** Device is currently sensing motion. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700308 @VisibleForTesting
309 static final int STATE_SENSING = 3;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700310 /** Device is currently finding location (and may still be sensing). */
Kweku Adams00e3a372018-09-28 16:57:09 -0700311 @VisibleForTesting
312 static final int STATE_LOCATING = 4;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700313 /** Device is in the idle state, trying to stay asleep as much as possible. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700314 @VisibleForTesting
315 static final int STATE_IDLE = 5;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700316 /** Device is in the idle state, but temporarily out of idle to do regular maintenance. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700317 @VisibleForTesting
318 static final int STATE_IDLE_MAINTENANCE = 6;
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700319 /**
320 * Device is inactive and should go straight into idle (foregoing motion and location
321 * monitoring), but allow some time for current work to complete first.
322 */
323 @VisibleForTesting
324 static final int STATE_QUICK_DOZE_DELAY = 7;
Amith Yamasani396a10c2018-01-19 10:58:07 -0800325
Kweku Adams00e3a372018-09-28 16:57:09 -0700326 @VisibleForTesting
327 static String stateToString(int state) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700328 switch (state) {
329 case STATE_ACTIVE: return "ACTIVE";
330 case STATE_INACTIVE: return "INACTIVE";
331 case STATE_IDLE_PENDING: return "IDLE_PENDING";
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700332 case STATE_SENSING: return "SENSING";
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700333 case STATE_LOCATING: return "LOCATING";
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700334 case STATE_IDLE: return "IDLE";
335 case STATE_IDLE_MAINTENANCE: return "IDLE_MAINTENANCE";
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700336 case STATE_QUICK_DOZE_DELAY: return "QUICK_DOZE_DELAY";
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700337 default: return Integer.toString(state);
338 }
339 }
340
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700341 /** Device is currently active. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700342 @VisibleForTesting
343 static final int LIGHT_STATE_ACTIVE = 0;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700344 /** Device is inactive (screen off) and we are waiting to for the first light idle. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700345 @VisibleForTesting
346 static final int LIGHT_STATE_INACTIVE = 1;
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700347 /** Device is about to go idle for the first time, wait for current work to complete. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700348 @VisibleForTesting
349 static final int LIGHT_STATE_PRE_IDLE = 3;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700350 /** Device is in the light idle state, trying to stay asleep as much as possible. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700351 @VisibleForTesting
352 static final int LIGHT_STATE_IDLE = 4;
Dianne Hackborn88c41352016-04-07 15:18:58 -0700353 /** Device is in the light idle state, we want to go in to idle maintenance but are
354 * waiting for network connectivity before doing so. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700355 @VisibleForTesting
356 static final int LIGHT_STATE_WAITING_FOR_NETWORK = 5;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700357 /** Device is in the light idle state, but temporarily out of idle to do regular maintenance. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700358 @VisibleForTesting
359 static final int LIGHT_STATE_IDLE_MAINTENANCE = 6;
Dianne Hackbornb6843652016-02-22 12:20:13 -0800360 /** Device light idle state is overriden, now applying deep doze state. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700361 @VisibleForTesting
362 static final int LIGHT_STATE_OVERRIDE = 7;
363
364 @VisibleForTesting
365 static String lightStateToString(int state) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700366 switch (state) {
367 case LIGHT_STATE_ACTIVE: return "ACTIVE";
368 case LIGHT_STATE_INACTIVE: return "INACTIVE";
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700369 case LIGHT_STATE_PRE_IDLE: return "PRE_IDLE";
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700370 case LIGHT_STATE_IDLE: return "IDLE";
Dianne Hackborn88c41352016-04-07 15:18:58 -0700371 case LIGHT_STATE_WAITING_FOR_NETWORK: return "WAITING_FOR_NETWORK";
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700372 case LIGHT_STATE_IDLE_MAINTENANCE: return "IDLE_MAINTENANCE";
373 case LIGHT_STATE_OVERRIDE: return "OVERRIDE";
374 default: return Integer.toString(state);
375 }
376 }
377
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700378 private int mState;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700379 private int mLightState;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700380
381 private long mInactiveTimeout;
382 private long mNextAlarmTime;
383 private long mNextIdlePendingDelay;
384 private long mNextIdleDelay;
Dianne Hackborn953fc942016-03-29 15:36:24 -0700385 private long mNextLightIdleDelay;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700386 private long mNextLightAlarmTime;
Kevin Gabayan92f15e62016-04-04 17:52:22 -0700387 private long mNextSensingTimeoutAlarmTime;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800388 private long mCurIdleBudget;
389 private long mMaintenanceStartTime;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700390
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800391 private int mActiveIdleOpCount;
Joe Onorato8f0e9ced2016-12-08 17:48:49 -0800392 private PowerManager.WakeLock mActiveIdleWakeLock; // held when there are operations in progress
393 private PowerManager.WakeLock mGoingIdleWakeLock; // held when we are going idle so hardware
394 // (especially NetworkPolicyManager) can shut
395 // down.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800396 private boolean mJobsActive;
397 private boolean mAlarmsActive;
Yao Chenca5edbb2016-01-13 14:44:36 -0800398 private boolean mReportedMaintenanceActivity;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800399
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700400 public final AtomicFile mConfigFile;
401
Yao Chenca5edbb2016-01-13 14:44:36 -0800402 private final RemoteCallbackList<IMaintenanceActivityListener> mMaintenanceActivityListeners =
403 new RemoteCallbackList<IMaintenanceActivityListener>();
404
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700405 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700406 * Package names the system has white-listed to opt out of power save restrictions,
407 * except for device idle mode.
408 */
409 private final ArrayMap<String, Integer> mPowerSaveWhitelistAppsExceptIdle = new ArrayMap<>();
410
411 /**
Sudheer Shanka3f4d7702017-04-28 17:38:03 -0700412 * Package names the user has white-listed using commandline option to opt out of
413 * power save restrictions, except for device idle mode.
414 */
415 private final ArraySet<String> mPowerSaveWhitelistUserAppsExceptIdle = new ArraySet<>();
416
417 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700418 * Package names the system has white-listed to opt out of power save restrictions for
419 * all modes.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700420 */
421 private final ArrayMap<String, Integer> mPowerSaveWhitelistApps = new ArrayMap<>();
422
423 /**
424 * Package names the user has white-listed to opt out of power save restrictions.
425 */
426 private final ArrayMap<String, Integer> mPowerSaveWhitelistUserApps = new ArrayMap<>();
427
428 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700429 * App IDs of built-in system apps that have been white-listed except for idle modes.
430 */
431 private final SparseBooleanArray mPowerSaveWhitelistSystemAppIdsExceptIdle
432 = new SparseBooleanArray();
433
434 /**
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700435 * App IDs of built-in system apps that have been white-listed.
436 */
437 private final SparseBooleanArray mPowerSaveWhitelistSystemAppIds = new SparseBooleanArray();
438
439 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700440 * App IDs that have been white-listed to opt out of power save restrictions, except
441 * for device idle modes.
442 */
443 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
444
445 /**
446 * Current app IDs that are in the complete power save white list, but shouldn't be
447 * excluded from idle modes. This array can be shared with others because it will not be
448 * modified once set.
449 */
450 private int[] mPowerSaveWhitelistExceptIdleAppIdArray = new int[0];
451
452 /**
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700453 * App IDs that have been white-listed to opt out of power save restrictions.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700454 */
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700455 private final SparseBooleanArray mPowerSaveWhitelistAllAppIds = new SparseBooleanArray();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700456
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700457 /**
458 * Current app IDs that are in the complete power save white list. This array can
459 * be shared with others because it will not be modified once set.
460 */
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700461 private int[] mPowerSaveWhitelistAllAppIdArray = new int[0];
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700462
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700463 /**
Dianne Hackborn262ae5c2016-02-10 16:28:29 -0800464 * App IDs that have been white-listed by the user to opt out of power save restrictions.
465 */
466 private final SparseBooleanArray mPowerSaveWhitelistUserAppIds = new SparseBooleanArray();
467
468 /**
469 * Current app IDs that are in the user power save white list. This array can
470 * be shared with others because it will not be modified once set.
471 */
472 private int[] mPowerSaveWhitelistUserAppIdArray = new int[0];
473
474 /**
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700475 * List of end times for UIDs that are temporarily marked as being allowed to access
476 * the network and acquire wakelocks. Times are in milliseconds.
477 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700478 private final SparseArray<Pair<MutableLong, String>> mTempWhitelistAppIdEndTimes
479 = new SparseArray<>();
480
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -0700481 private NetworkPolicyManagerInternal mNetworkPolicyManagerInternal;
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700482
483 /**
484 * Current app IDs of temporarily whitelist apps for high-priority messages.
485 */
486 private int[] mTempWhitelistAppIdArray = new int[0];
487
Suprabh Shukla08105642017-09-26 14:45:30 -0700488 /**
489 * Apps in the system whitelist that have been taken out (probably because the user wanted to).
490 * They can be restored back by calling restoreAppToSystemWhitelist(String).
491 */
492 private ArrayMap<String, Integer> mRemovedFromSystemWhitelistApps = new ArrayMap<>();
493
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800494 private static final int EVENT_NULL = 0;
495 private static final int EVENT_NORMAL = 1;
496 private static final int EVENT_LIGHT_IDLE = 2;
497 private static final int EVENT_LIGHT_MAINTENANCE = 3;
Dianne Hackbornb6843652016-02-22 12:20:13 -0800498 private static final int EVENT_DEEP_IDLE = 4;
499 private static final int EVENT_DEEP_MAINTENANCE = 5;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800500
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -0700501 private final int[] mEventCmds = new int[EVENT_BUFFER_SIZE];
502 private final long[] mEventTimes = new long[EVENT_BUFFER_SIZE];
Amith Yamasaniac6517a2018-04-23 12:19:34 -0700503 private final String[] mEventReasons = new String[EVENT_BUFFER_SIZE];
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800504
Amith Yamasaniac6517a2018-04-23 12:19:34 -0700505 private void addEvent(int cmd, String reason) {
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800506 if (mEventCmds[0] != cmd) {
507 System.arraycopy(mEventCmds, 0, mEventCmds, 1, EVENT_BUFFER_SIZE - 1);
508 System.arraycopy(mEventTimes, 0, mEventTimes, 1, EVENT_BUFFER_SIZE - 1);
Amith Yamasaniac6517a2018-04-23 12:19:34 -0700509 System.arraycopy(mEventReasons, 0, mEventReasons, 1, EVENT_BUFFER_SIZE - 1);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800510 mEventCmds[0] = cmd;
511 mEventTimes[0] = SystemClock.elapsedRealtime();
Amith Yamasaniac6517a2018-04-23 12:19:34 -0700512 mEventReasons[0] = reason;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800513 }
514 }
515
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700516 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
517 @Override public void onReceive(Context context, Intent intent) {
Dianne Hackborn88c41352016-04-07 15:18:58 -0700518 switch (intent.getAction()) {
519 case ConnectivityManager.CONNECTIVITY_ACTION: {
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -0700520 updateConnectivityState(intent);
Dianne Hackborn88c41352016-04-07 15:18:58 -0700521 } break;
522 case Intent.ACTION_BATTERY_CHANGED: {
523 synchronized (DeviceIdleController.this) {
524 int plugged = intent.getIntExtra("plugged", 0);
525 updateChargingLocked(plugged != 0);
526 }
527 } break;
528 case Intent.ACTION_PACKAGE_REMOVED: {
529 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
530 Uri data = intent.getData();
531 String ssp;
532 if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
533 removePowerSaveWhitelistAppInternal(ssp);
534 }
535 }
536 } break;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700537 }
538 }
539 };
540
541 private final AlarmManager.OnAlarmListener mLightAlarmListener
542 = new AlarmManager.OnAlarmListener() {
543 @Override
544 public void onAlarm() {
545 synchronized (DeviceIdleController.this) {
546 stepLightIdleStateLocked("s:alarm");
547 }
548 }
549 };
550
Kevin Gabayan92f15e62016-04-04 17:52:22 -0700551 private final AlarmManager.OnAlarmListener mSensingTimeoutAlarmListener
552 = new AlarmManager.OnAlarmListener() {
553 @Override
554 public void onAlarm() {
555 if (mState == STATE_SENSING) {
556 synchronized (DeviceIdleController.this) {
Kweku Adams00e3a372018-09-28 16:57:09 -0700557 // Restart the device idle progression in case the device moved but the screen
558 // didn't turn on.
Kevin Gabayan92f15e62016-04-04 17:52:22 -0700559 becomeInactiveIfAppropriateLocked();
560 }
561 }
562 }
563 };
564
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700565 private final AlarmManager.OnAlarmListener mDeepAlarmListener
566 = new AlarmManager.OnAlarmListener() {
567 @Override
568 public void onAlarm() {
569 synchronized (DeviceIdleController.this) {
570 stepIdleStateLocked("s:alarm");
571 }
572 }
573 };
574
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800575 private final BroadcastReceiver mIdleStartedDoneReceiver = new BroadcastReceiver() {
576 @Override public void onReceive(Context context, Intent intent) {
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700577 // When coming out of a deep idle, we will add in some delay before we allow
578 // the system to settle down and finish the maintenance window. This is
579 // to give a chance for any pending work to be scheduled.
580 if (PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED.equals(intent.getAction())) {
581 mHandler.sendEmptyMessageDelayed(MSG_FINISH_IDLE_OP,
582 mConstants.MIN_DEEP_MAINTENANCE_TIME);
583 } else {
584 mHandler.sendEmptyMessageDelayed(MSG_FINISH_IDLE_OP,
585 mConstants.MIN_LIGHT_MAINTENANCE_TIME);
586 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800587 }
588 };
589
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -0700590 private final BroadcastReceiver mInteractivityReceiver = new BroadcastReceiver() {
591 @Override
592 public void onReceive(Context context, Intent intent) {
Dianne Hackborn9b5ebc92017-09-08 13:45:35 -0700593 synchronized (DeviceIdleController.this) {
594 updateInteractivityLocked();
595 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700596 }
597 };
598
Kweku Adams00e3a372018-09-28 16:57:09 -0700599 @VisibleForTesting
600 final class MotionListener extends TriggerEventListener
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700601 implements SensorEventListener {
602
603 boolean active = false;
604
Kweku Adams00e3a372018-09-28 16:57:09 -0700605 public boolean isActive() {
606 return active;
607 }
608
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700609 @Override
610 public void onTrigger(TriggerEvent event) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700611 synchronized (DeviceIdleController.this) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700612 active = false;
613 motionLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700614 }
615 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700616
617 @Override
618 public void onSensorChanged(SensorEvent event) {
619 synchronized (DeviceIdleController.this) {
620 mSensorManager.unregisterListener(this, mMotionSensor);
621 active = false;
622 motionLocked();
623 }
624 }
625
626 @Override
627 public void onAccuracyChanged(Sensor sensor, int accuracy) {}
628
629 public boolean registerLocked() {
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700630 boolean success;
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700631 if (mMotionSensor.getReportingMode() == Sensor.REPORTING_MODE_ONE_SHOT) {
632 success = mSensorManager.requestTriggerSensor(mMotionListener, mMotionSensor);
633 } else {
634 success = mSensorManager.registerListener(
635 mMotionListener, mMotionSensor, SensorManager.SENSOR_DELAY_NORMAL);
636 }
637 if (success) {
638 active = true;
639 } else {
640 Slog.e(TAG, "Unable to register for " + mMotionSensor);
641 }
642 return success;
643 }
644
645 public void unregisterLocked() {
646 if (mMotionSensor.getReportingMode() == Sensor.REPORTING_MODE_ONE_SHOT) {
647 mSensorManager.cancelTriggerSensor(mMotionListener, mMotionSensor);
648 } else {
649 mSensorManager.unregisterListener(mMotionListener);
650 }
651 active = false;
652 }
653 }
Kweku Adams00e3a372018-09-28 16:57:09 -0700654 @VisibleForTesting final MotionListener mMotionListener = new MotionListener();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700655
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700656 private final LocationListener mGenericLocationListener = new LocationListener() {
657 @Override
658 public void onLocationChanged(Location location) {
659 synchronized (DeviceIdleController.this) {
660 receivedGenericLocationLocked(location);
661 }
662 }
663
664 @Override
665 public void onStatusChanged(String provider, int status, Bundle extras) {
666 }
667
668 @Override
669 public void onProviderEnabled(String provider) {
670 }
671
672 @Override
673 public void onProviderDisabled(String provider) {
674 }
675 };
676
677 private final LocationListener mGpsLocationListener = new LocationListener() {
678 @Override
679 public void onLocationChanged(Location location) {
680 synchronized (DeviceIdleController.this) {
681 receivedGpsLocationLocked(location);
682 }
683 }
684
685 @Override
686 public void onStatusChanged(String provider, int status, Bundle extras) {
687 }
688
689 @Override
690 public void onProviderEnabled(String provider) {
691 }
692
693 @Override
694 public void onProviderDisabled(String provider) {
695 }
696 };
697
Adam Lesinski31c05d12015-06-09 17:34:04 -0700698 /**
699 * All times are in milliseconds. These constants are kept synchronized with the system
700 * global Settings. Any access to this class or its fields should be done while
701 * holding the DeviceIdleController lock.
702 */
Kweku Adamsa457f4e2018-10-03 15:56:06 -0700703 @VisibleForTesting
704 final class Constants extends ContentObserver {
Adam Lesinski31c05d12015-06-09 17:34:04 -0700705 // Key names stored in the settings value.
Dianne Hackborn953fc942016-03-29 15:36:24 -0700706 private static final String KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT
707 = "light_after_inactive_to";
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700708 private static final String KEY_LIGHT_PRE_IDLE_TIMEOUT = "light_pre_idle_to";
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700709 private static final String KEY_LIGHT_IDLE_TIMEOUT = "light_idle_to";
Dianne Hackborn953fc942016-03-29 15:36:24 -0700710 private static final String KEY_LIGHT_IDLE_FACTOR = "light_idle_factor";
711 private static final String KEY_LIGHT_MAX_IDLE_TIMEOUT = "light_max_idle_to";
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800712 private static final String KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET
713 = "light_idle_maintenance_min_budget";
714 private static final String KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET
715 = "light_idle_maintenance_max_budget";
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700716 private static final String KEY_MIN_LIGHT_MAINTENANCE_TIME = "min_light_maintenance_time";
717 private static final String KEY_MIN_DEEP_MAINTENANCE_TIME = "min_deep_maintenance_time";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700718 private static final String KEY_INACTIVE_TIMEOUT = "inactive_to";
719 private static final String KEY_SENSING_TIMEOUT = "sensing_to";
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700720 private static final String KEY_LOCATING_TIMEOUT = "locating_to";
721 private static final String KEY_LOCATION_ACCURACY = "location_accuracy";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700722 private static final String KEY_MOTION_INACTIVE_TIMEOUT = "motion_inactive_to";
723 private static final String KEY_IDLE_AFTER_INACTIVE_TIMEOUT = "idle_after_inactive_to";
724 private static final String KEY_IDLE_PENDING_TIMEOUT = "idle_pending_to";
725 private static final String KEY_MAX_IDLE_PENDING_TIMEOUT = "max_idle_pending_to";
726 private static final String KEY_IDLE_PENDING_FACTOR = "idle_pending_factor";
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700727 private static final String KEY_QUICK_DOZE_DELAY_TIMEOUT = "quick_doze_delay_to";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700728 private static final String KEY_IDLE_TIMEOUT = "idle_to";
729 private static final String KEY_MAX_IDLE_TIMEOUT = "max_idle_to";
730 private static final String KEY_IDLE_FACTOR = "idle_factor";
731 private static final String KEY_MIN_TIME_TO_ALARM = "min_time_to_alarm";
732 private static final String KEY_MAX_TEMP_APP_WHITELIST_DURATION =
733 "max_temp_app_whitelist_duration";
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700734 private static final String KEY_MMS_TEMP_APP_WHITELIST_DURATION =
735 "mms_temp_app_whitelist_duration";
Dianne Hackborn451c3462015-07-21 17:39:46 -0700736 private static final String KEY_SMS_TEMP_APP_WHITELIST_DURATION =
737 "sms_temp_app_whitelist_duration";
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700738 private static final String KEY_NOTIFICATION_WHITELIST_DURATION =
739 "notification_whitelist_duration";
Amith Yamasani396a10c2018-01-19 10:58:07 -0800740 /**
741 * Whether to wait for the user to unlock the device before causing screen-on to
742 * exit doze. Default = true
743 */
744 private static final String KEY_WAIT_FOR_UNLOCK = "wait_for_unlock";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700745
746 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700747 * This is the time, after becoming inactive, that we go in to the first
748 * light-weight idle mode.
749 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
750 * @see #KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT
751 */
752 public long LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT;
753
754 /**
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700755 * This is amount of time we will wait from the point where we decide we would
756 * like to go idle until we actually do, while waiting for jobs and other current
757 * activity to finish.
758 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
759 * @see #KEY_LIGHT_PRE_IDLE_TIMEOUT
760 */
761 public long LIGHT_PRE_IDLE_TIMEOUT;
762
763 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700764 * This is the initial time that we will run in idle maintenance mode.
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700765 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
766 * @see #KEY_LIGHT_IDLE_TIMEOUT
767 */
768 public long LIGHT_IDLE_TIMEOUT;
769
770 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700771 * Scaling factor to apply to the light idle mode time each time we complete a cycle.
772 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
773 * @see #KEY_LIGHT_IDLE_FACTOR
774 */
775 public float LIGHT_IDLE_FACTOR;
776
777 /**
Kweku Adams00e3a372018-09-28 16:57:09 -0700778 * This is the maximum time we will run in idle maintenance mode.
Dianne Hackborn953fc942016-03-29 15:36:24 -0700779 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
780 * @see #KEY_LIGHT_MAX_IDLE_TIMEOUT
781 */
782 public long LIGHT_MAX_IDLE_TIMEOUT;
783
784 /**
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800785 * This is the minimum amount of time we want to make available for maintenance mode
786 * when lightly idling. That is, we will always have at least this amount of time
787 * available maintenance before timing out and cutting off maintenance mode.
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700788 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800789 * @see #KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700790 */
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800791 public long LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
792
793 /**
794 * This is the maximum amount of time we want to make available for maintenance mode
795 * when lightly idling. That is, if the system isn't using up its minimum maintenance
796 * budget and this time is being added to the budget reserve, this is the maximum
797 * reserve size we will allow to grow and thus the maximum amount of time we will
798 * allow for the maintenance window.
799 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
800 * @see #KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET
801 */
802 public long LIGHT_IDLE_MAINTENANCE_MAX_BUDGET;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700803
804 /**
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700805 * This is the minimum amount of time that we will stay in maintenance mode after
806 * a light doze. We have this minimum to allow various things to respond to switching
807 * in to maintenance mode and scheduling their work -- otherwise we may
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700808 * see there is nothing to do (no jobs pending) and go out of maintenance
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700809 * mode immediately.
810 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
811 * @see #KEY_MIN_LIGHT_MAINTENANCE_TIME
812 */
813 public long MIN_LIGHT_MAINTENANCE_TIME;
814
815 /**
816 * This is the minimum amount of time that we will stay in maintenance mode after
817 * a full doze. We have this minimum to allow various things to respond to switching
818 * in to maintenance mode and scheduling their work -- otherwise we may
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700819 * see there is nothing to do (no jobs pending) and go out of maintenance
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700820 * mode immediately.
821 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
822 * @see #KEY_MIN_DEEP_MAINTENANCE_TIME
823 */
824 public long MIN_DEEP_MAINTENANCE_TIME;
825
826 /**
Adam Lesinski31c05d12015-06-09 17:34:04 -0700827 * This is the time, after becoming inactive, at which we start looking at the
828 * motion sensor to determine if the device is being left alone. We don't do this
829 * immediately after going inactive just because we don't want to be continually running
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700830 * the motion sensor whenever the screen is off.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700831 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
832 * @see #KEY_INACTIVE_TIMEOUT
833 */
834 public long INACTIVE_TIMEOUT;
835
836 /**
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700837 * If we don't receive a callback from AnyMotion in this amount of time +
838 * {@link #LOCATING_TIMEOUT}, we will change from
Adam Lesinski31c05d12015-06-09 17:34:04 -0700839 * STATE_SENSING to STATE_INACTIVE, and any AnyMotion callbacks while not in STATE_SENSING
840 * will be ignored.
841 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
842 * @see #KEY_SENSING_TIMEOUT
843 */
844 public long SENSING_TIMEOUT;
845
846 /**
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700847 * This is how long we will wait to try to get a good location fix before going in to
848 * idle mode.
849 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
850 * @see #KEY_LOCATING_TIMEOUT
851 */
852 public long LOCATING_TIMEOUT;
853
854 /**
855 * The desired maximum accuracy (in meters) we consider the location to be good enough to go
856 * on to idle. We will be trying to get an accuracy fix at least this good or until
857 * {@link #LOCATING_TIMEOUT} expires.
858 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
859 * @see #KEY_LOCATION_ACCURACY
860 */
861 public float LOCATION_ACCURACY;
862
863 /**
Adam Lesinski31c05d12015-06-09 17:34:04 -0700864 * This is the time, after seeing motion, that we wait after becoming inactive from
865 * that until we start looking for motion again.
866 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
867 * @see #KEY_MOTION_INACTIVE_TIMEOUT
868 */
869 public long MOTION_INACTIVE_TIMEOUT;
870
871 /**
872 * This is the time, after the inactive timeout elapses, that we will wait looking
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700873 * for motion until we truly consider the device to be idle.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700874 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
875 * @see #KEY_IDLE_AFTER_INACTIVE_TIMEOUT
876 */
877 public long IDLE_AFTER_INACTIVE_TIMEOUT;
878
879 /**
880 * This is the initial time, after being idle, that we will allow ourself to be back
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700881 * in the IDLE_MAINTENANCE state allowing the system to run normally until we return to
882 * idle.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700883 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
884 * @see #KEY_IDLE_PENDING_TIMEOUT
885 */
886 public long IDLE_PENDING_TIMEOUT;
887
888 /**
889 * Maximum pending idle timeout (time spent running) we will be allowed to use.
890 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
891 * @see #KEY_MAX_IDLE_PENDING_TIMEOUT
892 */
893 public long MAX_IDLE_PENDING_TIMEOUT;
894
895 /**
896 * Scaling factor to apply to current pending idle timeout each time we cycle through
897 * that state.
898 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
899 * @see #KEY_IDLE_PENDING_FACTOR
900 */
901 public float IDLE_PENDING_FACTOR;
902
903 /**
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700904 * This is amount of time we will wait from the point where we go into
905 * STATE_QUICK_DOZE_DELAY until we actually go into STATE_IDLE, while waiting for jobs
906 * and other current activity to finish.
907 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
908 * @see #KEY_QUICK_DOZE_DELAY_TIMEOUT
909 */
910 public long QUICK_DOZE_DELAY_TIMEOUT;
911
912 /**
Adam Lesinski31c05d12015-06-09 17:34:04 -0700913 * This is the initial time that we want to sit in the idle state before waking up
914 * again to return to pending idle and allowing normal work to run.
915 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
916 * @see #KEY_IDLE_TIMEOUT
917 */
918 public long IDLE_TIMEOUT;
919
920 /**
921 * Maximum idle duration we will be allowed to use.
922 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
923 * @see #KEY_MAX_IDLE_TIMEOUT
924 */
925 public long MAX_IDLE_TIMEOUT;
926
927 /**
928 * Scaling factor to apply to current idle timeout each time we cycle through that state.
929 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
930 * @see #KEY_IDLE_FACTOR
931 */
932 public float IDLE_FACTOR;
933
934 /**
935 * This is the minimum time we will allow until the next upcoming alarm for us to
936 * actually go in to idle mode.
937 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
938 * @see #KEY_MIN_TIME_TO_ALARM
939 */
940 public long MIN_TIME_TO_ALARM;
941
942 /**
943 * Max amount of time to temporarily whitelist an app when it receives a high priority
944 * tickle.
945 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
946 * @see #KEY_MAX_TEMP_APP_WHITELIST_DURATION
947 */
948 public long MAX_TEMP_APP_WHITELIST_DURATION;
949
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700950 /**
951 * Amount of time we would like to whitelist an app that is receiving an MMS.
952 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
953 * @see #KEY_MMS_TEMP_APP_WHITELIST_DURATION
954 */
955 public long MMS_TEMP_APP_WHITELIST_DURATION;
956
Dianne Hackborn451c3462015-07-21 17:39:46 -0700957 /**
958 * Amount of time we would like to whitelist an app that is receiving an SMS.
959 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
960 * @see #KEY_SMS_TEMP_APP_WHITELIST_DURATION
961 */
962 public long SMS_TEMP_APP_WHITELIST_DURATION;
963
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700964 /**
965 * Amount of time we would like to whitelist an app that is handling a
966 * {@link android.app.PendingIntent} triggered by a {@link android.app.Notification}.
967 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
968 * @see #KEY_NOTIFICATION_WHITELIST_DURATION
969 */
970 public long NOTIFICATION_WHITELIST_DURATION;
971
Amith Yamasani396a10c2018-01-19 10:58:07 -0800972 public boolean WAIT_FOR_UNLOCK;
973
Adam Lesinski31c05d12015-06-09 17:34:04 -0700974 private final ContentResolver mResolver;
shreerag597da8a2017-07-21 14:24:14 -0700975 private final boolean mSmallBatteryDevice;
Adam Lesinski31c05d12015-06-09 17:34:04 -0700976 private final KeyValueListParser mParser = new KeyValueListParser(',');
977
978 public Constants(Handler handler, ContentResolver resolver) {
979 super(handler);
980 mResolver = resolver;
shreerag597da8a2017-07-21 14:24:14 -0700981 mSmallBatteryDevice = ActivityManager.isSmallBatteryDevice();
982 mResolver.registerContentObserver(
983 Settings.Global.getUriFor(Settings.Global.DEVICE_IDLE_CONSTANTS),
Joe LaPennaf33b5bf2016-03-23 15:19:47 -0700984 false, this);
Adam Lesinski31c05d12015-06-09 17:34:04 -0700985 updateConstants();
986 }
987
988 @Override
989 public void onChange(boolean selfChange, Uri uri) {
990 updateConstants();
991 }
992
993 private void updateConstants() {
994 synchronized (DeviceIdleController.this) {
995 try {
996 mParser.setString(Settings.Global.getString(mResolver,
shreerag597da8a2017-07-21 14:24:14 -0700997 Settings.Global.DEVICE_IDLE_CONSTANTS));
Adam Lesinski31c05d12015-06-09 17:34:04 -0700998 } catch (IllegalArgumentException e) {
999 // Failed to parse the settings string, log this and move on
1000 // with defaults.
1001 Slog.e(TAG, "Bad device idle settings", e);
1002 }
1003
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001004 LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT = mParser.getDurationMillis(
Dianne Hackborn953fc942016-03-29 15:36:24 -07001005 KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT,
Suprabh Shukla85fff7d2018-05-08 17:39:24 -07001006 !COMPRESS_TIME ? 3 * 60 * 1000L : 15 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001007 LIGHT_PRE_IDLE_TIMEOUT = mParser.getDurationMillis(KEY_LIGHT_PRE_IDLE_TIMEOUT,
Suprabh Shukla85fff7d2018-05-08 17:39:24 -07001008 !COMPRESS_TIME ? 3 * 60 * 1000L : 30 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001009 LIGHT_IDLE_TIMEOUT = mParser.getDurationMillis(KEY_LIGHT_IDLE_TIMEOUT,
Dianne Hackborn953fc942016-03-29 15:36:24 -07001010 !COMPRESS_TIME ? 5 * 60 * 1000L : 15 * 1000L);
1011 LIGHT_IDLE_FACTOR = mParser.getFloat(KEY_LIGHT_IDLE_FACTOR,
1012 2f);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001013 LIGHT_MAX_IDLE_TIMEOUT = mParser.getDurationMillis(KEY_LIGHT_MAX_IDLE_TIMEOUT,
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001014 !COMPRESS_TIME ? 15 * 60 * 1000L : 60 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001015 LIGHT_IDLE_MAINTENANCE_MIN_BUDGET = mParser.getDurationMillis(
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001016 KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET,
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001017 !COMPRESS_TIME ? 1 * 60 * 1000L : 15 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001018 LIGHT_IDLE_MAINTENANCE_MAX_BUDGET = mParser.getDurationMillis(
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001019 KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET,
1020 !COMPRESS_TIME ? 5 * 60 * 1000L : 30 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001021 MIN_LIGHT_MAINTENANCE_TIME = mParser.getDurationMillis(
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07001022 KEY_MIN_LIGHT_MAINTENANCE_TIME,
1023 !COMPRESS_TIME ? 5 * 1000L : 1 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001024 MIN_DEEP_MAINTENANCE_TIME = mParser.getDurationMillis(
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07001025 KEY_MIN_DEEP_MAINTENANCE_TIME,
1026 !COMPRESS_TIME ? 30 * 1000L : 5 * 1000L);
Michael Kwan88871462017-08-21 13:13:37 -07001027 long inactiveTimeoutDefault = (mSmallBatteryDevice ? 15 : 30) * 60 * 1000L;
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001028 INACTIVE_TIMEOUT = mParser.getDurationMillis(KEY_INACTIVE_TIMEOUT,
Joe LaPenna0c5d3e92016-03-24 13:29:56 -07001029 !COMPRESS_TIME ? inactiveTimeoutDefault : (inactiveTimeoutDefault / 10));
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001030 SENSING_TIMEOUT = mParser.getDurationMillis(KEY_SENSING_TIMEOUT,
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001031 !DEBUG ? 4 * 60 * 1000L : 60 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001032 LOCATING_TIMEOUT = mParser.getDurationMillis(KEY_LOCATING_TIMEOUT,
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001033 !DEBUG ? 30 * 1000L : 15 * 1000L);
1034 LOCATION_ACCURACY = mParser.getFloat(KEY_LOCATION_ACCURACY, 20);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001035 MOTION_INACTIVE_TIMEOUT = mParser.getDurationMillis(KEY_MOTION_INACTIVE_TIMEOUT,
Adam Lesinski31c05d12015-06-09 17:34:04 -07001036 !COMPRESS_TIME ? 10 * 60 * 1000L : 60 * 1000L);
Michael Kwan88871462017-08-21 13:13:37 -07001037 long idleAfterInactiveTimeout = (mSmallBatteryDevice ? 15 : 30) * 60 * 1000L;
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001038 IDLE_AFTER_INACTIVE_TIMEOUT = mParser.getDurationMillis(
1039 KEY_IDLE_AFTER_INACTIVE_TIMEOUT,
Joe LaPenna0c5d3e92016-03-24 13:29:56 -07001040 !COMPRESS_TIME ? idleAfterInactiveTimeout
1041 : (idleAfterInactiveTimeout / 10));
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001042 IDLE_PENDING_TIMEOUT = mParser.getDurationMillis(KEY_IDLE_PENDING_TIMEOUT,
Adam Lesinski31c05d12015-06-09 17:34:04 -07001043 !COMPRESS_TIME ? 5 * 60 * 1000L : 30 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001044 MAX_IDLE_PENDING_TIMEOUT = mParser.getDurationMillis(KEY_MAX_IDLE_PENDING_TIMEOUT,
Adam Lesinski31c05d12015-06-09 17:34:04 -07001045 !COMPRESS_TIME ? 10 * 60 * 1000L : 60 * 1000L);
1046 IDLE_PENDING_FACTOR = mParser.getFloat(KEY_IDLE_PENDING_FACTOR,
1047 2f);
Kweku Adamsb396ccf2018-09-17 16:37:15 -07001048 QUICK_DOZE_DELAY_TIMEOUT = mParser.getDurationMillis(
1049 KEY_QUICK_DOZE_DELAY_TIMEOUT, !COMPRESS_TIME ? 60 * 1000L : 15 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001050 IDLE_TIMEOUT = mParser.getDurationMillis(KEY_IDLE_TIMEOUT,
Adam Lesinski31c05d12015-06-09 17:34:04 -07001051 !COMPRESS_TIME ? 60 * 60 * 1000L : 6 * 60 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001052 MAX_IDLE_TIMEOUT = mParser.getDurationMillis(KEY_MAX_IDLE_TIMEOUT,
Adam Lesinski31c05d12015-06-09 17:34:04 -07001053 !COMPRESS_TIME ? 6 * 60 * 60 * 1000L : 30 * 60 * 1000L);
1054 IDLE_FACTOR = mParser.getFloat(KEY_IDLE_FACTOR,
1055 2f);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001056 MIN_TIME_TO_ALARM = mParser.getDurationMillis(KEY_MIN_TIME_TO_ALARM,
Adam Lesinski31c05d12015-06-09 17:34:04 -07001057 !COMPRESS_TIME ? 60 * 60 * 1000L : 6 * 60 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001058 MAX_TEMP_APP_WHITELIST_DURATION = mParser.getDurationMillis(
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001059 KEY_MAX_TEMP_APP_WHITELIST_DURATION, 5 * 60 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001060 MMS_TEMP_APP_WHITELIST_DURATION = mParser.getDurationMillis(
Dianne Hackborn0b6134b2015-07-14 18:48:07 -07001061 KEY_MMS_TEMP_APP_WHITELIST_DURATION, 60 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001062 SMS_TEMP_APP_WHITELIST_DURATION = mParser.getDurationMillis(
Dianne Hackborn451c3462015-07-21 17:39:46 -07001063 KEY_SMS_TEMP_APP_WHITELIST_DURATION, 20 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001064 NOTIFICATION_WHITELIST_DURATION = mParser.getDurationMillis(
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001065 KEY_NOTIFICATION_WHITELIST_DURATION, 30 * 1000L);
Amith Yamasani396a10c2018-01-19 10:58:07 -08001066 WAIT_FOR_UNLOCK = mParser.getBoolean(KEY_WAIT_FOR_UNLOCK, false);
Adam Lesinski31c05d12015-06-09 17:34:04 -07001067 }
1068 }
1069
1070 void dump(PrintWriter pw) {
1071 pw.println(" Settings:");
1072
Dianne Hackborn953fc942016-03-29 15:36:24 -07001073 pw.print(" "); pw.print(KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT); pw.print("=");
1074 TimeUtils.formatDuration(LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT, pw);
1075 pw.println();
1076
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001077 pw.print(" "); pw.print(KEY_LIGHT_PRE_IDLE_TIMEOUT); pw.print("=");
1078 TimeUtils.formatDuration(LIGHT_PRE_IDLE_TIMEOUT, pw);
1079 pw.println();
1080
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001081 pw.print(" "); pw.print(KEY_LIGHT_IDLE_TIMEOUT); pw.print("=");
1082 TimeUtils.formatDuration(LIGHT_IDLE_TIMEOUT, pw);
1083 pw.println();
1084
Dianne Hackborn953fc942016-03-29 15:36:24 -07001085 pw.print(" "); pw.print(KEY_LIGHT_IDLE_FACTOR); pw.print("=");
1086 pw.print(LIGHT_IDLE_FACTOR);
1087 pw.println();
1088
1089 pw.print(" "); pw.print(KEY_LIGHT_MAX_IDLE_TIMEOUT); pw.print("=");
1090 TimeUtils.formatDuration(LIGHT_MAX_IDLE_TIMEOUT, pw);
1091 pw.println();
1092
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001093 pw.print(" "); pw.print(KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET); pw.print("=");
1094 TimeUtils.formatDuration(LIGHT_IDLE_MAINTENANCE_MIN_BUDGET, pw);
1095 pw.println();
1096
1097 pw.print(" "); pw.print(KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET); pw.print("=");
1098 TimeUtils.formatDuration(LIGHT_IDLE_MAINTENANCE_MAX_BUDGET, pw);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001099 pw.println();
1100
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07001101 pw.print(" "); pw.print(KEY_MIN_LIGHT_MAINTENANCE_TIME); pw.print("=");
1102 TimeUtils.formatDuration(MIN_LIGHT_MAINTENANCE_TIME, pw);
1103 pw.println();
1104
1105 pw.print(" "); pw.print(KEY_MIN_DEEP_MAINTENANCE_TIME); pw.print("=");
1106 TimeUtils.formatDuration(MIN_DEEP_MAINTENANCE_TIME, pw);
1107 pw.println();
1108
Dianne Hackborna750a632015-06-16 17:18:23 -07001109 pw.print(" "); pw.print(KEY_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001110 TimeUtils.formatDuration(INACTIVE_TIMEOUT, pw);
1111 pw.println();
1112
Dianne Hackborna750a632015-06-16 17:18:23 -07001113 pw.print(" "); pw.print(KEY_SENSING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001114 TimeUtils.formatDuration(SENSING_TIMEOUT, pw);
1115 pw.println();
1116
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001117 pw.print(" "); pw.print(KEY_LOCATING_TIMEOUT); pw.print("=");
1118 TimeUtils.formatDuration(LOCATING_TIMEOUT, pw);
1119 pw.println();
1120
1121 pw.print(" "); pw.print(KEY_LOCATION_ACCURACY); pw.print("=");
1122 pw.print(LOCATION_ACCURACY); pw.print("m");
1123 pw.println();
1124
Dianne Hackborna750a632015-06-16 17:18:23 -07001125 pw.print(" "); pw.print(KEY_MOTION_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001126 TimeUtils.formatDuration(MOTION_INACTIVE_TIMEOUT, pw);
1127 pw.println();
1128
Dianne Hackborna750a632015-06-16 17:18:23 -07001129 pw.print(" "); pw.print(KEY_IDLE_AFTER_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001130 TimeUtils.formatDuration(IDLE_AFTER_INACTIVE_TIMEOUT, pw);
1131 pw.println();
1132
Dianne Hackborna750a632015-06-16 17:18:23 -07001133 pw.print(" "); pw.print(KEY_IDLE_PENDING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001134 TimeUtils.formatDuration(IDLE_PENDING_TIMEOUT, pw);
1135 pw.println();
1136
Dianne Hackborna750a632015-06-16 17:18:23 -07001137 pw.print(" "); pw.print(KEY_MAX_IDLE_PENDING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001138 TimeUtils.formatDuration(MAX_IDLE_PENDING_TIMEOUT, pw);
1139 pw.println();
1140
Dianne Hackborna750a632015-06-16 17:18:23 -07001141 pw.print(" "); pw.print(KEY_IDLE_PENDING_FACTOR); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001142 pw.println(IDLE_PENDING_FACTOR);
1143
Kweku Adamsb396ccf2018-09-17 16:37:15 -07001144 pw.print(" "); pw.print(KEY_QUICK_DOZE_DELAY_TIMEOUT); pw.print("=");
1145 TimeUtils.formatDuration(QUICK_DOZE_DELAY_TIMEOUT, pw);
1146 pw.println();
1147
Dianne Hackborna750a632015-06-16 17:18:23 -07001148 pw.print(" "); pw.print(KEY_IDLE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001149 TimeUtils.formatDuration(IDLE_TIMEOUT, pw);
1150 pw.println();
1151
Dianne Hackborna750a632015-06-16 17:18:23 -07001152 pw.print(" "); pw.print(KEY_MAX_IDLE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001153 TimeUtils.formatDuration(MAX_IDLE_TIMEOUT, pw);
1154 pw.println();
1155
Dianne Hackborna750a632015-06-16 17:18:23 -07001156 pw.print(" "); pw.print(KEY_IDLE_FACTOR); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001157 pw.println(IDLE_FACTOR);
1158
Dianne Hackborna750a632015-06-16 17:18:23 -07001159 pw.print(" "); pw.print(KEY_MIN_TIME_TO_ALARM); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001160 TimeUtils.formatDuration(MIN_TIME_TO_ALARM, pw);
1161 pw.println();
1162
Dianne Hackborna750a632015-06-16 17:18:23 -07001163 pw.print(" "); pw.print(KEY_MAX_TEMP_APP_WHITELIST_DURATION); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001164 TimeUtils.formatDuration(MAX_TEMP_APP_WHITELIST_DURATION, pw);
1165 pw.println();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001166
1167 pw.print(" "); pw.print(KEY_MMS_TEMP_APP_WHITELIST_DURATION); pw.print("=");
1168 TimeUtils.formatDuration(MMS_TEMP_APP_WHITELIST_DURATION, pw);
1169 pw.println();
Dianne Hackborn451c3462015-07-21 17:39:46 -07001170
1171 pw.print(" "); pw.print(KEY_SMS_TEMP_APP_WHITELIST_DURATION); pw.print("=");
1172 TimeUtils.formatDuration(SMS_TEMP_APP_WHITELIST_DURATION, pw);
1173 pw.println();
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001174
1175 pw.print(" "); pw.print(KEY_NOTIFICATION_WHITELIST_DURATION); pw.print("=");
1176 TimeUtils.formatDuration(NOTIFICATION_WHITELIST_DURATION, pw);
1177 pw.println();
Amith Yamasani396a10c2018-01-19 10:58:07 -08001178
1179 pw.print(" "); pw.print(KEY_WAIT_FOR_UNLOCK); pw.print("=");
1180 pw.println(WAIT_FOR_UNLOCK);
Adam Lesinski31c05d12015-06-09 17:34:04 -07001181 }
1182 }
1183
1184 private Constants mConstants;
1185
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001186 @Override
1187 public void onAnyMotionResult(int result) {
1188 if (DEBUG) Slog.d(TAG, "onAnyMotionResult(" + result + ")");
Kevin Gabayan92f15e62016-04-04 17:52:22 -07001189 if (result != AnyMotionDetector.RESULT_UNKNOWN) {
1190 synchronized (this) {
1191 cancelSensingTimeoutAlarmLocked();
1192 }
1193 }
Kevin Gabayandcf47012016-07-08 10:41:24 -07001194 if ((result == AnyMotionDetector.RESULT_MOVED) ||
1195 (result == AnyMotionDetector.RESULT_UNKNOWN)) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001196 synchronized (this) {
Kevin Gabayandcf47012016-07-08 10:41:24 -07001197 handleMotionDetectedLocked(mConstants.INACTIVE_TIMEOUT, "non_stationary");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001198 }
1199 } else if (result == AnyMotionDetector.RESULT_STATIONARY) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001200 if (mState == STATE_SENSING) {
1201 // If we are currently sensing, it is time to move to locating.
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001202 synchronized (this) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001203 mNotMoving = true;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001204 stepIdleStateLocked("s:stationary");
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001205 }
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001206 } else if (mState == STATE_LOCATING) {
1207 // If we are currently locating, note that we are not moving and step
1208 // if we have located the position.
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001209 synchronized (this) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001210 mNotMoving = true;
1211 if (mLocated) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001212 stepIdleStateLocked("s:stationary");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001213 }
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001214 }
1215 }
1216 }
1217 }
1218
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001219 private static final int MSG_WRITE_CONFIG = 1;
1220 private static final int MSG_REPORT_IDLE_ON = 2;
1221 private static final int MSG_REPORT_IDLE_ON_LIGHT = 3;
1222 private static final int MSG_REPORT_IDLE_OFF = 4;
1223 private static final int MSG_REPORT_ACTIVE = 5;
1224 private static final int MSG_TEMP_APP_WHITELIST_TIMEOUT = 6;
1225 private static final int MSG_REPORT_MAINTENANCE_ACTIVITY = 7;
1226 private static final int MSG_FINISH_IDLE_OP = 8;
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001227 private static final int MSG_REPORT_TEMP_APP_WHITELIST_CHANGED = 9;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001228
1229 final class MyHandler extends Handler {
1230 MyHandler(Looper looper) {
1231 super(looper);
1232 }
1233
1234 @Override public void handleMessage(Message msg) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001235 if (DEBUG) Slog.d(TAG, "handleMessage(" + msg.what + ")");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001236 switch (msg.what) {
1237 case MSG_WRITE_CONFIG: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001238 // Does not hold a wakelock. Just let this happen whenever.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001239 handleWriteConfigFile();
1240 } break;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001241 case MSG_REPORT_IDLE_ON:
1242 case MSG_REPORT_IDLE_ON_LIGHT: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001243 // mGoingIdleWakeLock is held at this point
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001244 EventLogTags.writeDeviceIdleOnStart();
Dianne Hackbornb6843652016-02-22 12:20:13 -08001245 final boolean deepChanged;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001246 final boolean lightChanged;
1247 if (msg.what == MSG_REPORT_IDLE_ON) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001248 deepChanged = mLocalPowerManager.setDeviceIdleMode(true);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001249 lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
1250 } else {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001251 deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001252 lightChanged = mLocalPowerManager.setLightDeviceIdleMode(true);
1253 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001254 try {
1255 mNetworkPolicyManager.setDeviceIdleMode(true);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001256 mBatteryStats.noteDeviceIdleMode(msg.what == MSG_REPORT_IDLE_ON
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07001257 ? BatteryStats.DEVICE_IDLE_MODE_DEEP
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001258 : BatteryStats.DEVICE_IDLE_MODE_LIGHT, null, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001259 } catch (RemoteException e) {
1260 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001261 if (deepChanged) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001262 getContext().sendBroadcastAsUser(mIdleIntent, UserHandle.ALL);
1263 }
1264 if (lightChanged) {
1265 getContext().sendBroadcastAsUser(mLightIdleIntent, UserHandle.ALL);
1266 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001267 EventLogTags.writeDeviceIdleOnComplete();
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001268 mGoingIdleWakeLock.release();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001269 } break;
1270 case MSG_REPORT_IDLE_OFF: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001271 // mActiveIdleWakeLock is held at this point
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001272 EventLogTags.writeDeviceIdleOffStart("unknown");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001273 final boolean deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001274 final boolean lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001275 try {
1276 mNetworkPolicyManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001277 mBatteryStats.noteDeviceIdleMode(BatteryStats.DEVICE_IDLE_MODE_OFF,
1278 null, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001279 } catch (RemoteException e) {
1280 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001281 if (deepChanged) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001282 incActiveIdleOps();
1283 getContext().sendOrderedBroadcastAsUser(mIdleIntent, UserHandle.ALL,
1284 null, mIdleStartedDoneReceiver, null, 0, null, null);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001285 }
1286 if (lightChanged) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001287 incActiveIdleOps();
1288 getContext().sendOrderedBroadcastAsUser(mLightIdleIntent, UserHandle.ALL,
1289 null, mIdleStartedDoneReceiver, null, 0, null, null);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001290 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001291 // Always start with one active op for the message being sent here.
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001292 // Now we are done!
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001293 decActiveIdleOps();
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001294 EventLogTags.writeDeviceIdleOffComplete();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001295 } break;
1296 case MSG_REPORT_ACTIVE: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001297 // The device is awake at this point, so no wakelock necessary.
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001298 String activeReason = (String)msg.obj;
1299 int activeUid = msg.arg1;
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001300 EventLogTags.writeDeviceIdleOffStart(
1301 activeReason != null ? activeReason : "unknown");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001302 final boolean deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001303 final boolean lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001304 try {
1305 mNetworkPolicyManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001306 mBatteryStats.noteDeviceIdleMode(BatteryStats.DEVICE_IDLE_MODE_OFF,
1307 activeReason, activeUid);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001308 } catch (RemoteException e) {
1309 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001310 if (deepChanged) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001311 getContext().sendBroadcastAsUser(mIdleIntent, UserHandle.ALL);
1312 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001313 if (lightChanged) {
1314 getContext().sendBroadcastAsUser(mLightIdleIntent, UserHandle.ALL);
1315 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001316 EventLogTags.writeDeviceIdleOffComplete();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001317 } break;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001318 case MSG_TEMP_APP_WHITELIST_TIMEOUT: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001319 // TODO: What is keeping the device awake at this point? Does it need to be?
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001320 int uid = msg.arg1;
1321 checkTempAppWhitelistTimeout(uid);
1322 } break;
Yao Chenca5edbb2016-01-13 14:44:36 -08001323 case MSG_REPORT_MAINTENANCE_ACTIVITY: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001324 // TODO: What is keeping the device awake at this point? Does it need to be?
Yao Chenca5edbb2016-01-13 14:44:36 -08001325 boolean active = (msg.arg1 == 1);
1326 final int size = mMaintenanceActivityListeners.beginBroadcast();
1327 try {
1328 for (int i = 0; i < size; i++) {
1329 try {
1330 mMaintenanceActivityListeners.getBroadcastItem(i)
1331 .onMaintenanceActivityChanged(active);
1332 } catch (RemoteException ignored) {
1333 }
1334 }
1335 } finally {
1336 mMaintenanceActivityListeners.finishBroadcast();
1337 }
1338 } break;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001339 case MSG_FINISH_IDLE_OP: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001340 // mActiveIdleWakeLock is held at this point
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001341 decActiveIdleOps();
1342 } break;
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001343 case MSG_REPORT_TEMP_APP_WHITELIST_CHANGED: {
1344 final int appId = msg.arg1;
1345 final boolean added = (msg.arg2 == 1);
1346 mNetworkPolicyManagerInternal.onTempPowerSaveWhitelistChange(appId, added);
1347 } break;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001348 }
1349 }
1350 }
1351
1352 final MyHandler mHandler;
1353
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001354 BinderService mBinderService;
1355
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001356 private final class BinderService extends IDeviceIdleController.Stub {
1357 @Override public void addPowerSaveWhitelistApp(String name) {
Eugene Susla6a7006a2017-03-13 12:57:58 -07001358 if (DEBUG) {
1359 Slog.i(TAG, "addPowerSaveWhitelistApp(name = " + name + ")");
1360 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001361 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1362 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001363 long ident = Binder.clearCallingIdentity();
1364 try {
1365 addPowerSaveWhitelistAppInternal(name);
1366 } finally {
1367 Binder.restoreCallingIdentity(ident);
1368 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001369 }
1370
1371 @Override public void removePowerSaveWhitelistApp(String name) {
Eugene Susla6a7006a2017-03-13 12:57:58 -07001372 if (DEBUG) {
1373 Slog.i(TAG, "removePowerSaveWhitelistApp(name = " + name + ")");
1374 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001375 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1376 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001377 long ident = Binder.clearCallingIdentity();
1378 try {
1379 removePowerSaveWhitelistAppInternal(name);
1380 } finally {
1381 Binder.restoreCallingIdentity(ident);
1382 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001383 }
1384
Suprabh Shukla08105642017-09-26 14:45:30 -07001385 @Override public void removeSystemPowerWhitelistApp(String name) {
1386 if (DEBUG) {
1387 Slog.d(TAG, "removeAppFromSystemWhitelist(name = " + name + ")");
1388 }
1389 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1390 null);
1391 long ident = Binder.clearCallingIdentity();
1392 try {
1393 removeSystemPowerWhitelistAppInternal(name);
1394 } finally {
1395 Binder.restoreCallingIdentity(ident);
1396 }
1397 }
1398
1399 @Override public void restoreSystemPowerWhitelistApp(String name) {
1400 if (DEBUG) {
1401 Slog.d(TAG, "restoreAppToSystemWhitelist(name = " + name + ")");
1402 }
1403 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1404 null);
1405 long ident = Binder.clearCallingIdentity();
1406 try {
1407 restoreSystemPowerWhitelistAppInternal(name);
1408 } finally {
1409 Binder.restoreCallingIdentity(ident);
1410 }
1411 }
1412
1413 public String[] getRemovedSystemPowerWhitelistApps() {
1414 return getRemovedSystemPowerWhitelistAppsInternal();
1415 }
1416
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001417 @Override public String[] getSystemPowerWhitelistExceptIdle() {
1418 return getSystemPowerWhitelistExceptIdleInternal();
1419 }
1420
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001421 @Override public String[] getSystemPowerWhitelist() {
1422 return getSystemPowerWhitelistInternal();
1423 }
1424
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001425 @Override public String[] getUserPowerWhitelist() {
1426 return getUserPowerWhitelistInternal();
1427 }
1428
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001429 @Override public String[] getFullPowerWhitelistExceptIdle() {
1430 return getFullPowerWhitelistExceptIdleInternal();
1431 }
1432
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001433 @Override public String[] getFullPowerWhitelist() {
1434 return getFullPowerWhitelistInternal();
1435 }
1436
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001437 @Override public int[] getAppIdWhitelistExceptIdle() {
1438 return getAppIdWhitelistExceptIdleInternal();
1439 }
1440
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001441 @Override public int[] getAppIdWhitelist() {
1442 return getAppIdWhitelistInternal();
1443 }
1444
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001445 @Override public int[] getAppIdUserWhitelist() {
1446 return getAppIdUserWhitelistInternal();
1447 }
1448
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001449 @Override public int[] getAppIdTempWhitelist() {
1450 return getAppIdTempWhitelistInternal();
1451 }
1452
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001453 @Override public boolean isPowerSaveWhitelistExceptIdleApp(String name) {
1454 return isPowerSaveWhitelistExceptIdleAppInternal(name);
1455 }
1456
Amith Yamasani06bf8242015-05-08 16:36:21 -07001457 @Override public boolean isPowerSaveWhitelistApp(String name) {
1458 return isPowerSaveWhitelistAppInternal(name);
1459 }
1460
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001461 @Override public void addPowerSaveTempWhitelistApp(String packageName, long duration,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001462 int userId, String reason) throws RemoteException {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001463 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001464 }
1465
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001466 @Override public long addPowerSaveTempWhitelistAppForMms(String packageName,
1467 int userId, String reason) throws RemoteException {
1468 long duration = mConstants.MMS_TEMP_APP_WHITELIST_DURATION;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001469 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001470 return duration;
1471 }
1472
Dianne Hackborn451c3462015-07-21 17:39:46 -07001473 @Override public long addPowerSaveTempWhitelistAppForSms(String packageName,
1474 int userId, String reason) throws RemoteException {
1475 long duration = mConstants.SMS_TEMP_APP_WHITELIST_DURATION;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001476 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Dianne Hackborn451c3462015-07-21 17:39:46 -07001477 return duration;
1478 }
1479
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001480 @Override public void exitIdle(String reason) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001481 getContext().enforceCallingOrSelfPermission(Manifest.permission.DEVICE_POWER,
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001482 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001483 long ident = Binder.clearCallingIdentity();
1484 try {
1485 exitIdleInternal(reason);
1486 } finally {
1487 Binder.restoreCallingIdentity(ident);
1488 }
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001489 }
1490
Yao Chenca5edbb2016-01-13 14:44:36 -08001491 @Override public boolean registerMaintenanceActivityListener(
1492 IMaintenanceActivityListener listener) {
1493 return DeviceIdleController.this.registerMaintenanceActivityListener(listener);
1494 }
1495
1496 @Override public void unregisterMaintenanceActivityListener(
1497 IMaintenanceActivityListener listener) {
1498 DeviceIdleController.this.unregisterMaintenanceActivityListener(listener);
1499 }
1500
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001501 @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1502 DeviceIdleController.this.dump(fd, pw, args);
1503 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001504
1505 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07001506 FileDescriptor err, String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
1507 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001508 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001509 }
1510
Felipe Lemeef134662016-08-10 14:46:39 -07001511 public class LocalService {
Christopher Tatee0be7e82017-02-08 17:38:20 -08001512 // duration in milliseconds
1513 public void addPowerSaveTempWhitelistApp(int callingUid, String packageName,
1514 long duration, int userId, boolean sync, String reason) {
1515 addPowerSaveTempWhitelistAppInternal(callingUid, packageName, duration,
1516 userId, sync, reason);
1517 }
1518
1519 // duration in milliseconds
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001520 public void addPowerSaveTempWhitelistAppDirect(int appId, long duration, boolean sync,
1521 String reason) {
1522 addPowerSaveTempWhitelistAppDirectInternal(0, appId, duration, sync, reason);
1523 }
1524
Christopher Tatee0be7e82017-02-08 17:38:20 -08001525 // duration in milliseconds
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001526 public long getNotificationWhitelistDuration() {
1527 return mConstants.NOTIFICATION_WHITELIST_DURATION;
1528 }
1529
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001530 public void setJobsActive(boolean active) {
1531 DeviceIdleController.this.setJobsActive(active);
1532 }
1533
1534 // Up-call from alarm manager.
1535 public void setAlarmsActive(boolean active) {
1536 DeviceIdleController.this.setAlarmsActive(active);
1537 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001538
Christopher Tate42a386b2016-11-07 12:21:21 -08001539 /** Is the app on any of the power save whitelists, whether system or user? */
1540 public boolean isAppOnWhitelist(int appid) {
1541 return DeviceIdleController.this.isAppOnWhitelistInternal(appid);
1542 }
1543
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001544 /**
1545 * Returns the array of app ids whitelisted by user. Take care not to
1546 * modify this, as it is a reference to the original copy. But the reference
1547 * can change when the list changes, so it needs to be re-acquired when
1548 * {@link PowerManager#ACTION_POWER_SAVE_WHITELIST_CHANGED} is sent.
1549 */
1550 public int[] getPowerSaveWhitelistUserAppIds() {
1551 return DeviceIdleController.this.getPowerSaveWhitelistUserAppIds();
1552 }
Suprabh Shuklaa78acfd2017-10-13 19:29:36 -07001553
1554 public int[] getPowerSaveTempWhitelistAppIds() {
1555 return DeviceIdleController.this.getAppIdTempWhitelistInternal();
1556 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001557 }
1558
Kweku Adams00e3a372018-09-28 16:57:09 -07001559 static class Injector {
1560 private final Context mContext;
Kweku Adams799858b2018-10-08 17:19:08 -07001561 private ConnectivityService mConnectivityService;
1562 private LocationManager mLocationManager;
Kweku Adams00e3a372018-09-28 16:57:09 -07001563
1564 Injector(Context ctx) {
1565 mContext = ctx;
1566 }
1567
1568 AlarmManager getAlarmManager() {
1569 return mContext.getSystemService(AlarmManager.class);
1570 }
1571
1572 AnyMotionDetector getAnyMotionDetector(Handler handler, SensorManager sm,
1573 AnyMotionDetector.DeviceIdleCallback callback, float angleThreshold) {
1574 return new AnyMotionDetector(getPowerManager(), handler, sm, callback, angleThreshold);
1575 }
1576
1577 AppStateTracker getAppStateTracker(Context ctx, Looper looper) {
1578 return new AppStateTracker(ctx, looper);
1579 }
1580
1581 ConnectivityService getConnectivityService() {
Kweku Adams799858b2018-10-08 17:19:08 -07001582 if (mConnectivityService == null) {
1583 mConnectivityService = (ConnectivityService) ServiceManager.getService(
1584 Context.CONNECTIVITY_SERVICE);
1585 }
1586 return mConnectivityService;
Kweku Adams00e3a372018-09-28 16:57:09 -07001587 }
1588
Kweku Adamsa457f4e2018-10-03 15:56:06 -07001589 Constants getConstants(DeviceIdleController controller, Handler handler,
1590 ContentResolver resolver) {
1591 return controller.new Constants(handler, resolver);
1592 }
1593
Kweku Adams00e3a372018-09-28 16:57:09 -07001594 LocationManager getLocationManager() {
Kweku Adams799858b2018-10-08 17:19:08 -07001595 if (mLocationManager == null) {
1596 mLocationManager = mContext.getSystemService(LocationManager.class);
1597 }
1598 return mLocationManager;
Kweku Adams00e3a372018-09-28 16:57:09 -07001599 }
1600
Kweku Adamsa457f4e2018-10-03 15:56:06 -07001601 MyHandler getHandler(DeviceIdleController controller) {
1602 return controller.new MyHandler(BackgroundThread.getHandler().getLooper());
Kweku Adams00e3a372018-09-28 16:57:09 -07001603 }
1604
1605 PowerManager getPowerManager() {
1606 return mContext.getSystemService(PowerManager.class);
1607 }
1608 }
1609
1610 private final Injector mInjector;
1611
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001612 private ActivityTaskManagerInternal.ScreenObserver mScreenObserver =
1613 new ActivityTaskManagerInternal.ScreenObserver() {
Amith Yamasani396a10c2018-01-19 10:58:07 -08001614 @Override
1615 public void onAwakeStateChanged(boolean isAwake) { }
1616
1617 @Override
1618 public void onKeyguardStateChanged(boolean isShowing) {
1619 synchronized (DeviceIdleController.this) {
1620 DeviceIdleController.this.keyguardShowingLocked(isShowing);
1621 }
1622 }
1623 };
1624
Kweku Adams00e3a372018-09-28 16:57:09 -07001625 @VisibleForTesting DeviceIdleController(Context context, Injector injector) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001626 super(context);
Kweku Adams00e3a372018-09-28 16:57:09 -07001627 mInjector = injector;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001628 mConfigFile = new AtomicFile(new File(getSystemDir(), "deviceidle.xml"));
Kweku Adams00e3a372018-09-28 16:57:09 -07001629 mHandler = mInjector.getHandler(this);
1630 mAppStateTracker = mInjector.getAppStateTracker(context, FgThread.get().getLooper());
Makoto Onukie4918212018-02-06 11:30:15 -08001631 LocalServices.addService(AppStateTracker.class, mAppStateTracker);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001632 }
1633
Kweku Adams00e3a372018-09-28 16:57:09 -07001634 public DeviceIdleController(Context context) {
1635 this(context, new Injector(context));
1636 }
1637
Christopher Tate42a386b2016-11-07 12:21:21 -08001638 boolean isAppOnWhitelistInternal(int appid) {
1639 synchronized (this) {
1640 return Arrays.binarySearch(mPowerSaveWhitelistAllAppIdArray, appid) >= 0;
1641 }
1642 }
1643
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001644 int[] getPowerSaveWhitelistUserAppIds() {
1645 synchronized (this) {
1646 return mPowerSaveWhitelistUserAppIdArray;
1647 }
1648 }
1649
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001650 private static File getSystemDir() {
1651 return new File(Environment.getDataDirectory(), "system");
1652 }
1653
1654 @Override
1655 public void onStart() {
1656 final PackageManager pm = getContext().getPackageManager();
1657
1658 synchronized (this) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001659 mLightEnabled = mDeepEnabled = getContext().getResources().getBoolean(
Dianne Hackborn92617032015-06-19 15:32:19 -07001660 com.android.internal.R.bool.config_enableAutoPowerModes);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001661 SystemConfig sysConfig = SystemConfig.getInstance();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001662 ArraySet<String> allowPowerExceptIdle = sysConfig.getAllowInPowerSaveExceptIdle();
1663 for (int i=0; i<allowPowerExceptIdle.size(); i++) {
1664 String pkg = allowPowerExceptIdle.valueAt(i);
1665 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001666 ApplicationInfo ai = pm.getApplicationInfo(pkg,
1667 PackageManager.MATCH_SYSTEM_ONLY);
1668 int appid = UserHandle.getAppId(ai.uid);
1669 mPowerSaveWhitelistAppsExceptIdle.put(ai.packageName, appid);
1670 mPowerSaveWhitelistSystemAppIdsExceptIdle.put(appid, true);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001671 } catch (PackageManager.NameNotFoundException e) {
1672 }
1673 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001674 ArraySet<String> allowPower = sysConfig.getAllowInPowerSave();
1675 for (int i=0; i<allowPower.size(); i++) {
1676 String pkg = allowPower.valueAt(i);
1677 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001678 ApplicationInfo ai = pm.getApplicationInfo(pkg,
1679 PackageManager.MATCH_SYSTEM_ONLY);
1680 int appid = UserHandle.getAppId(ai.uid);
1681 // These apps are on both the whitelist-except-idle as well
1682 // as the full whitelist, so they apply in all cases.
1683 mPowerSaveWhitelistAppsExceptIdle.put(ai.packageName, appid);
1684 mPowerSaveWhitelistSystemAppIdsExceptIdle.put(appid, true);
1685 mPowerSaveWhitelistApps.put(ai.packageName, appid);
1686 mPowerSaveWhitelistSystemAppIds.put(appid, true);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001687 } catch (PackageManager.NameNotFoundException e) {
1688 }
1689 }
1690
Kweku Adamsa457f4e2018-10-03 15:56:06 -07001691 mConstants = mInjector.getConstants(this, mHandler, getContext().getContentResolver());
Adam Lesinski31c05d12015-06-09 17:34:04 -07001692
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001693 readConfigFileLocked();
1694 updateWhitelistAppIdsLocked();
1695
Dianne Hackborn88c41352016-04-07 15:18:58 -07001696 mNetworkConnected = true;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001697 mScreenOn = true;
Amith Yamasani396a10c2018-01-19 10:58:07 -08001698 mScreenLocked = false;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001699 // Start out assuming we are charging. If we aren't, we will at least get
1700 // a battery update the next time the level drops.
1701 mCharging = true;
1702 mState = STATE_ACTIVE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001703 mLightState = LIGHT_STATE_ACTIVE;
Adam Lesinski31c05d12015-06-09 17:34:04 -07001704 mInactiveTimeout = mConstants.INACTIVE_TIMEOUT;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001705 }
1706
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001707 mBinderService = new BinderService();
1708 publishBinderService(Context.DEVICE_IDLE_CONTROLLER, mBinderService);
Dianne Hackborna750a632015-06-16 17:18:23 -07001709 publishLocalService(LocalService.class, new LocalService());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001710 }
1711
1712 @Override
1713 public void onBootPhase(int phase) {
1714 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1715 synchronized (this) {
Kweku Adams00e3a372018-09-28 16:57:09 -07001716 mAlarmManager = mInjector.getAlarmManager();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001717 mBatteryStats = BatteryStatsService.getService();
Dianne Hackborn85e35642017-01-12 15:10:57 -08001718 mLocalActivityManager = getLocalService(ActivityManagerInternal.class);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001719 mLocalActivityTaskManager = getLocalService(ActivityTaskManagerInternal.class);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001720 mLocalPowerManager = getLocalService(PowerManagerInternal.class);
Kweku Adams00e3a372018-09-28 16:57:09 -07001721 mPowerManager = mInjector.getPowerManager();
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001722 mActiveIdleWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
1723 "deviceidle_maint");
1724 mActiveIdleWakeLock.setReferenceCounted(false);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001725 mGoingIdleWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
1726 "deviceidle_going_idle");
1727 mGoingIdleWakeLock.setReferenceCounted(true);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001728 mNetworkPolicyManager = INetworkPolicyManager.Stub.asInterface(
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001729 ServiceManager.getService(Context.NETWORK_POLICY_SERVICE));
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001730 mNetworkPolicyManagerInternal = getLocalService(NetworkPolicyManagerInternal.class);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001731 mSensorManager = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001732 int sigMotionSensorId = getContext().getResources().getInteger(
1733 com.android.internal.R.integer.config_autoPowerModeAnyMotionSensor);
1734 if (sigMotionSensorId > 0) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001735 mMotionSensor = mSensorManager.getDefaultSensor(sigMotionSensorId, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001736 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001737 if (mMotionSensor == null && getContext().getResources().getBoolean(
Joe LaPenna23d681b2015-08-27 15:12:11 -07001738 com.android.internal.R.bool.config_autoPowerModePreferWristTilt)) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001739 mMotionSensor = mSensorManager.getDefaultSensor(
1740 Sensor.TYPE_WRIST_TILT_GESTURE, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001741 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001742 if (mMotionSensor == null) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07001743 // As a last ditch, fall back to SMD.
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001744 mMotionSensor = mSensorManager.getDefaultSensor(
1745 Sensor.TYPE_SIGNIFICANT_MOTION, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001746 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001747
Joe LaPenna23d681b2015-08-27 15:12:11 -07001748 if (getContext().getResources().getBoolean(
1749 com.android.internal.R.bool.config_autoPowerModePrefetchLocation)) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07001750 mLocationRequest = new LocationRequest()
1751 .setQuality(LocationRequest.ACCURACY_FINE)
1752 .setInterval(0)
1753 .setFastestInterval(0)
1754 .setNumUpdates(1);
1755 }
1756
1757 float angleThreshold = getContext().getResources().getInteger(
1758 com.android.internal.R.integer.config_autoPowerModeThresholdAngle) / 100f;
Kweku Adams00e3a372018-09-28 16:57:09 -07001759 mAnyMotionDetector = mInjector.getAnyMotionDetector(mHandler, mSensorManager, this,
1760 angleThreshold);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001761
Makoto Onukie4918212018-02-06 11:30:15 -08001762 mAppStateTracker.onSystemServicesReady();
1763
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001764 mIdleIntent = new Intent(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001765 mIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1766 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001767 mLightIdleIntent = new Intent(PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED);
1768 mLightIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1769 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001770
1771 IntentFilter filter = new IntentFilter();
1772 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001773 getContext().registerReceiver(mReceiver, filter);
Amith Yamasaniac59f75e2016-05-05 12:38:17 -07001774
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001775 filter = new IntentFilter();
1776 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1777 filter.addDataScheme("package");
Amith Yamasaniac59f75e2016-05-05 12:38:17 -07001778 getContext().registerReceiver(mReceiver, filter);
1779
Dianne Hackborn88c41352016-04-07 15:18:58 -07001780 filter = new IntentFilter();
1781 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001782 getContext().registerReceiver(mReceiver, filter);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001783
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -07001784 filter = new IntentFilter();
1785 filter.addAction(Intent.ACTION_SCREEN_OFF);
1786 filter.addAction(Intent.ACTION_SCREEN_ON);
1787 getContext().registerReceiver(mInteractivityReceiver, filter);
1788
Makoto Onukiaf8ff4f2018-06-04 14:44:19 -07001789 mLocalActivityManager.setDeviceIdleWhitelist(
1790 mPowerSaveWhitelistAllAppIdArray, mPowerSaveWhitelistExceptIdleAppIdArray);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001791 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -07001792
Kweku Adamsb396ccf2018-09-17 16:37:15 -07001793 mLocalPowerManager.registerLowPowerModeObserver(ServiceType.QUICK_DOZE,
1794 state -> {
1795 synchronized (DeviceIdleController.this) {
1796 updateQuickDozeFlagLocked(state.batterySaverEnabled);
1797 }
1798 });
1799 updateQuickDozeFlagLocked(
1800 mLocalPowerManager.getLowPowerState(
1801 ServiceType.QUICK_DOZE).batterySaverEnabled);
1802
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001803 mLocalActivityTaskManager.registerScreenObserver(mScreenObserver);
Amith Yamasani396a10c2018-01-19 10:58:07 -08001804
Suprabh Shukla5bf49812018-05-24 18:38:50 -07001805 passWhiteListsToForceAppStandbyTrackerLocked();
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -07001806 updateInteractivityLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001807 }
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -07001808 updateConnectivityState(null);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001809 }
1810 }
1811
1812 public boolean addPowerSaveWhitelistAppInternal(String name) {
1813 synchronized (this) {
1814 try {
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001815 ApplicationInfo ai = getContext().getPackageManager().getApplicationInfo(name,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07001816 PackageManager.MATCH_ANY_USER);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001817 if (mPowerSaveWhitelistUserApps.put(name, UserHandle.getAppId(ai.uid)) == null) {
1818 reportPowerSaveWhitelistChangedLocked();
1819 updateWhitelistAppIdsLocked();
1820 writeConfigFileLocked();
1821 }
1822 return true;
1823 } catch (PackageManager.NameNotFoundException e) {
1824 return false;
1825 }
1826 }
1827 }
1828
1829 public boolean removePowerSaveWhitelistAppInternal(String name) {
1830 synchronized (this) {
1831 if (mPowerSaveWhitelistUserApps.remove(name) != null) {
1832 reportPowerSaveWhitelistChangedLocked();
1833 updateWhitelistAppIdsLocked();
1834 writeConfigFileLocked();
1835 return true;
1836 }
1837 }
1838 return false;
1839 }
1840
Felipe Lemef8a46232016-02-10 13:51:54 -08001841 public boolean getPowerSaveWhitelistAppInternal(String name) {
1842 synchronized (this) {
1843 return mPowerSaveWhitelistUserApps.containsKey(name);
1844 }
1845 }
1846
Suprabh Shukla08105642017-09-26 14:45:30 -07001847 void resetSystemPowerWhitelistInternal() {
1848 synchronized (this) {
1849 mPowerSaveWhitelistApps.putAll(mRemovedFromSystemWhitelistApps);
1850 mRemovedFromSystemWhitelistApps.clear();
1851 reportPowerSaveWhitelistChangedLocked();
1852 updateWhitelistAppIdsLocked();
1853 writeConfigFileLocked();
1854 }
1855 }
1856
1857 public boolean restoreSystemPowerWhitelistAppInternal(String name) {
1858 synchronized (this) {
1859 if (!mRemovedFromSystemWhitelistApps.containsKey(name)) {
1860 return false;
1861 }
1862 mPowerSaveWhitelistApps.put(name, mRemovedFromSystemWhitelistApps.remove(name));
1863 reportPowerSaveWhitelistChangedLocked();
1864 updateWhitelistAppIdsLocked();
1865 writeConfigFileLocked();
1866 return true;
1867 }
1868 }
1869
1870 public boolean removeSystemPowerWhitelistAppInternal(String name) {
1871 synchronized (this) {
1872 if (!mPowerSaveWhitelistApps.containsKey(name)) {
1873 return false;
1874 }
1875 mRemovedFromSystemWhitelistApps.put(name, mPowerSaveWhitelistApps.remove(name));
1876 reportPowerSaveWhitelistChangedLocked();
1877 updateWhitelistAppIdsLocked();
1878 writeConfigFileLocked();
1879 return true;
1880 }
1881 }
1882
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07001883 public boolean addPowerSaveWhitelistExceptIdleInternal(String name) {
1884 synchronized (this) {
1885 try {
1886 final ApplicationInfo ai = getContext().getPackageManager().getApplicationInfo(name,
1887 PackageManager.MATCH_ANY_USER);
1888 if (mPowerSaveWhitelistAppsExceptIdle.put(name, UserHandle.getAppId(ai.uid))
1889 == null) {
1890 mPowerSaveWhitelistUserAppsExceptIdle.add(name);
1891 reportPowerSaveWhitelistChangedLocked();
1892 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(
1893 mPowerSaveWhitelistAppsExceptIdle, mPowerSaveWhitelistUserApps,
1894 mPowerSaveWhitelistExceptIdleAppIds);
Makoto Onuki71755c92018-01-16 14:15:44 -08001895
Suprabh Shukla5bf49812018-05-24 18:38:50 -07001896 passWhiteListsToForceAppStandbyTrackerLocked();
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07001897 }
1898 return true;
1899 } catch (PackageManager.NameNotFoundException e) {
1900 return false;
1901 }
1902 }
1903 }
1904
1905 public void resetPowerSaveWhitelistExceptIdleInternal() {
1906 synchronized (this) {
1907 if (mPowerSaveWhitelistAppsExceptIdle.removeAll(
1908 mPowerSaveWhitelistUserAppsExceptIdle)) {
1909 reportPowerSaveWhitelistChangedLocked();
1910 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(
1911 mPowerSaveWhitelistAppsExceptIdle, mPowerSaveWhitelistUserApps,
1912 mPowerSaveWhitelistExceptIdleAppIds);
1913 mPowerSaveWhitelistUserAppsExceptIdle.clear();
Makoto Onuki71755c92018-01-16 14:15:44 -08001914
Suprabh Shukla5bf49812018-05-24 18:38:50 -07001915 passWhiteListsToForceAppStandbyTrackerLocked();
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07001916 }
1917 }
1918 }
1919
1920 public boolean getPowerSaveWhitelistExceptIdleInternal(String name) {
1921 synchronized (this) {
1922 return mPowerSaveWhitelistAppsExceptIdle.containsKey(name);
1923 }
1924 }
1925
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001926 public String[] getSystemPowerWhitelistExceptIdleInternal() {
1927 synchronized (this) {
1928 int size = mPowerSaveWhitelistAppsExceptIdle.size();
1929 String[] apps = new String[size];
1930 for (int i = 0; i < size; i++) {
1931 apps[i] = mPowerSaveWhitelistAppsExceptIdle.keyAt(i);
1932 }
1933 return apps;
1934 }
1935 }
1936
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001937 public String[] getSystemPowerWhitelistInternal() {
1938 synchronized (this) {
1939 int size = mPowerSaveWhitelistApps.size();
1940 String[] apps = new String[size];
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001941 for (int i = 0; i < size; i++) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001942 apps[i] = mPowerSaveWhitelistApps.keyAt(i);
1943 }
1944 return apps;
1945 }
1946 }
1947
Suprabh Shukla08105642017-09-26 14:45:30 -07001948 public String[] getRemovedSystemPowerWhitelistAppsInternal() {
1949 synchronized (this) {
1950 int size = mRemovedFromSystemWhitelistApps.size();
1951 final String[] apps = new String[size];
1952 for (int i = 0; i < size; i++) {
1953 apps[i] = mRemovedFromSystemWhitelistApps.keyAt(i);
1954 }
1955 return apps;
1956 }
1957 }
1958
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001959 public String[] getUserPowerWhitelistInternal() {
1960 synchronized (this) {
1961 int size = mPowerSaveWhitelistUserApps.size();
1962 String[] apps = new String[size];
1963 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1964 apps[i] = mPowerSaveWhitelistUserApps.keyAt(i);
1965 }
1966 return apps;
1967 }
1968 }
1969
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001970 public String[] getFullPowerWhitelistExceptIdleInternal() {
1971 synchronized (this) {
1972 int size = mPowerSaveWhitelistAppsExceptIdle.size() + mPowerSaveWhitelistUserApps.size();
1973 String[] apps = new String[size];
1974 int cur = 0;
1975 for (int i = 0; i < mPowerSaveWhitelistAppsExceptIdle.size(); i++) {
1976 apps[cur] = mPowerSaveWhitelistAppsExceptIdle.keyAt(i);
1977 cur++;
1978 }
1979 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1980 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
1981 cur++;
1982 }
1983 return apps;
1984 }
1985 }
1986
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001987 public String[] getFullPowerWhitelistInternal() {
1988 synchronized (this) {
1989 int size = mPowerSaveWhitelistApps.size() + mPowerSaveWhitelistUserApps.size();
1990 String[] apps = new String[size];
1991 int cur = 0;
1992 for (int i = 0; i < mPowerSaveWhitelistApps.size(); i++) {
1993 apps[cur] = mPowerSaveWhitelistApps.keyAt(i);
1994 cur++;
1995 }
1996 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1997 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
1998 cur++;
1999 }
2000 return apps;
2001 }
2002 }
2003
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002004 public boolean isPowerSaveWhitelistExceptIdleAppInternal(String packageName) {
2005 synchronized (this) {
2006 return mPowerSaveWhitelistAppsExceptIdle.containsKey(packageName)
2007 || mPowerSaveWhitelistUserApps.containsKey(packageName);
2008 }
2009 }
2010
Amith Yamasani06bf8242015-05-08 16:36:21 -07002011 public boolean isPowerSaveWhitelistAppInternal(String packageName) {
2012 synchronized (this) {
2013 return mPowerSaveWhitelistApps.containsKey(packageName)
2014 || mPowerSaveWhitelistUserApps.containsKey(packageName);
2015 }
2016 }
2017
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002018 public int[] getAppIdWhitelistExceptIdleInternal() {
2019 synchronized (this) {
2020 return mPowerSaveWhitelistExceptIdleAppIdArray;
2021 }
2022 }
2023
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002024 public int[] getAppIdWhitelistInternal() {
2025 synchronized (this) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002026 return mPowerSaveWhitelistAllAppIdArray;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002027 }
2028 }
2029
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002030 public int[] getAppIdUserWhitelistInternal() {
2031 synchronized (this) {
2032 return mPowerSaveWhitelistUserAppIdArray;
2033 }
2034 }
2035
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002036 public int[] getAppIdTempWhitelistInternal() {
2037 synchronized (this) {
2038 return mTempWhitelistAppIdArray;
2039 }
2040 }
2041
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002042 void addPowerSaveTempWhitelistAppChecked(String packageName, long duration,
2043 int userId, String reason) throws RemoteException {
2044 getContext().enforceCallingPermission(
2045 Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
2046 "No permission to change device idle whitelist");
2047 final int callingUid = Binder.getCallingUid();
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002048 userId = ActivityManager.getService().handleIncomingUser(
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002049 Binder.getCallingPid(),
2050 callingUid,
2051 userId,
2052 /*allowAll=*/ false,
2053 /*requireFull=*/ false,
2054 "addPowerSaveTempWhitelistApp", null);
2055 final long token = Binder.clearCallingIdentity();
2056 try {
2057 addPowerSaveTempWhitelistAppInternal(callingUid,
2058 packageName, duration, userId, true, reason);
2059 } finally {
2060 Binder.restoreCallingIdentity(token);
2061 }
2062 }
2063
Sudheer Shanka326b3112017-11-27 14:40:57 -08002064 void removePowerSaveTempWhitelistAppChecked(String packageName, int userId)
2065 throws RemoteException {
2066 getContext().enforceCallingPermission(
2067 Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
2068 "No permission to change device idle whitelist");
2069 final int callingUid = Binder.getCallingUid();
2070 userId = ActivityManager.getService().handleIncomingUser(
2071 Binder.getCallingPid(),
2072 callingUid,
2073 userId,
2074 /*allowAll=*/ false,
2075 /*requireFull=*/ false,
2076 "removePowerSaveTempWhitelistApp", null);
2077 final long token = Binder.clearCallingIdentity();
2078 try {
2079 removePowerSaveTempWhitelistAppInternal(packageName, userId);
2080 } finally {
2081 Binder.restoreCallingIdentity(token);
2082 }
2083 }
2084
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002085 /**
2086 * Adds an app to the temporary whitelist and resets the endTime for granting the
2087 * app an exemption to access network and acquire wakelocks.
2088 */
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002089 void addPowerSaveTempWhitelistAppInternal(int callingUid, String packageName,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002090 long duration, int userId, boolean sync, String reason) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002091 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07002092 int uid = getContext().getPackageManager().getPackageUidAsUser(packageName, userId);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002093 int appId = UserHandle.getAppId(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002094 addPowerSaveTempWhitelistAppDirectInternal(callingUid, appId, duration, sync, reason);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002095 } catch (NameNotFoundException e) {
2096 }
2097 }
2098
Dianne Hackborna750a632015-06-16 17:18:23 -07002099 /**
2100 * Adds an app to the temporary whitelist and resets the endTime for granting the
2101 * app an exemption to access network and acquire wakelocks.
2102 */
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002103 void addPowerSaveTempWhitelistAppDirectInternal(int callingUid, int appId,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002104 long duration, boolean sync, String reason) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002105 final long timeNow = SystemClock.elapsedRealtime();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07002106 boolean informWhitelistChanged = false;
Dianne Hackborna750a632015-06-16 17:18:23 -07002107 synchronized (this) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002108 int callingAppId = UserHandle.getAppId(callingUid);
2109 if (callingAppId >= Process.FIRST_APPLICATION_UID) {
2110 if (!mPowerSaveWhitelistSystemAppIds.get(callingAppId)) {
2111 throw new SecurityException("Calling app " + UserHandle.formatUid(callingUid)
2112 + " is not on whitelist");
2113 }
2114 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002115 duration = Math.min(duration, mConstants.MAX_TEMP_APP_WHITELIST_DURATION);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002116 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.get(appId);
2117 final boolean newEntry = entry == null;
Dianne Hackborna750a632015-06-16 17:18:23 -07002118 // Set the new end time
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002119 if (newEntry) {
2120 entry = new Pair<>(new MutableLong(0), reason);
2121 mTempWhitelistAppIdEndTimes.put(appId, entry);
2122 }
2123 entry.first.value = timeNow + duration;
Dianne Hackborna750a632015-06-16 17:18:23 -07002124 if (DEBUG) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002125 Slog.d(TAG, "Adding AppId " + appId + " to temp whitelist. New entry: " + newEntry);
Dianne Hackborna750a632015-06-16 17:18:23 -07002126 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002127 if (newEntry) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002128 // No pending timeout for the app id, post a delayed message
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002129 try {
2130 mBatteryStats.noteEvent(BatteryStats.HistoryItem.EVENT_TEMP_WHITELIST_START,
2131 reason, appId);
2132 } catch (RemoteException e) {
2133 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002134 postTempActiveTimeoutMessage(appId, duration);
Dianne Hackborn85e35642017-01-12 15:10:57 -08002135 updateTempWhitelistAppIdsLocked(appId, true);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07002136 if (sync) {
2137 informWhitelistChanged = true;
2138 } else {
2139 mHandler.obtainMessage(MSG_REPORT_TEMP_APP_WHITELIST_CHANGED, appId, 1)
2140 .sendToTarget();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002141 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002142 reportTempWhitelistChangedLocked();
2143 }
2144 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07002145 if (informWhitelistChanged) {
2146 mNetworkPolicyManagerInternal.onTempPowerSaveWhitelistChange(appId, true);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002147 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002148 }
2149
Sudheer Shanka326b3112017-11-27 14:40:57 -08002150 /**
2151 * Removes an app from the temporary whitelist and notifies the observers.
2152 */
2153 private void removePowerSaveTempWhitelistAppInternal(String packageName, int userId) {
2154 try {
2155 final int uid = getContext().getPackageManager().getPackageUidAsUser(
2156 packageName, userId);
2157 final int appId = UserHandle.getAppId(uid);
2158 removePowerSaveTempWhitelistAppDirectInternal(appId);
2159 } catch (NameNotFoundException e) {
2160 }
2161 }
2162
2163 private void removePowerSaveTempWhitelistAppDirectInternal(int appId) {
2164 synchronized (this) {
2165 final int idx = mTempWhitelistAppIdEndTimes.indexOfKey(appId);
2166 if (idx < 0) {
2167 // Nothing else to do
2168 return;
2169 }
2170 final String reason = mTempWhitelistAppIdEndTimes.valueAt(idx).second;
2171 mTempWhitelistAppIdEndTimes.removeAt(idx);
2172 onAppRemovedFromTempWhitelistLocked(appId, reason);
2173 }
2174 }
2175
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002176 private void postTempActiveTimeoutMessage(int uid, long delay) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002177 if (DEBUG) {
2178 Slog.d(TAG, "postTempActiveTimeoutMessage: uid=" + uid + ", delay=" + delay);
2179 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002180 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_TEMP_APP_WHITELIST_TIMEOUT, uid, 0),
2181 delay);
2182 }
2183
2184 void checkTempAppWhitelistTimeout(int uid) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002185 final long timeNow = SystemClock.elapsedRealtime();
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002186 if (DEBUG) {
2187 Slog.d(TAG, "checkTempAppWhitelistTimeout: uid=" + uid + ", timeNow=" + timeNow);
2188 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002189 synchronized (this) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002190 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.get(uid);
2191 if (entry == null) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002192 // Nothing to do
2193 return;
2194 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002195 if (timeNow >= entry.first.value) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002196 mTempWhitelistAppIdEndTimes.delete(uid);
Sudheer Shanka326b3112017-11-27 14:40:57 -08002197 onAppRemovedFromTempWhitelistLocked(uid, entry.second);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002198 } else {
2199 // Need more time
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002200 if (DEBUG) {
2201 Slog.d(TAG, "Time to remove UID " + uid + ": " + entry.first.value);
2202 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002203 postTempActiveTimeoutMessage(uid, entry.first.value - timeNow);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002204 }
2205 }
2206 }
2207
Sudheer Shanka326b3112017-11-27 14:40:57 -08002208 @GuardedBy("this")
2209 private void onAppRemovedFromTempWhitelistLocked(int appId, String reason) {
2210 if (DEBUG) {
2211 Slog.d(TAG, "Removing appId " + appId + " from temp whitelist");
2212 }
2213 updateTempWhitelistAppIdsLocked(appId, false);
2214 mHandler.obtainMessage(MSG_REPORT_TEMP_APP_WHITELIST_CHANGED, appId, 0)
2215 .sendToTarget();
2216 reportTempWhitelistChangedLocked();
2217 try {
2218 mBatteryStats.noteEvent(BatteryStats.HistoryItem.EVENT_TEMP_WHITELIST_FINISH,
2219 reason, appId);
2220 } catch (RemoteException e) {
2221 }
2222 }
2223
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002224 public void exitIdleInternal(String reason) {
2225 synchronized (this) {
2226 becomeActiveLocked(reason, Binder.getCallingUid());
2227 }
2228 }
2229
Kweku Adams799858b2018-10-08 17:19:08 -07002230 @VisibleForTesting
2231 boolean isNetworkConnected() {
2232 synchronized (this) {
2233 return mNetworkConnected;
2234 }
2235 }
2236
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -07002237 void updateConnectivityState(Intent connIntent) {
2238 ConnectivityService cm;
2239 synchronized (this) {
Kweku Adams799858b2018-10-08 17:19:08 -07002240 cm = mInjector.getConnectivityService();
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -07002241 }
2242 if (cm == null) {
2243 return;
2244 }
2245 // Note: can't call out to ConnectivityService with our lock held.
2246 NetworkInfo ni = cm.getActiveNetworkInfo();
2247 synchronized (this) {
Dianne Hackborn88c41352016-04-07 15:18:58 -07002248 boolean conn;
2249 if (ni == null) {
2250 conn = false;
2251 } else {
2252 if (connIntent == null) {
2253 conn = ni.isConnected();
2254 } else {
2255 final int networkType =
2256 connIntent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
2257 ConnectivityManager.TYPE_NONE);
2258 if (ni.getType() != networkType) {
2259 return;
2260 }
2261 conn = !connIntent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,
2262 false);
2263 }
2264 }
2265 if (conn != mNetworkConnected) {
2266 mNetworkConnected = conn;
2267 if (conn && mLightState == LIGHT_STATE_WAITING_FOR_NETWORK) {
2268 stepLightIdleStateLocked("network");
2269 }
2270 }
2271 }
2272 }
2273
Kweku Adams00e3a372018-09-28 16:57:09 -07002274 @VisibleForTesting
2275 boolean isScreenOn() {
Kweku Adamsb396ccf2018-09-17 16:37:15 -07002276 synchronized (this) {
2277 return mScreenOn;
2278 }
Kweku Adams00e3a372018-09-28 16:57:09 -07002279 }
2280
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -07002281 void updateInteractivityLocked() {
2282 // The interactivity state from the power manager tells us whether the display is
2283 // in a state that we need to keep things running so they will update at a normal
2284 // frequency.
2285 boolean screenOn = mPowerManager.isInteractive();
2286 if (DEBUG) Slog.d(TAG, "updateInteractivityLocked: screenOn=" + screenOn);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002287 if (!screenOn && mScreenOn) {
2288 mScreenOn = false;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002289 if (!mForceIdle) {
2290 becomeInactiveIfAppropriateLocked();
2291 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002292 } else if (screenOn) {
2293 mScreenOn = true;
Amith Yamasani396a10c2018-01-19 10:58:07 -08002294 if (!mForceIdle && (!mScreenLocked || !mConstants.WAIT_FOR_UNLOCK)) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002295 becomeActiveLocked("screen", Process.myUid());
2296 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002297 }
2298 }
2299
Kweku Adams00e3a372018-09-28 16:57:09 -07002300 @VisibleForTesting
2301 boolean isCharging() {
Kweku Adamsb396ccf2018-09-17 16:37:15 -07002302 synchronized (this) {
2303 return mCharging;
2304 }
Kweku Adams00e3a372018-09-28 16:57:09 -07002305 }
2306
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002307 void updateChargingLocked(boolean charging) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002308 if (DEBUG) Slog.i(TAG, "updateChargingLocked: charging=" + charging);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002309 if (!charging && mCharging) {
2310 mCharging = false;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002311 if (!mForceIdle) {
2312 becomeInactiveIfAppropriateLocked();
2313 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002314 } else if (charging) {
2315 mCharging = charging;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002316 if (!mForceIdle) {
2317 becomeActiveLocked("charging", Process.myUid());
2318 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002319 }
2320 }
2321
Kweku Adamsb396ccf2018-09-17 16:37:15 -07002322 @VisibleForTesting
2323 boolean isQuickDozeEnabled() {
2324 synchronized (this) {
2325 return mQuickDozeActivated;
2326 }
2327 }
2328
2329 /** Updates the quick doze flag and enters deep doze if appropriate. */
2330 @VisibleForTesting
2331 void updateQuickDozeFlagLocked(boolean enabled) {
2332 if (DEBUG) Slog.i(TAG, "updateQuickDozeFlagLocked: enabled=" + enabled);
2333 mQuickDozeActivated = enabled;
2334 if (enabled) {
2335 // If Quick Doze is enabled, see if we should go straight into it.
2336 becomeInactiveIfAppropriateLocked();
2337 }
2338 // Going from Deep Doze to Light Idle (if quick doze becomes disabled) is tricky and
2339 // probably not worth the overhead, so leave in deep doze if that's the case until the
2340 // next natural time to come out of it.
2341 }
2342
Amith Yamasani396a10c2018-01-19 10:58:07 -08002343 void keyguardShowingLocked(boolean showing) {
2344 if (DEBUG) Slog.i(TAG, "keyguardShowing=" + showing);
2345 if (mScreenLocked != showing) {
2346 mScreenLocked = showing;
2347 if (mScreenOn && !mForceIdle && !mScreenLocked) {
2348 becomeActiveLocked("unlocked", Process.myUid());
2349 }
2350 }
2351 }
2352
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002353 void scheduleReportActiveLocked(String activeReason, int activeUid) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002354 Message msg = mHandler.obtainMessage(MSG_REPORT_ACTIVE, activeUid, 0, activeReason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002355 mHandler.sendMessage(msg);
2356 }
2357
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002358 void becomeActiveLocked(String activeReason, int activeUid) {
2359 if (DEBUG) Slog.i(TAG, "becomeActiveLocked, reason = " + activeReason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002360 if (mState != STATE_ACTIVE || mLightState != STATE_ACTIVE) {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002361 EventLogTags.writeDeviceIdle(STATE_ACTIVE, activeReason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002362 EventLogTags.writeDeviceIdleLight(LIGHT_STATE_ACTIVE, activeReason);
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002363 scheduleReportActiveLocked(activeReason, activeUid);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002364 mState = STATE_ACTIVE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002365 mLightState = LIGHT_STATE_ACTIVE;
Adam Lesinski31c05d12015-06-09 17:34:04 -07002366 mInactiveTimeout = mConstants.INACTIVE_TIMEOUT;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002367 mCurIdleBudget = 0;
2368 mMaintenanceStartTime = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002369 resetIdleManagementLocked();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002370 resetLightIdleManagementLocked();
Amith Yamasaniac6517a2018-04-23 12:19:34 -07002371 addEvent(EVENT_NORMAL, activeReason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002372 }
2373 }
2374
Kweku Adams00e3a372018-09-28 16:57:09 -07002375 /** Must only be used in tests. */
2376 @VisibleForTesting
2377 void setDeepEnabledForTest(boolean enabled) {
Kweku Adams799858b2018-10-08 17:19:08 -07002378 synchronized (this) {
2379 mDeepEnabled = enabled;
2380 }
Kweku Adams00e3a372018-09-28 16:57:09 -07002381 }
2382
2383 /** Must only be used in tests. */
2384 @VisibleForTesting
2385 void setLightEnabledForTest(boolean enabled) {
Kweku Adams799858b2018-10-08 17:19:08 -07002386 synchronized (this) {
2387 mLightEnabled = enabled;
2388 }
Kweku Adams00e3a372018-09-28 16:57:09 -07002389 }
2390
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002391 void becomeInactiveIfAppropriateLocked() {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002392 if (DEBUG) Slog.d(TAG, "becomeInactiveIfAppropriateLocked()");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002393 if ((!mScreenOn && !mCharging) || mForceIdle) {
Kweku Adamsb396ccf2018-09-17 16:37:15 -07002394 // Become inactive and determine if we will ultimately go idle.
2395 if (mDeepEnabled) {
2396 if (mQuickDozeActivated) {
2397 if (mState == STATE_QUICK_DOZE_DELAY || mState == STATE_IDLE
2398 || mState == STATE_IDLE_MAINTENANCE) {
2399 // Already "idling". Don't want to restart the process.
2400 // mLightState can't be LIGHT_STATE_ACTIVE if mState is any of these 3
2401 // values, so returning here is safe.
2402 return;
2403 }
2404 if (DEBUG) {
2405 Slog.d(TAG, "Moved from "
2406 + stateToString(mState) + " to STATE_QUICK_DOZE_DELAY");
2407 }
2408 mState = STATE_QUICK_DOZE_DELAY;
2409 // Make sure any motion sensing or locating is stopped.
2410 resetIdleManagementLocked();
2411 // Wait a small amount of time in case something (eg: background service from
2412 // recently closed app) needs to finish running.
2413 scheduleAlarmLocked(mConstants.QUICK_DOZE_DELAY_TIMEOUT, false);
2414 EventLogTags.writeDeviceIdle(mState, "no activity");
2415 } else if (mState == STATE_ACTIVE) {
2416 mState = STATE_INACTIVE;
2417 if (DEBUG) Slog.d(TAG, "Moved from STATE_ACTIVE to STATE_INACTIVE");
2418 resetIdleManagementLocked();
2419 scheduleAlarmLocked(mInactiveTimeout, false);
2420 EventLogTags.writeDeviceIdle(mState, "no activity");
2421 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002422 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08002423 if (mLightState == LIGHT_STATE_ACTIVE && mLightEnabled) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002424 mLightState = LIGHT_STATE_INACTIVE;
2425 if (DEBUG) Slog.d(TAG, "Moved from LIGHT_STATE_ACTIVE to LIGHT_STATE_INACTIVE");
2426 resetLightIdleManagementLocked();
Dianne Hackborn953fc942016-03-29 15:36:24 -07002427 scheduleLightAlarmLocked(mConstants.LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002428 EventLogTags.writeDeviceIdleLight(mLightState, "no activity");
2429 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002430 }
2431 }
2432
Kweku Adams00e3a372018-09-28 16:57:09 -07002433 private void resetIdleManagementLocked() {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002434 mNextIdlePendingDelay = 0;
2435 mNextIdleDelay = 0;
Dianne Hackborn953fc942016-03-29 15:36:24 -07002436 mNextLightIdleDelay = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002437 cancelAlarmLocked();
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002438 cancelSensingTimeoutAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002439 cancelLocatingLocked();
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002440 stopMonitoringMotionLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002441 mAnyMotionDetector.stop();
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002442 }
2443
Kweku Adams00e3a372018-09-28 16:57:09 -07002444 private void resetLightIdleManagementLocked() {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002445 cancelLightAlarmLocked();
2446 }
2447
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002448 void exitForceIdleLocked() {
2449 if (mForceIdle) {
2450 mForceIdle = false;
2451 if (mScreenOn || mCharging) {
Dianne Hackborn88c41352016-04-07 15:18:58 -07002452 becomeActiveLocked("exit-force", Process.myUid());
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002453 }
2454 }
2455 }
2456
Kweku Adamsa457f4e2018-10-03 15:56:06 -07002457 /**
2458 * Must only be used in tests.
2459 *
2460 * This sets the state value directly and thus doesn't trigger any behavioral changes.
2461 */
2462 @VisibleForTesting
2463 void setLightStateForTest(int lightState) {
Kweku Adams799858b2018-10-08 17:19:08 -07002464 synchronized (this) {
2465 mLightState = lightState;
2466 }
Kweku Adamsa457f4e2018-10-03 15:56:06 -07002467 }
2468
Kweku Adams00e3a372018-09-28 16:57:09 -07002469 @VisibleForTesting
2470 int getLightState() {
2471 return mLightState;
2472 }
2473
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002474 void stepLightIdleStateLocked(String reason) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002475 if (mLightState == LIGHT_STATE_OVERRIDE) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002476 // If we are already in deep device idle mode, then
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002477 // there is nothing left to do for light mode.
2478 return;
2479 }
2480
2481 if (DEBUG) Slog.d(TAG, "stepLightIdleStateLocked: mLightState=" + mLightState);
2482 EventLogTags.writeDeviceIdleLightStep();
2483
2484 switch (mLightState) {
2485 case LIGHT_STATE_INACTIVE:
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002486 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
Dianne Hackborn953fc942016-03-29 15:36:24 -07002487 // Reset the upcoming idle delays.
2488 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002489 mMaintenanceStartTime = 0;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002490 if (!isOpsInactiveLocked()) {
2491 // We have some active ops going on... give them a chance to finish
2492 // before going in to our first idle.
2493 mLightState = LIGHT_STATE_PRE_IDLE;
2494 EventLogTags.writeDeviceIdleLight(mLightState, reason);
2495 scheduleLightAlarmLocked(mConstants.LIGHT_PRE_IDLE_TIMEOUT);
2496 break;
2497 }
2498 // Nothing active, fall through to immediately idle.
2499 case LIGHT_STATE_PRE_IDLE:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002500 case LIGHT_STATE_IDLE_MAINTENANCE:
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002501 if (mMaintenanceStartTime != 0) {
2502 long duration = SystemClock.elapsedRealtime() - mMaintenanceStartTime;
2503 if (duration < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
2504 // We didn't use up all of our minimum budget; add this to the reserve.
2505 mCurIdleBudget += (mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET-duration);
2506 } else {
2507 // We used more than our minimum budget; this comes out of the reserve.
2508 mCurIdleBudget -= (duration-mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET);
2509 }
2510 }
2511 mMaintenanceStartTime = 0;
Dianne Hackborn953fc942016-03-29 15:36:24 -07002512 scheduleLightAlarmLocked(mNextLightIdleDelay);
2513 mNextLightIdleDelay = Math.min(mConstants.LIGHT_MAX_IDLE_TIMEOUT,
2514 (long)(mNextLightIdleDelay * mConstants.LIGHT_IDLE_FACTOR));
2515 if (mNextLightIdleDelay < mConstants.LIGHT_IDLE_TIMEOUT) {
2516 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
2517 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002518 if (DEBUG) Slog.d(TAG, "Moved to LIGHT_STATE_IDLE.");
2519 mLightState = LIGHT_STATE_IDLE;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002520 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Amith Yamasaniac6517a2018-04-23 12:19:34 -07002521 addEvent(EVENT_LIGHT_IDLE, null);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08002522 mGoingIdleWakeLock.acquire();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002523 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON_LIGHT);
2524 break;
2525 case LIGHT_STATE_IDLE:
Dianne Hackborn88c41352016-04-07 15:18:58 -07002526 case LIGHT_STATE_WAITING_FOR_NETWORK:
2527 if (mNetworkConnected || mLightState == LIGHT_STATE_WAITING_FOR_NETWORK) {
2528 // We have been idling long enough, now it is time to do some work.
2529 mActiveIdleOpCount = 1;
2530 mActiveIdleWakeLock.acquire();
2531 mMaintenanceStartTime = SystemClock.elapsedRealtime();
2532 if (mCurIdleBudget < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
2533 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
2534 } else if (mCurIdleBudget > mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET) {
2535 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET;
2536 }
2537 scheduleLightAlarmLocked(mCurIdleBudget);
2538 if (DEBUG) Slog.d(TAG,
2539 "Moved from LIGHT_STATE_IDLE to LIGHT_STATE_IDLE_MAINTENANCE.");
2540 mLightState = LIGHT_STATE_IDLE_MAINTENANCE;
2541 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Amith Yamasaniac6517a2018-04-23 12:19:34 -07002542 addEvent(EVENT_LIGHT_MAINTENANCE, null);
Dianne Hackborn88c41352016-04-07 15:18:58 -07002543 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
2544 } else {
2545 // We'd like to do maintenance, but currently don't have network
2546 // connectivity... let's try to wait until the network comes back.
2547 // We'll only wait for another full idle period, however, and then give up.
2548 scheduleLightAlarmLocked(mNextLightIdleDelay);
2549 if (DEBUG) Slog.d(TAG, "Moved to LIGHT_WAITING_FOR_NETWORK.");
2550 mLightState = LIGHT_STATE_WAITING_FOR_NETWORK;
2551 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002552 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002553 break;
2554 }
2555 }
2556
Kweku Adams00e3a372018-09-28 16:57:09 -07002557 @VisibleForTesting
2558 int getState() {
2559 return mState;
2560 }
2561
2562 @VisibleForTesting
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002563 void stepIdleStateLocked(String reason) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002564 if (DEBUG) Slog.d(TAG, "stepIdleStateLocked: mState=" + mState);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002565 EventLogTags.writeDeviceIdleStep();
2566
2567 final long now = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07002568 if ((now+mConstants.MIN_TIME_TO_ALARM) > mAlarmManager.getNextWakeFromIdleTime()) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002569 // Whoops, there is an upcoming alarm. We don't actually want to go idle.
2570 if (mState != STATE_ACTIVE) {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002571 becomeActiveLocked("alarm", Process.myUid());
Koji Fukui27b33302015-12-16 19:43:01 +09002572 becomeInactiveIfAppropriateLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002573 }
2574 return;
2575 }
2576
2577 switch (mState) {
2578 case STATE_INACTIVE:
2579 // We have now been inactive long enough, it is time to start looking
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002580 // for motion and sleep some more while doing so.
2581 startMonitoringMotionLocked();
Adam Lesinski31c05d12015-06-09 17:34:04 -07002582 scheduleAlarmLocked(mConstants.IDLE_AFTER_INACTIVE_TIMEOUT, false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002583 mState = STATE_IDLE_PENDING;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002584 if (DEBUG) Slog.d(TAG, "Moved from STATE_INACTIVE to STATE_IDLE_PENDING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002585 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002586 break;
2587 case STATE_IDLE_PENDING:
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002588 mState = STATE_SENSING;
2589 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE_PENDING to STATE_SENSING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002590 EventLogTags.writeDeviceIdle(mState, reason);
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002591 scheduleSensingTimeoutAlarmLocked(mConstants.SENSING_TIMEOUT);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002592 cancelLocatingLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002593 mNotMoving = false;
2594 mLocated = false;
2595 mLastGenericLocation = null;
2596 mLastGpsLocation = null;
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002597 mAnyMotionDetector.checkForAnyMotion();
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002598 break;
2599 case STATE_SENSING:
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002600 cancelSensingTimeoutAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002601 mState = STATE_LOCATING;
2602 if (DEBUG) Slog.d(TAG, "Moved from STATE_SENSING to STATE_LOCATING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002603 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002604 scheduleAlarmLocked(mConstants.LOCATING_TIMEOUT, false);
Kweku Adams799858b2018-10-08 17:19:08 -07002605 LocationManager locationManager = mInjector.getLocationManager();
2606 if (locationManager != null
2607 && locationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
2608 locationManager.requestLocationUpdates(mLocationRequest,
Joe LaPenna23d681b2015-08-27 15:12:11 -07002609 mGenericLocationListener, mHandler.getLooper());
2610 mLocating = true;
2611 } else {
2612 mHasNetworkLocation = false;
2613 }
Kweku Adams799858b2018-10-08 17:19:08 -07002614 if (locationManager != null
2615 && locationManager.getProvider(LocationManager.GPS_PROVIDER) != null) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07002616 mHasGps = true;
Kweku Adams799858b2018-10-08 17:19:08 -07002617 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 5,
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002618 mGpsLocationListener, mHandler.getLooper());
Joe LaPenna23d681b2015-08-27 15:12:11 -07002619 mLocating = true;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002620 } else {
Joe LaPenna23d681b2015-08-27 15:12:11 -07002621 mHasGps = false;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002622 }
Joe LaPenna23d681b2015-08-27 15:12:11 -07002623 // If we have a location provider, we're all set, the listeners will move state
2624 // forward.
2625 if (mLocating) {
2626 break;
2627 }
2628
2629 // Otherwise, we have to move from locating into idle maintenance.
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002630 case STATE_LOCATING:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002631 cancelAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002632 cancelLocatingLocked();
2633 mAnyMotionDetector.stop();
Dianne Hackborn953fc942016-03-29 15:36:24 -07002634
Kweku Adamsb396ccf2018-09-17 16:37:15 -07002635 // Intentional fallthrough -- time to go into IDLE state.
2636 case STATE_QUICK_DOZE_DELAY:
2637 // Reset the upcoming idle delays.
2638 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
2639 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
2640
2641 // Everything is in place to go into IDLE state.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002642 case STATE_IDLE_MAINTENANCE:
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002643 scheduleAlarmLocked(mNextIdleDelay, true);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002644 if (DEBUG) Slog.d(TAG, "Moved to STATE_IDLE. Next alarm in " + mNextIdleDelay +
2645 " ms.");
Adam Lesinski31c05d12015-06-09 17:34:04 -07002646 mNextIdleDelay = (long)(mNextIdleDelay * mConstants.IDLE_FACTOR);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002647 if (DEBUG) Slog.d(TAG, "Setting mNextIdleDelay = " + mNextIdleDelay);
Adam Lesinski31c05d12015-06-09 17:34:04 -07002648 mNextIdleDelay = Math.min(mNextIdleDelay, mConstants.MAX_IDLE_TIMEOUT);
Dianne Hackborn953fc942016-03-29 15:36:24 -07002649 if (mNextIdleDelay < mConstants.IDLE_TIMEOUT) {
2650 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
2651 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002652 mState = STATE_IDLE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002653 if (mLightState != LIGHT_STATE_OVERRIDE) {
2654 mLightState = LIGHT_STATE_OVERRIDE;
2655 cancelLightAlarmLocked();
2656 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002657 EventLogTags.writeDeviceIdle(mState, reason);
Amith Yamasaniac6517a2018-04-23 12:19:34 -07002658 addEvent(EVENT_DEEP_IDLE, null);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08002659 mGoingIdleWakeLock.acquire();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002660 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON);
2661 break;
2662 case STATE_IDLE:
2663 // We have been idling long enough, now it is time to do some work.
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002664 mActiveIdleOpCount = 1;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002665 mActiveIdleWakeLock.acquire();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002666 scheduleAlarmLocked(mNextIdlePendingDelay, false);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002667 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE to STATE_IDLE_MAINTENANCE. " +
2668 "Next alarm in " + mNextIdlePendingDelay + " ms.");
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002669 mMaintenanceStartTime = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07002670 mNextIdlePendingDelay = Math.min(mConstants.MAX_IDLE_PENDING_TIMEOUT,
2671 (long)(mNextIdlePendingDelay * mConstants.IDLE_PENDING_FACTOR));
Dianne Hackborn953fc942016-03-29 15:36:24 -07002672 if (mNextIdlePendingDelay < mConstants.IDLE_PENDING_TIMEOUT) {
2673 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
2674 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002675 mState = STATE_IDLE_MAINTENANCE;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002676 EventLogTags.writeDeviceIdle(mState, reason);
Amith Yamasaniac6517a2018-04-23 12:19:34 -07002677 addEvent(EVENT_DEEP_MAINTENANCE, null);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002678 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
2679 break;
2680 }
2681 }
2682
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002683 void incActiveIdleOps() {
2684 synchronized (this) {
2685 mActiveIdleOpCount++;
2686 }
2687 }
2688
2689 void decActiveIdleOps() {
2690 synchronized (this) {
2691 mActiveIdleOpCount--;
2692 if (mActiveIdleOpCount <= 0) {
2693 exitMaintenanceEarlyIfNeededLocked();
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002694 mActiveIdleWakeLock.release();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002695 }
2696 }
2697 }
2698
Kweku Adamsa457f4e2018-10-03 15:56:06 -07002699 /** Must only be used in tests. */
2700 @VisibleForTesting
2701 void setActiveIdleOpsForTest(int count) {
Kweku Adams799858b2018-10-08 17:19:08 -07002702 synchronized (this) {
2703 mActiveIdleOpCount = count;
2704 }
Kweku Adamsa457f4e2018-10-03 15:56:06 -07002705 }
2706
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002707 void setJobsActive(boolean active) {
2708 synchronized (this) {
2709 mJobsActive = active;
Yao Chenca5edbb2016-01-13 14:44:36 -08002710 reportMaintenanceActivityIfNeededLocked();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002711 if (!active) {
2712 exitMaintenanceEarlyIfNeededLocked();
2713 }
2714 }
2715 }
2716
2717 void setAlarmsActive(boolean active) {
2718 synchronized (this) {
2719 mAlarmsActive = active;
2720 if (!active) {
2721 exitMaintenanceEarlyIfNeededLocked();
2722 }
2723 }
2724 }
2725
Yao Chenca5edbb2016-01-13 14:44:36 -08002726 boolean registerMaintenanceActivityListener(IMaintenanceActivityListener listener) {
2727 synchronized (this) {
2728 mMaintenanceActivityListeners.register(listener);
2729 return mReportedMaintenanceActivity;
2730 }
2731 }
2732
2733 void unregisterMaintenanceActivityListener(IMaintenanceActivityListener listener) {
2734 synchronized (this) {
2735 mMaintenanceActivityListeners.unregister(listener);
2736 }
2737 }
2738
2739 void reportMaintenanceActivityIfNeededLocked() {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07002740 boolean active = mJobsActive;
Yao Chenca5edbb2016-01-13 14:44:36 -08002741 if (active == mReportedMaintenanceActivity) {
2742 return;
2743 }
2744 mReportedMaintenanceActivity = active;
2745 Message msg = mHandler.obtainMessage(MSG_REPORT_MAINTENANCE_ACTIVITY,
2746 mReportedMaintenanceActivity ? 1 : 0, 0);
2747 mHandler.sendMessage(msg);
2748 }
2749
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002750 boolean isOpsInactiveLocked() {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07002751 return mActiveIdleOpCount <= 0 && !mJobsActive && !mAlarmsActive;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002752 }
2753
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002754 void exitMaintenanceEarlyIfNeededLocked() {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002755 if (mState == STATE_IDLE_MAINTENANCE || mLightState == LIGHT_STATE_IDLE_MAINTENANCE
2756 || mLightState == LIGHT_STATE_PRE_IDLE) {
2757 if (isOpsInactiveLocked()) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002758 final long now = SystemClock.elapsedRealtime();
2759 if (DEBUG) {
2760 StringBuilder sb = new StringBuilder();
2761 sb.append("Exit: start=");
2762 TimeUtils.formatDuration(mMaintenanceStartTime, sb);
2763 sb.append(" now=");
2764 TimeUtils.formatDuration(now, sb);
2765 Slog.d(TAG, sb.toString());
2766 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002767 if (mState == STATE_IDLE_MAINTENANCE) {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002768 stepIdleStateLocked("s:early");
2769 } else if (mLightState == LIGHT_STATE_PRE_IDLE) {
2770 stepLightIdleStateLocked("s:predone");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002771 } else {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002772 stepLightIdleStateLocked("s:early");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002773 }
2774 }
2775 }
2776 }
2777
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002778 void motionLocked() {
2779 if (DEBUG) Slog.d(TAG, "motionLocked()");
2780 // The motion sensor will have been disabled at this point
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002781 handleMotionDetectedLocked(mConstants.MOTION_INACTIVE_TIMEOUT, "motion");
2782 }
2783
2784 void handleMotionDetectedLocked(long timeout, String type) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002785 // The device is not yet active, so we want to go back to the pending idle
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002786 // state to wait again for no motion. Note that we only monitor for motion
2787 // after moving out of the inactive state, so no need to worry about that.
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002788 boolean becomeInactive = false;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002789 if (mState != STATE_ACTIVE) {
Amith Yamasani4cb42572018-04-27 10:02:57 -07002790 // Motion shouldn't affect light state, if it's already in doze-light or maintenance
2791 boolean lightIdle = mLightState == LIGHT_STATE_IDLE
2792 || mLightState == LIGHT_STATE_WAITING_FOR_NETWORK
2793 || mLightState == LIGHT_STATE_IDLE_MAINTENANCE;
2794 if (!lightIdle) {
2795 // Only switch to active state if we're not in either idle state
2796 scheduleReportActiveLocked(type, Process.myUid());
2797 addEvent(EVENT_NORMAL, type);
2798 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002799 mState = STATE_ACTIVE;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002800 mInactiveTimeout = timeout;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002801 mCurIdleBudget = 0;
2802 mMaintenanceStartTime = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002803 EventLogTags.writeDeviceIdle(mState, type);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002804 becomeInactive = true;
2805 }
2806 if (mLightState == LIGHT_STATE_OVERRIDE) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002807 // We went out of light idle mode because we had started deep idle mode... let's
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002808 // now go back and reset things so we resume light idling if appropriate.
Amith Yamasani4cb42572018-04-27 10:02:57 -07002809 mLightState = LIGHT_STATE_ACTIVE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002810 EventLogTags.writeDeviceIdleLight(mLightState, type);
2811 becomeInactive = true;
2812 }
2813 if (becomeInactive) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002814 becomeInactiveIfAppropriateLocked();
2815 }
2816 }
2817
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002818 void receivedGenericLocationLocked(Location location) {
2819 if (mState != STATE_LOCATING) {
2820 cancelLocatingLocked();
2821 return;
2822 }
2823 if (DEBUG) Slog.d(TAG, "Generic location: " + location);
2824 mLastGenericLocation = new Location(location);
Joe LaPenna23d681b2015-08-27 15:12:11 -07002825 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY && mHasGps) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002826 return;
2827 }
2828 mLocated = true;
2829 if (mNotMoving) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002830 stepIdleStateLocked("s:location");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002831 }
2832 }
2833
2834 void receivedGpsLocationLocked(Location location) {
2835 if (mState != STATE_LOCATING) {
2836 cancelLocatingLocked();
2837 return;
2838 }
2839 if (DEBUG) Slog.d(TAG, "GPS location: " + location);
2840 mLastGpsLocation = new Location(location);
2841 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY) {
2842 return;
2843 }
2844 mLocated = true;
2845 if (mNotMoving) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002846 stepIdleStateLocked("s:gps");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002847 }
2848 }
2849
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002850 void startMonitoringMotionLocked() {
2851 if (DEBUG) Slog.d(TAG, "startMonitoringMotionLocked()");
2852 if (mMotionSensor != null && !mMotionListener.active) {
2853 mMotionListener.registerLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002854 }
2855 }
2856
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002857 void stopMonitoringMotionLocked() {
2858 if (DEBUG) Slog.d(TAG, "stopMonitoringMotionLocked()");
2859 if (mMotionSensor != null && mMotionListener.active) {
2860 mMotionListener.unregisterLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002861 }
2862 }
2863
2864 void cancelAlarmLocked() {
2865 if (mNextAlarmTime != 0) {
2866 mNextAlarmTime = 0;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002867 mAlarmManager.cancel(mDeepAlarmListener);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002868 }
2869 }
2870
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002871 void cancelLightAlarmLocked() {
2872 if (mNextLightAlarmTime != 0) {
2873 mNextLightAlarmTime = 0;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002874 mAlarmManager.cancel(mLightAlarmListener);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002875 }
2876 }
2877
2878 void cancelLocatingLocked() {
2879 if (mLocating) {
Kweku Adams799858b2018-10-08 17:19:08 -07002880 LocationManager locationManager = mInjector.getLocationManager();
2881 locationManager.removeUpdates(mGenericLocationListener);
2882 locationManager.removeUpdates(mGpsLocationListener);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002883 mLocating = false;
2884 }
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002885 }
2886
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002887 void cancelSensingTimeoutAlarmLocked() {
2888 if (mNextSensingTimeoutAlarmTime != 0) {
2889 mNextSensingTimeoutAlarmTime = 0;
2890 mAlarmManager.cancel(mSensingTimeoutAlarmListener);
2891 }
2892 }
2893
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002894 void scheduleAlarmLocked(long delay, boolean idleUntil) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002895 if (DEBUG) Slog.d(TAG, "scheduleAlarmLocked(" + delay + ", " + idleUntil + ")");
Kweku Adamsb396ccf2018-09-17 16:37:15 -07002896 if (mMotionSensor == null && !(mState == STATE_QUICK_DOZE_DELAY || mState == STATE_IDLE
2897 || mState == STATE_IDLE_MAINTENANCE)) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07002898 // If there is no motion sensor on this device, then we won't schedule
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002899 // alarms, because we can't determine if the device is not moving. This effectively
Joe LaPenna23d681b2015-08-27 15:12:11 -07002900 // turns off normal execution of device idling, although it is still possible to
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002901 // manually poke it by pretending like the alarm is going off.
Kweku Adamsb396ccf2018-09-17 16:37:15 -07002902 // STATE_QUICK_DOZE_DELAY skips the motion sensing so if the state is past the motion
2903 // sensing stage (ie, is QUICK_DOZE_DELAY, IDLE, or IDLE_MAINTENANCE), then idling
2904 // can continue until the user interacts with the device.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002905 return;
2906 }
2907 mNextAlarmTime = SystemClock.elapsedRealtime() + delay;
2908 if (idleUntil) {
2909 mAlarmManager.setIdleUntil(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002910 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002911 } else {
2912 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002913 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002914 }
2915 }
2916
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002917 void scheduleLightAlarmLocked(long delay) {
2918 if (DEBUG) Slog.d(TAG, "scheduleLightAlarmLocked(" + delay + ")");
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002919 mNextLightAlarmTime = SystemClock.elapsedRealtime() + delay;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002920 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002921 mNextLightAlarmTime, "DeviceIdleController.light", mLightAlarmListener, mHandler);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002922 }
2923
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002924 void scheduleSensingTimeoutAlarmLocked(long delay) {
2925 if (DEBUG) Slog.d(TAG, "scheduleSensingAlarmLocked(" + delay + ")");
2926 mNextSensingTimeoutAlarmTime = SystemClock.elapsedRealtime() + delay;
2927 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, mNextSensingTimeoutAlarmTime,
2928 "DeviceIdleController.sensing", mSensingTimeoutAlarmListener, mHandler);
2929 }
2930
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002931 private static int[] buildAppIdArray(ArrayMap<String, Integer> systemApps,
2932 ArrayMap<String, Integer> userApps, SparseBooleanArray outAppIds) {
2933 outAppIds.clear();
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002934 if (systemApps != null) {
2935 for (int i = 0; i < systemApps.size(); i++) {
2936 outAppIds.put(systemApps.valueAt(i), true);
2937 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002938 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002939 if (userApps != null) {
2940 for (int i = 0; i < userApps.size(); i++) {
2941 outAppIds.put(userApps.valueAt(i), true);
2942 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002943 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002944 int size = outAppIds.size();
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002945 int[] appids = new int[size];
2946 for (int i = 0; i < size; i++) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002947 appids[i] = outAppIds.keyAt(i);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002948 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002949 return appids;
2950 }
2951
2952 private void updateWhitelistAppIdsLocked() {
2953 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(mPowerSaveWhitelistAppsExceptIdle,
2954 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistExceptIdleAppIds);
2955 mPowerSaveWhitelistAllAppIdArray = buildAppIdArray(mPowerSaveWhitelistApps,
2956 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistAllAppIds);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002957 mPowerSaveWhitelistUserAppIdArray = buildAppIdArray(null,
2958 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistUserAppIds);
Dianne Hackborn85e35642017-01-12 15:10:57 -08002959 if (mLocalActivityManager != null) {
Makoto Onukiaf8ff4f2018-06-04 14:44:19 -07002960 mLocalActivityManager.setDeviceIdleWhitelist(
2961 mPowerSaveWhitelistAllAppIdArray, mPowerSaveWhitelistExceptIdleAppIdArray);
Dianne Hackborn85e35642017-01-12 15:10:57 -08002962 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002963 if (mLocalPowerManager != null) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002964 if (DEBUG) {
2965 Slog.d(TAG, "Setting wakelock whitelist to "
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002966 + Arrays.toString(mPowerSaveWhitelistAllAppIdArray));
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002967 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002968 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002969 }
Suprabh Shukla5bf49812018-05-24 18:38:50 -07002970 passWhiteListsToForceAppStandbyTrackerLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002971 }
2972
Dianne Hackborn85e35642017-01-12 15:10:57 -08002973 private void updateTempWhitelistAppIdsLocked(int appId, boolean adding) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002974 final int size = mTempWhitelistAppIdEndTimes.size();
2975 if (mTempWhitelistAppIdArray.length != size) {
2976 mTempWhitelistAppIdArray = new int[size];
2977 }
2978 for (int i = 0; i < size; i++) {
2979 mTempWhitelistAppIdArray[i] = mTempWhitelistAppIdEndTimes.keyAt(i);
2980 }
Dianne Hackborn85e35642017-01-12 15:10:57 -08002981 if (mLocalActivityManager != null) {
2982 if (DEBUG) {
2983 Slog.d(TAG, "Setting activity manager temp whitelist to "
2984 + Arrays.toString(mTempWhitelistAppIdArray));
2985 }
2986 mLocalActivityManager.updateDeviceIdleTempWhitelist(mTempWhitelistAppIdArray, appId,
2987 adding);
2988 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002989 if (mLocalPowerManager != null) {
2990 if (DEBUG) {
2991 Slog.d(TAG, "Setting wakelock temp whitelist to "
2992 + Arrays.toString(mTempWhitelistAppIdArray));
2993 }
2994 mLocalPowerManager.setDeviceIdleTempWhitelist(mTempWhitelistAppIdArray);
2995 }
Suprabh Shukla5bf49812018-05-24 18:38:50 -07002996 passWhiteListsToForceAppStandbyTrackerLocked();
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002997 }
2998
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002999 private void reportPowerSaveWhitelistChangedLocked() {
3000 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
3001 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Xiaohui Chene4de5a02015-09-22 15:33:31 -07003002 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003003 }
3004
3005 private void reportTempWhitelistChangedLocked() {
3006 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_TEMP_WHITELIST_CHANGED);
3007 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Xiaohui Chene4de5a02015-09-22 15:33:31 -07003008 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003009 }
3010
Suprabh Shukla5bf49812018-05-24 18:38:50 -07003011 private void passWhiteListsToForceAppStandbyTrackerLocked() {
Makoto Onukie4918212018-02-06 11:30:15 -08003012 mAppStateTracker.setPowerSaveWhitelistAppIds(
Makoto Onuki71755c92018-01-16 14:15:44 -08003013 mPowerSaveWhitelistExceptIdleAppIdArray,
Suprabh Shukla5bf49812018-05-24 18:38:50 -07003014 mPowerSaveWhitelistUserAppIdArray,
Makoto Onuki2206af32017-11-21 16:25:35 -08003015 mTempWhitelistAppIdArray);
3016 }
3017
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003018 void readConfigFileLocked() {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003019 if (DEBUG) Slog.d(TAG, "Reading config from " + mConfigFile.getBaseFile());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003020 mPowerSaveWhitelistUserApps.clear();
3021 FileInputStream stream;
3022 try {
3023 stream = mConfigFile.openRead();
3024 } catch (FileNotFoundException e) {
3025 return;
3026 }
3027 try {
3028 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003029 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003030 readConfigFileLocked(parser);
3031 } catch (XmlPullParserException e) {
3032 } finally {
3033 try {
3034 stream.close();
3035 } catch (IOException e) {
3036 }
3037 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003038 }
3039
3040 private void readConfigFileLocked(XmlPullParser parser) {
3041 final PackageManager pm = getContext().getPackageManager();
3042
3043 try {
3044 int type;
3045 while ((type = parser.next()) != XmlPullParser.START_TAG
3046 && type != XmlPullParser.END_DOCUMENT) {
3047 ;
3048 }
3049
3050 if (type != XmlPullParser.START_TAG) {
3051 throw new IllegalStateException("no start tag found");
3052 }
3053
3054 int outerDepth = parser.getDepth();
3055 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3056 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3057 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3058 continue;
3059 }
3060
3061 String tagName = parser.getName();
Suprabh Shukla08105642017-09-26 14:45:30 -07003062 switch (tagName) {
3063 case "wl":
3064 String name = parser.getAttributeValue(null, "n");
3065 if (name != null) {
3066 try {
3067 ApplicationInfo ai = pm.getApplicationInfo(name,
3068 PackageManager.MATCH_ANY_USER);
3069 mPowerSaveWhitelistUserApps.put(ai.packageName,
3070 UserHandle.getAppId(ai.uid));
3071 } catch (PackageManager.NameNotFoundException e) {
3072 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003073 }
Suprabh Shukla08105642017-09-26 14:45:30 -07003074 break;
3075 case "un-wl":
3076 final String packageName = parser.getAttributeValue(null, "n");
3077 if (mPowerSaveWhitelistApps.containsKey(packageName)) {
3078 mRemovedFromSystemWhitelistApps.put(packageName,
3079 mPowerSaveWhitelistApps.remove(packageName));
3080 }
3081 break;
3082 default:
3083 Slog.w(TAG, "Unknown element under <config>: "
3084 + parser.getName());
3085 XmlUtils.skipCurrentTag(parser);
3086 break;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003087 }
3088 }
3089
3090 } catch (IllegalStateException e) {
3091 Slog.w(TAG, "Failed parsing config " + e);
3092 } catch (NullPointerException e) {
3093 Slog.w(TAG, "Failed parsing config " + e);
3094 } catch (NumberFormatException e) {
3095 Slog.w(TAG, "Failed parsing config " + e);
3096 } catch (XmlPullParserException e) {
3097 Slog.w(TAG, "Failed parsing config " + e);
3098 } catch (IOException e) {
3099 Slog.w(TAG, "Failed parsing config " + e);
3100 } catch (IndexOutOfBoundsException e) {
3101 Slog.w(TAG, "Failed parsing config " + e);
3102 }
3103 }
3104
3105 void writeConfigFileLocked() {
3106 mHandler.removeMessages(MSG_WRITE_CONFIG);
3107 mHandler.sendEmptyMessageDelayed(MSG_WRITE_CONFIG, 5000);
3108 }
3109
3110 void handleWriteConfigFile() {
3111 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
3112
3113 try {
3114 synchronized (this) {
3115 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003116 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003117 writeConfigFileLocked(out);
3118 }
3119 } catch (IOException e) {
3120 }
3121
3122 synchronized (mConfigFile) {
3123 FileOutputStream stream = null;
3124 try {
3125 stream = mConfigFile.startWrite();
3126 memStream.writeTo(stream);
3127 stream.flush();
3128 FileUtils.sync(stream);
3129 stream.close();
3130 mConfigFile.finishWrite(stream);
3131 } catch (IOException e) {
3132 Slog.w(TAG, "Error writing config file", e);
3133 mConfigFile.failWrite(stream);
3134 }
3135 }
3136 }
3137
3138 void writeConfigFileLocked(XmlSerializer out) throws IOException {
3139 out.startDocument(null, true);
3140 out.startTag(null, "config");
3141 for (int i=0; i<mPowerSaveWhitelistUserApps.size(); i++) {
3142 String name = mPowerSaveWhitelistUserApps.keyAt(i);
3143 out.startTag(null, "wl");
3144 out.attribute(null, "n", name);
3145 out.endTag(null, "wl");
3146 }
Suprabh Shukla08105642017-09-26 14:45:30 -07003147 for (int i = 0; i < mRemovedFromSystemWhitelistApps.size(); i++) {
3148 out.startTag(null, "un-wl");
3149 out.attribute(null, "n", mRemovedFromSystemWhitelistApps.keyAt(i));
3150 out.endTag(null, "un-wl");
3151 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003152 out.endTag(null, "config");
3153 out.endDocument();
3154 }
3155
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003156 static void dumpHelp(PrintWriter pw) {
3157 pw.println("Device idle controller (deviceidle) commands:");
3158 pw.println(" help");
3159 pw.println(" Print this help text.");
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003160 pw.println(" step [light|deep]");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003161 pw.println(" Immediately step to next state, without waiting for alarm.");
Dianne Hackborn88c41352016-04-07 15:18:58 -07003162 pw.println(" force-idle [light|deep]");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003163 pw.println(" Force directly into idle mode, regardless of other device state.");
Dianne Hackborn88c41352016-04-07 15:18:58 -07003164 pw.println(" force-inactive");
3165 pw.println(" Force to be inactive, ready to freely step idle states.");
3166 pw.println(" unforce");
3167 pw.println(" Resume normal functioning after force-idle or force-inactive.");
3168 pw.println(" get [light|deep|force|screen|charging|network]");
3169 pw.println(" Retrieve the current given state.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08003170 pw.println(" disable [light|deep|all]");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003171 pw.println(" Completely disable device idle mode.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08003172 pw.println(" enable [light|deep|all]");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003173 pw.println(" Re-enable device idle mode after it had previously been disabled.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08003174 pw.println(" enabled [light|deep|all]");
Dianne Hackborn92617032015-06-19 15:32:19 -07003175 pw.println(" Print 1 if device idle mode is currently enabled, else 0.");
Dianne Hackborn1b139682015-07-06 15:13:37 -07003176 pw.println(" whitelist");
3177 pw.println(" Print currently whitelisted apps.");
Dianne Hackborn92617032015-06-19 15:32:19 -07003178 pw.println(" whitelist [package ...]");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003179 pw.println(" Add (prefix with +) or remove (prefix with -) packages.");
Suprabh Shukla08105642017-09-26 14:45:30 -07003180 pw.println(" sys-whitelist [package ...|reset]");
3181 pw.println(" Prefix the package with '-' to remove it from the system whitelist or '+'"
3182 + " to put it back in the system whitelist.");
3183 pw.println(" Note that only packages that were"
3184 + " earlier removed from the system whitelist can be added back.");
3185 pw.println(" reset will reset the whitelist to the original state");
3186 pw.println(" Prints the system whitelist if no arguments are specified");
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07003187 pw.println(" except-idle-whitelist [package ...|reset]");
3188 pw.println(" Prefix the package with '+' to add it to whitelist or "
3189 + "'=' to check if it is already whitelisted");
3190 pw.println(" [reset] will reset the whitelist to it's original state");
3191 pw.println(" Note that unlike <whitelist> cmd, "
3192 + "changes made using this won't be persisted across boots");
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003193 pw.println(" tempwhitelist");
3194 pw.println(" Print packages that are temporarily whitelisted.");
Sudheer Shanka326b3112017-11-27 14:40:57 -08003195 pw.println(" tempwhitelist [-u USER] [-d DURATION] [-r] [package]");
3196 pw.println(" Temporarily place package in whitelist for DURATION milliseconds.");
Dianne Hackborn85e35642017-01-12 15:10:57 -08003197 pw.println(" If no DURATION is specified, 10 seconds is used");
Sudheer Shanka326b3112017-11-27 14:40:57 -08003198 pw.println(" If [-r] option is used, then the package is removed from temp whitelist "
3199 + "and any [-d] is ignored");
Amith Yamasani4cb42572018-04-27 10:02:57 -07003200 pw.println(" motion");
3201 pw.println(" Simulate a motion event to bring the device out of deep doze");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003202 }
3203
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003204 class Shell extends ShellCommand {
3205 int userId = UserHandle.USER_SYSTEM;
3206
3207 @Override
3208 public int onCommand(String cmd) {
3209 return onShellCommand(this, cmd);
3210 }
3211
3212 @Override
3213 public void onHelp() {
3214 PrintWriter pw = getOutPrintWriter();
3215 dumpHelp(pw);
3216 }
3217 }
3218
3219 int onShellCommand(Shell shell, String cmd) {
3220 PrintWriter pw = shell.getOutPrintWriter();
3221 if ("step".equals(cmd)) {
3222 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3223 null);
3224 synchronized (this) {
3225 long token = Binder.clearCallingIdentity();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003226 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003227 try {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003228 if (arg == null || "deep".equals(arg)) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003229 stepIdleStateLocked("s:shell");
3230 pw.print("Stepped to deep: ");
3231 pw.println(stateToString(mState));
3232 } else if ("light".equals(arg)) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003233 stepLightIdleStateLocked("s:shell");
3234 pw.print("Stepped to light: "); pw.println(lightStateToString(mLightState));
3235 } else {
3236 pw.println("Unknown idle mode: " + arg);
3237 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003238 } finally {
3239 Binder.restoreCallingIdentity(token);
3240 }
3241 }
3242 } else if ("force-idle".equals(cmd)) {
3243 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3244 null);
3245 synchronized (this) {
3246 long token = Binder.clearCallingIdentity();
Dianne Hackborn88c41352016-04-07 15:18:58 -07003247 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003248 try {
Dianne Hackborn88c41352016-04-07 15:18:58 -07003249 if (arg == null || "deep".equals(arg)) {
3250 if (!mDeepEnabled) {
3251 pw.println("Unable to go deep idle; not enabled");
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003252 return -1;
3253 }
Dianne Hackborn88c41352016-04-07 15:18:58 -07003254 mForceIdle = true;
3255 becomeInactiveIfAppropriateLocked();
3256 int curState = mState;
3257 while (curState != STATE_IDLE) {
3258 stepIdleStateLocked("s:shell");
3259 if (curState == mState) {
3260 pw.print("Unable to go deep idle; stopped at ");
3261 pw.println(stateToString(mState));
3262 exitForceIdleLocked();
3263 return -1;
3264 }
3265 curState = mState;
3266 }
3267 pw.println("Now forced in to deep idle mode");
3268 } else if ("light".equals(arg)) {
3269 mForceIdle = true;
3270 becomeInactiveIfAppropriateLocked();
3271 int curLightState = mLightState;
3272 while (curLightState != LIGHT_STATE_IDLE) {
Tej Singh93cf3e32017-12-07 13:05:38 -08003273 stepLightIdleStateLocked("s:shell");
Dianne Hackborn88c41352016-04-07 15:18:58 -07003274 if (curLightState == mLightState) {
3275 pw.print("Unable to go light idle; stopped at ");
3276 pw.println(lightStateToString(mLightState));
3277 exitForceIdleLocked();
3278 return -1;
3279 }
3280 curLightState = mLightState;
3281 }
3282 pw.println("Now forced in to light idle mode");
3283 } else {
3284 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003285 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003286 } finally {
3287 Binder.restoreCallingIdentity(token);
3288 }
3289 }
Dianne Hackborn88c41352016-04-07 15:18:58 -07003290 } else if ("force-inactive".equals(cmd)) {
3291 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3292 null);
3293 synchronized (this) {
3294 long token = Binder.clearCallingIdentity();
3295 try {
3296 mForceIdle = true;
3297 becomeInactiveIfAppropriateLocked();
3298 pw.print("Light state: ");
3299 pw.print(lightStateToString(mLightState));
3300 pw.print(", deep state: ");
3301 pw.println(stateToString(mState));
3302 } finally {
3303 Binder.restoreCallingIdentity(token);
3304 }
3305 }
3306 } else if ("unforce".equals(cmd)) {
3307 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3308 null);
3309 synchronized (this) {
3310 long token = Binder.clearCallingIdentity();
3311 try {
3312 exitForceIdleLocked();
3313 pw.print("Light state: ");
3314 pw.print(lightStateToString(mLightState));
3315 pw.print(", deep state: ");
3316 pw.println(stateToString(mState));
3317 } finally {
3318 Binder.restoreCallingIdentity(token);
3319 }
3320 }
3321 } else if ("get".equals(cmd)) {
3322 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3323 null);
3324 synchronized (this) {
3325 String arg = shell.getNextArg();
3326 if (arg != null) {
3327 long token = Binder.clearCallingIdentity();
3328 try {
3329 switch (arg) {
3330 case "light": pw.println(lightStateToString(mLightState)); break;
3331 case "deep": pw.println(stateToString(mState)); break;
3332 case "force": pw.println(mForceIdle); break;
Kweku Adamsb396ccf2018-09-17 16:37:15 -07003333 case "quick": pw.println(mQuickDozeActivated); break;
Dianne Hackborn88c41352016-04-07 15:18:58 -07003334 case "screen": pw.println(mScreenOn); break;
3335 case "charging": pw.println(mCharging); break;
3336 case "network": pw.println(mNetworkConnected); break;
3337 default: pw.println("Unknown get option: " + arg); break;
3338 }
3339 } finally {
3340 Binder.restoreCallingIdentity(token);
3341 }
3342 } else {
3343 pw.println("Argument required");
3344 }
3345 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003346 } else if ("disable".equals(cmd)) {
3347 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3348 null);
3349 synchronized (this) {
3350 long token = Binder.clearCallingIdentity();
Dianne Hackbornb6843652016-02-22 12:20:13 -08003351 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003352 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08003353 boolean becomeActive = false;
3354 boolean valid = false;
3355 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
3356 valid = true;
3357 if (mDeepEnabled) {
3358 mDeepEnabled = false;
3359 becomeActive = true;
3360 pw.println("Deep idle mode disabled");
3361 }
3362 }
3363 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
3364 valid = true;
3365 if (mLightEnabled) {
3366 mLightEnabled = false;
3367 becomeActive = true;
3368 pw.println("Light idle mode disabled");
3369 }
3370 }
3371 if (becomeActive) {
3372 becomeActiveLocked((arg == null ? "all" : arg) + "-disabled",
3373 Process.myUid());
3374 }
3375 if (!valid) {
3376 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003377 }
3378 } finally {
3379 Binder.restoreCallingIdentity(token);
3380 }
3381 }
3382 } else if ("enable".equals(cmd)) {
3383 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3384 null);
3385 synchronized (this) {
3386 long token = Binder.clearCallingIdentity();
Dianne Hackbornb6843652016-02-22 12:20:13 -08003387 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003388 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08003389 boolean becomeInactive = false;
3390 boolean valid = false;
3391 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
3392 valid = true;
3393 if (!mDeepEnabled) {
3394 mDeepEnabled = true;
3395 becomeInactive = true;
3396 pw.println("Deep idle mode enabled");
3397 }
3398 }
3399 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
3400 valid = true;
3401 if (!mLightEnabled) {
3402 mLightEnabled = true;
3403 becomeInactive = true;
3404 pw.println("Light idle mode enable");
3405 }
3406 }
3407 if (becomeInactive) {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003408 becomeInactiveIfAppropriateLocked();
Dianne Hackbornb6843652016-02-22 12:20:13 -08003409 }
3410 if (!valid) {
3411 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003412 }
3413 } finally {
3414 Binder.restoreCallingIdentity(token);
3415 }
3416 }
3417 } else if ("enabled".equals(cmd)) {
3418 synchronized (this) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08003419 String arg = shell.getNextArg();
3420 if (arg == null || "all".equals(arg)) {
3421 pw.println(mDeepEnabled && mLightEnabled ? "1" : 0);
3422 } else if ("deep".equals(arg)) {
3423 pw.println(mDeepEnabled ? "1" : 0);
3424 } else if ("light".equals(arg)) {
3425 pw.println(mLightEnabled ? "1" : 0);
3426 } else {
3427 pw.println("Unknown idle mode: " + arg);
3428 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003429 }
3430 } else if ("whitelist".equals(cmd)) {
Dianne Hackborneb909e32016-09-29 14:35:15 -07003431 String arg = shell.getNextArg();
3432 if (arg != null) {
3433 getContext().enforceCallingOrSelfPermission(
3434 android.Manifest.permission.DEVICE_POWER, null);
3435 long token = Binder.clearCallingIdentity();
3436 try {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003437 do {
3438 if (arg.length() < 1 || (arg.charAt(0) != '-'
Felipe Lemef8a46232016-02-10 13:51:54 -08003439 && arg.charAt(0) != '+' && arg.charAt(0) != '=')) {
3440 pw.println("Package must be prefixed with +, -, or =: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003441 return -1;
3442 }
3443 char op = arg.charAt(0);
3444 String pkg = arg.substring(1);
3445 if (op == '+') {
3446 if (addPowerSaveWhitelistAppInternal(pkg)) {
3447 pw.println("Added: " + pkg);
3448 } else {
3449 pw.println("Unknown package: " + pkg);
3450 }
Felipe Lemef8a46232016-02-10 13:51:54 -08003451 } else if (op == '-') {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003452 if (removePowerSaveWhitelistAppInternal(pkg)) {
3453 pw.println("Removed: " + pkg);
3454 }
Felipe Lemef8a46232016-02-10 13:51:54 -08003455 } else {
3456 pw.println(getPowerSaveWhitelistAppInternal(pkg));
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003457 }
3458 } while ((arg=shell.getNextArg()) != null);
Dianne Hackborneb909e32016-09-29 14:35:15 -07003459 } finally {
3460 Binder.restoreCallingIdentity(token);
3461 }
3462 } else {
3463 synchronized (this) {
3464 for (int j=0; j<mPowerSaveWhitelistAppsExceptIdle.size(); j++) {
3465 pw.print("system-excidle,");
3466 pw.print(mPowerSaveWhitelistAppsExceptIdle.keyAt(j));
3467 pw.print(",");
3468 pw.println(mPowerSaveWhitelistAppsExceptIdle.valueAt(j));
3469 }
3470 for (int j=0; j<mPowerSaveWhitelistApps.size(); j++) {
3471 pw.print("system,");
3472 pw.print(mPowerSaveWhitelistApps.keyAt(j));
3473 pw.print(",");
3474 pw.println(mPowerSaveWhitelistApps.valueAt(j));
3475 }
3476 for (int j=0; j<mPowerSaveWhitelistUserApps.size(); j++) {
3477 pw.print("user,");
3478 pw.print(mPowerSaveWhitelistUserApps.keyAt(j));
3479 pw.print(",");
3480 pw.println(mPowerSaveWhitelistUserApps.valueAt(j));
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003481 }
3482 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003483 }
3484 } else if ("tempwhitelist".equals(cmd)) {
Dianne Hackborn85e35642017-01-12 15:10:57 -08003485 long duration = 10000;
Sudheer Shanka326b3112017-11-27 14:40:57 -08003486 boolean removePkg = false;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003487 String opt;
3488 while ((opt=shell.getNextOption()) != null) {
3489 if ("-u".equals(opt)) {
3490 opt = shell.getNextArg();
3491 if (opt == null) {
3492 pw.println("-u requires a user number");
3493 return -1;
3494 }
3495 shell.userId = Integer.parseInt(opt);
Dianne Hackborn85e35642017-01-12 15:10:57 -08003496 } else if ("-d".equals(opt)) {
3497 opt = shell.getNextArg();
3498 if (opt == null) {
3499 pw.println("-d requires a duration");
3500 return -1;
3501 }
3502 duration = Long.parseLong(opt);
Sudheer Shanka326b3112017-11-27 14:40:57 -08003503 } else if ("-r".equals(opt)) {
3504 removePkg = true;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003505 }
3506 }
3507 String arg = shell.getNextArg();
3508 if (arg != null) {
3509 try {
Sudheer Shanka326b3112017-11-27 14:40:57 -08003510 if (removePkg) {
3511 removePowerSaveTempWhitelistAppChecked(arg, shell.userId);
3512 } else {
3513 addPowerSaveTempWhitelistAppChecked(arg, duration, shell.userId, "shell");
3514 }
Christopher Tateec3a9f32017-03-21 17:43:47 -07003515 } catch (Exception e) {
3516 pw.println("Failed: " + e);
3517 return -1;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003518 }
Sudheer Shanka326b3112017-11-27 14:40:57 -08003519 } else if (removePkg) {
3520 pw.println("[-r] requires a package name");
3521 return -1;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003522 } else {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003523 dumpTempWhitelistSchedule(pw, false);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003524 }
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07003525 } else if ("except-idle-whitelist".equals(cmd)) {
3526 getContext().enforceCallingOrSelfPermission(
3527 android.Manifest.permission.DEVICE_POWER, null);
3528 final long token = Binder.clearCallingIdentity();
3529 try {
3530 String arg = shell.getNextArg();
3531 if (arg == null) {
3532 pw.println("No arguments given");
3533 return -1;
3534 } else if ("reset".equals(arg)) {
3535 resetPowerSaveWhitelistExceptIdleInternal();
3536 } else {
3537 do {
3538 if (arg.length() < 1 || (arg.charAt(0) != '-'
3539 && arg.charAt(0) != '+' && arg.charAt(0) != '=')) {
3540 pw.println("Package must be prefixed with +, -, or =: " + arg);
3541 return -1;
3542 }
3543 char op = arg.charAt(0);
3544 String pkg = arg.substring(1);
3545 if (op == '+') {
3546 if (addPowerSaveWhitelistExceptIdleInternal(pkg)) {
3547 pw.println("Added: " + pkg);
3548 } else {
3549 pw.println("Unknown package: " + pkg);
3550 }
3551 } else if (op == '=') {
3552 pw.println(getPowerSaveWhitelistExceptIdleInternal(pkg));
3553 } else {
3554 pw.println("Unknown argument: " + arg);
3555 return -1;
3556 }
3557 } while ((arg = shell.getNextArg()) != null);
3558 }
3559 } finally {
3560 Binder.restoreCallingIdentity(token);
3561 }
Suprabh Shukla08105642017-09-26 14:45:30 -07003562 } else if ("sys-whitelist".equals(cmd)) {
3563 String arg = shell.getNextArg();
3564 if (arg != null) {
3565 getContext().enforceCallingOrSelfPermission(
3566 android.Manifest.permission.DEVICE_POWER, null);
3567 final long token = Binder.clearCallingIdentity();
3568 try {
3569 if ("reset".equals(arg)) {
3570 resetSystemPowerWhitelistInternal();
3571 } else {
3572 do {
3573 if (arg.length() < 1
3574 || (arg.charAt(0) != '-' && arg.charAt(0) != '+')) {
3575 pw.println("Package must be prefixed with + or - " + arg);
3576 return -1;
3577 }
3578 final char op = arg.charAt(0);
3579 final String pkg = arg.substring(1);
3580 switch (op) {
3581 case '+':
3582 if (restoreSystemPowerWhitelistAppInternal(pkg)) {
3583 pw.println("Restored " + pkg);
3584 }
3585 break;
3586 case '-':
3587 if (removeSystemPowerWhitelistAppInternal(pkg)) {
3588 pw.println("Removed " + pkg);
3589 }
3590 break;
3591 }
3592 } while ((arg = shell.getNextArg()) != null);
3593 }
3594 } finally {
3595 Binder.restoreCallingIdentity(token);
3596 }
3597 } else {
3598 synchronized (this) {
Amith Yamasani4cb42572018-04-27 10:02:57 -07003599 for (int j = 0; j < mPowerSaveWhitelistApps.size(); j++) {
Suprabh Shukla08105642017-09-26 14:45:30 -07003600 pw.print(mPowerSaveWhitelistApps.keyAt(j));
3601 pw.print(",");
3602 pw.println(mPowerSaveWhitelistApps.valueAt(j));
3603 }
3604 }
3605 }
Amith Yamasani4cb42572018-04-27 10:02:57 -07003606 } else if ("motion".equals(cmd)) {
3607 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3608 null);
3609 synchronized (this) {
3610 long token = Binder.clearCallingIdentity();
3611 try {
3612 motionLocked();
3613 pw.print("Light state: ");
3614 pw.print(lightStateToString(mLightState));
3615 pw.print(", deep state: ");
3616 pw.println(stateToString(mState));
3617 } finally {
3618 Binder.restoreCallingIdentity(token);
3619 }
3620 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003621 } else {
3622 return shell.handleDefaultCommands(cmd);
3623 }
3624 return 0;
3625 }
3626
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003627 void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003628 if (!DumpUtils.checkDumpPermission(getContext(), TAG, pw)) return;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003629
3630 if (args != null) {
Xiaohui Chen7c696362015-09-16 09:56:14 -07003631 int userId = UserHandle.USER_SYSTEM;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003632 for (int i=0; i<args.length; i++) {
3633 String arg = args[i];
3634 if ("-h".equals(arg)) {
3635 dumpHelp(pw);
3636 return;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003637 } else if ("-u".equals(arg)) {
3638 i++;
3639 if (i < args.length) {
3640 arg = args[i];
3641 userId = Integer.parseInt(arg);
3642 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003643 } else if ("-a".equals(arg)) {
3644 // Ignore, we always dump all.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003645 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
3646 pw.println("Unknown option: " + arg);
3647 return;
3648 } else {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003649 Shell shell = new Shell();
3650 shell.userId = userId;
3651 String[] newArgs = new String[args.length-i];
3652 System.arraycopy(args, i, newArgs, 0, args.length-i);
Dianne Hackborn354736e2016-08-22 17:00:05 -07003653 shell.exec(mBinderService, null, fd, null, newArgs, null,
3654 new ResultReceiver(null));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003655 return;
3656 }
3657 }
3658 }
3659
3660 synchronized (this) {
Dianne Hackborna750a632015-06-16 17:18:23 -07003661 mConstants.dump(pw);
3662
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08003663 if (mEventCmds[0] != EVENT_NULL) {
3664 pw.println(" Idling history:");
3665 long now = SystemClock.elapsedRealtime();
3666 for (int i=EVENT_BUFFER_SIZE-1; i>=0; i--) {
3667 int cmd = mEventCmds[i];
3668 if (cmd == EVENT_NULL) {
3669 continue;
3670 }
3671 String label;
3672 switch (mEventCmds[i]) {
3673 case EVENT_NORMAL: label = " normal"; break;
3674 case EVENT_LIGHT_IDLE: label = " light-idle"; break;
3675 case EVENT_LIGHT_MAINTENANCE: label = "light-maint"; break;
Dianne Hackbornb6843652016-02-22 12:20:13 -08003676 case EVENT_DEEP_IDLE: label = " deep-idle"; break;
3677 case EVENT_DEEP_MAINTENANCE: label = " deep-maint"; break;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08003678 default: label = " ??"; break;
3679 }
3680 pw.print(" ");
3681 pw.print(label);
3682 pw.print(": ");
Amith Yamasaniac6517a2018-04-23 12:19:34 -07003683 TimeUtils.formatDuration(mEventTimes[i], now, pw);
3684 if (mEventReasons[i] != null) {
3685 pw.print(" (");
3686 pw.print(mEventReasons[i]);
3687 pw.print(")");
3688 }
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08003689 pw.println();
Amith Yamasaniac6517a2018-04-23 12:19:34 -07003690
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08003691 }
3692 }
3693
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003694 int size = mPowerSaveWhitelistAppsExceptIdle.size();
3695 if (size > 0) {
3696 pw.println(" Whitelist (except idle) system apps:");
3697 for (int i = 0; i < size; i++) {
3698 pw.print(" ");
3699 pw.println(mPowerSaveWhitelistAppsExceptIdle.keyAt(i));
3700 }
3701 }
3702 size = mPowerSaveWhitelistApps.size();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003703 if (size > 0) {
3704 pw.println(" Whitelist system apps:");
3705 for (int i = 0; i < size; i++) {
3706 pw.print(" ");
3707 pw.println(mPowerSaveWhitelistApps.keyAt(i));
3708 }
3709 }
Suprabh Shukla08105642017-09-26 14:45:30 -07003710 size = mRemovedFromSystemWhitelistApps.size();
3711 if (size > 0) {
3712 pw.println(" Removed from whitelist system apps:");
3713 for (int i = 0; i < size; i++) {
3714 pw.print(" ");
3715 pw.println(mRemovedFromSystemWhitelistApps.keyAt(i));
3716 }
3717 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003718 size = mPowerSaveWhitelistUserApps.size();
3719 if (size > 0) {
3720 pw.println(" Whitelist user apps:");
3721 for (int i = 0; i < size; i++) {
3722 pw.print(" ");
3723 pw.println(mPowerSaveWhitelistUserApps.keyAt(i));
3724 }
3725 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003726 size = mPowerSaveWhitelistExceptIdleAppIds.size();
3727 if (size > 0) {
3728 pw.println(" Whitelist (except idle) all app ids:");
3729 for (int i = 0; i < size; i++) {
3730 pw.print(" ");
3731 pw.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
3732 pw.println();
3733 }
3734 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08003735 size = mPowerSaveWhitelistUserAppIds.size();
3736 if (size > 0) {
3737 pw.println(" Whitelist user app ids:");
3738 for (int i = 0; i < size; i++) {
3739 pw.print(" ");
3740 pw.print(mPowerSaveWhitelistUserAppIds.keyAt(i));
3741 pw.println();
3742 }
3743 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07003744 size = mPowerSaveWhitelistAllAppIds.size();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003745 if (size > 0) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07003746 pw.println(" Whitelist all app ids:");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003747 for (int i = 0; i < size; i++) {
Dianne Hackborna750a632015-06-16 17:18:23 -07003748 pw.print(" ");
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07003749 pw.print(mPowerSaveWhitelistAllAppIds.keyAt(i));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003750 pw.println();
3751 }
3752 }
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003753 dumpTempWhitelistSchedule(pw, true);
3754
Dianne Hackborna750a632015-06-16 17:18:23 -07003755 size = mTempWhitelistAppIdArray != null ? mTempWhitelistAppIdArray.length : 0;
3756 if (size > 0) {
3757 pw.println(" Temp whitelist app ids:");
3758 for (int i = 0; i < size; i++) {
3759 pw.print(" ");
3760 pw.print(mTempWhitelistAppIdArray[i]);
3761 pw.println();
3762 }
3763 }
Adam Lesinski31c05d12015-06-09 17:34:04 -07003764
Dianne Hackbornb6843652016-02-22 12:20:13 -08003765 pw.print(" mLightEnabled="); pw.print(mLightEnabled);
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003766 pw.print(" mDeepEnabled="); pw.println(mDeepEnabled);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003767 pw.print(" mForceIdle="); pw.println(mForceIdle);
Nick Vaccaro20feaea2015-09-17 17:22:44 -07003768 pw.print(" mMotionSensor="); pw.println(mMotionSensor);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003769 pw.print(" mScreenOn="); pw.println(mScreenOn);
Amith Yamasani396a10c2018-01-19 10:58:07 -08003770 pw.print(" mScreenLocked="); pw.println(mScreenLocked);
Dianne Hackborn88c41352016-04-07 15:18:58 -07003771 pw.print(" mNetworkConnected="); pw.println(mNetworkConnected);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003772 pw.print(" mCharging="); pw.println(mCharging);
Nick Vaccaro20feaea2015-09-17 17:22:44 -07003773 pw.print(" mMotionActive="); pw.println(mMotionListener.active);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003774 pw.print(" mNotMoving="); pw.println(mNotMoving);
Joe LaPenna23d681b2015-08-27 15:12:11 -07003775 pw.print(" mLocating="); pw.print(mLocating); pw.print(" mHasGps=");
3776 pw.print(mHasGps); pw.print(" mHasNetwork=");
3777 pw.print(mHasNetworkLocation); pw.print(" mLocated="); pw.println(mLocated);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07003778 if (mLastGenericLocation != null) {
3779 pw.print(" mLastGenericLocation="); pw.println(mLastGenericLocation);
3780 }
3781 if (mLastGpsLocation != null) {
3782 pw.print(" mLastGpsLocation="); pw.println(mLastGpsLocation);
3783 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003784 pw.print(" mState="); pw.print(stateToString(mState));
3785 pw.print(" mLightState=");
3786 pw.println(lightStateToString(mLightState));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003787 pw.print(" mInactiveTimeout="); TimeUtils.formatDuration(mInactiveTimeout, pw);
3788 pw.println();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003789 if (mActiveIdleOpCount != 0) {
3790 pw.print(" mActiveIdleOpCount="); pw.println(mActiveIdleOpCount);
3791 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003792 if (mNextAlarmTime != 0) {
3793 pw.print(" mNextAlarmTime=");
3794 TimeUtils.formatDuration(mNextAlarmTime, SystemClock.elapsedRealtime(), pw);
3795 pw.println();
3796 }
3797 if (mNextIdlePendingDelay != 0) {
3798 pw.print(" mNextIdlePendingDelay=");
3799 TimeUtils.formatDuration(mNextIdlePendingDelay, pw);
3800 pw.println();
3801 }
3802 if (mNextIdleDelay != 0) {
3803 pw.print(" mNextIdleDelay=");
3804 TimeUtils.formatDuration(mNextIdleDelay, pw);
3805 pw.println();
3806 }
Dianne Hackborn953fc942016-03-29 15:36:24 -07003807 if (mNextLightIdleDelay != 0) {
3808 pw.print(" mNextIdleDelay=");
3809 TimeUtils.formatDuration(mNextLightIdleDelay, pw);
3810 pw.println();
3811 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003812 if (mNextLightAlarmTime != 0) {
3813 pw.print(" mNextLightAlarmTime=");
3814 TimeUtils.formatDuration(mNextLightAlarmTime, SystemClock.elapsedRealtime(), pw);
3815 pw.println();
3816 }
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08003817 if (mCurIdleBudget != 0) {
3818 pw.print(" mCurIdleBudget=");
3819 TimeUtils.formatDuration(mCurIdleBudget, pw);
3820 pw.println();
3821 }
3822 if (mMaintenanceStartTime != 0) {
3823 pw.print(" mMaintenanceStartTime=");
3824 TimeUtils.formatDuration(mMaintenanceStartTime, SystemClock.elapsedRealtime(), pw);
3825 pw.println();
3826 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003827 if (mJobsActive) {
3828 pw.print(" mJobsActive="); pw.println(mJobsActive);
3829 }
3830 if (mAlarmsActive) {
3831 pw.print(" mAlarmsActive="); pw.println(mAlarmsActive);
3832 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003833 }
3834 }
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003835
3836 void dumpTempWhitelistSchedule(PrintWriter pw, boolean printTitle) {
3837 final int size = mTempWhitelistAppIdEndTimes.size();
3838 if (size > 0) {
3839 String prefix = "";
3840 if (printTitle) {
3841 pw.println(" Temp whitelist schedule:");
3842 prefix = " ";
3843 }
3844 final long timeNow = SystemClock.elapsedRealtime();
3845 for (int i = 0; i < size; i++) {
3846 pw.print(prefix);
3847 pw.print("UID=");
3848 pw.print(mTempWhitelistAppIdEndTimes.keyAt(i));
3849 pw.print(": ");
3850 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.valueAt(i);
3851 TimeUtils.formatDuration(entry.first.value, timeNow, pw);
3852 pw.print(" - ");
3853 pw.println(entry.second);
3854 }
3855 }
3856 }
3857 }