blob: 08cb7a2f5047e922e489776d96a91b371c89ab8c [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;
Robin Lee204cb222018-12-07 15:17:44 +010046import android.os.BatteryManager;
Dianne Hackbornfd854ee2015-07-13 18:00:37 -070047import android.os.BatteryStats;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070048import android.os.Binder;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -070049import android.os.Bundle;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070050import android.os.Environment;
51import android.os.FileUtils;
52import android.os.Handler;
53import android.os.IDeviceIdleController;
Yao Chenca5edbb2016-01-13 14:44:36 -080054import android.os.IMaintenanceActivityListener;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070055import android.os.Looper;
56import android.os.Message;
57import android.os.PowerManager;
Kweku Adamsb396ccf2018-09-17 16:37:15 -070058import android.os.PowerManager.ServiceType;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070059import android.os.PowerManagerInternal;
Dianne Hackbornb6683c42015-06-18 17:40:33 -070060import android.os.Process;
Yao Chenca5edbb2016-01-13 14:44:36 -080061import android.os.RemoteCallbackList;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070062import android.os.RemoteException;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -070063import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070064import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070065import android.os.ShellCallback;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -070066import android.os.ShellCommand;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070067import android.os.SystemClock;
68import android.os.UserHandle;
Adam Lesinski31c05d12015-06-09 17:34:04 -070069import android.provider.Settings;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070070import android.util.ArrayMap;
71import android.util.ArraySet;
Adam Lesinski31c05d12015-06-09 17:34:04 -070072import android.util.KeyValueListParser;
Dianne Hackbornfd854ee2015-07-13 18:00:37 -070073import android.util.MutableLong;
74import android.util.Pair;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070075import android.util.Slog;
Dianne Hackbornfd854ee2015-07-13 18:00:37 -070076import android.util.SparseArray;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070077import android.util.SparseBooleanArray;
78import android.util.TimeUtils;
79import android.util.Xml;
Amith Yamasani520d8f22015-05-08 16:36:21 -070080
Sudheer Shanka326b3112017-11-27 14:40:57 -080081import com.android.internal.annotations.GuardedBy;
Kweku Adams00e3a372018-09-28 16:57:09 -070082import com.android.internal.annotations.VisibleForTesting;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070083import com.android.internal.app.IBatteryStats;
84import com.android.internal.os.AtomicFile;
85import com.android.internal.os.BackgroundThread;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060086import com.android.internal.util.DumpUtils;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070087import com.android.internal.util.FastXmlSerializer;
88import com.android.internal.util.XmlUtils;
89import com.android.server.am.BatteryStatsService;
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -070090import com.android.server.net.NetworkPolicyManagerInternal;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -070091import com.android.server.wm.ActivityTaskManagerInternal;
Amith Yamasani520d8f22015-05-08 16:36:21 -070092
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070093import org.xmlpull.v1.XmlPullParser;
94import org.xmlpull.v1.XmlPullParserException;
95import org.xmlpull.v1.XmlSerializer;
96
97import java.io.ByteArrayOutputStream;
98import java.io.File;
99import java.io.FileDescriptor;
100import java.io.FileInputStream;
101import java.io.FileNotFoundException;
102import java.io.FileOutputStream;
103import java.io.IOException;
104import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100105import java.nio.charset.StandardCharsets;
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700106import java.util.Arrays;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700107
108/**
109 * Keeps track of device idleness and drives low power mode based on that.
Kweku Adams00e3a372018-09-28 16:57:09 -0700110 *
111 * Test: atest com.android.server.DeviceIdleControllerTest
Kweku Adamsf596cfc2018-10-04 15:15:22 -0700112 *
113 * Current idling state machine (as of Android 9 Pie). This can be visualized using Graphviz:
114
115 digraph {
116 subgraph deep {
117 label="deep";
118
119 STATE_ACTIVE [label="STATE_ACTIVE\nScreen on OR Charging OR Alarm going off soon"]
120 STATE_INACTIVE [label="STATE_INACTIVE\nScreen off AND Not charging"]
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700121 STATE_QUICK_DOZE_DELAY [
122 label="STATE_QUICK_DOZE_DELAY\n"
123 + "Screen off AND Not charging\n"
124 + "Location, motion detection, and significant motion monitoring turned off"
125 ]
Kweku Adamsf596cfc2018-10-04 15:15:22 -0700126 STATE_IDLE_PENDING [
127 label="STATE_IDLE_PENDING\nSignificant motion monitoring turned on"
128 ]
129 STATE_SENSING [label="STATE_SENSING\nMonitoring for ANY motion"]
130 STATE_LOCATING [
131 label="STATE_LOCATING\nRequesting location, motion monitoring still on"
132 ]
133 STATE_IDLE [
134 label="STATE_IDLE\nLocation and motion detection turned off\n"
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700135 + "Significant motion monitoring state unchanged"
Kweku Adamsf596cfc2018-10-04 15:15:22 -0700136 ]
137 STATE_IDLE_MAINTENANCE [label="STATE_IDLE_MAINTENANCE\n"]
138
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700139 STATE_ACTIVE -> STATE_INACTIVE [
140 label="becomeInactiveIfAppropriateLocked() AND Quick Doze not enabled"
141 ]
142 STATE_ACTIVE -> STATE_QUICK_DOZE_DELAY [
143 label="becomeInactiveIfAppropriateLocked() AND Quick Doze enabled"
144 ]
Kweku Adamsf596cfc2018-10-04 15:15:22 -0700145
146 STATE_INACTIVE -> STATE_ACTIVE [
147 label="handleMotionDetectedLocked(), becomeActiveLocked()"
148 ]
149 STATE_INACTIVE -> STATE_IDLE_PENDING [label="stepIdleStateLocked()"]
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700150 STATE_INACTIVE -> STATE_QUICK_DOZE_DELAY [
151 label="becomeInactiveIfAppropriateLocked() AND Quick Doze enabled"
152 ]
Kweku Adamsf596cfc2018-10-04 15:15:22 -0700153
154 STATE_IDLE_PENDING -> STATE_ACTIVE [
155 label="handleMotionDetectedLocked(), becomeActiveLocked()"
156 ]
157 STATE_IDLE_PENDING -> STATE_SENSING [label="stepIdleStateLocked()"]
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700158 STATE_IDLE_PENDING -> STATE_QUICK_DOZE_DELAY [
159 label="becomeInactiveIfAppropriateLocked() AND Quick Doze enabled"
160 ]
Kweku Adamsf596cfc2018-10-04 15:15:22 -0700161
162 STATE_SENSING -> STATE_ACTIVE [
163 label="handleMotionDetectedLocked(), becomeActiveLocked()"
164 ]
165 STATE_SENSING -> STATE_LOCATING [label="stepIdleStateLocked()"]
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700166 STATE_SENSING -> STATE_QUICK_DOZE_DELAY [
167 label="becomeInactiveIfAppropriateLocked() AND Quick Doze enabled"
168 ]
Kweku Adamsf596cfc2018-10-04 15:15:22 -0700169 STATE_SENSING -> STATE_IDLE [
170 label="stepIdleStateLocked()\n"
171 + "No Location Manager OR (no Network provider AND no GPS provider)"
172 ]
173
174 STATE_LOCATING -> STATE_ACTIVE [
175 label="handleMotionDetectedLocked(), becomeActiveLocked()"
176 ]
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700177 STATE_LOCATING -> STATE_QUICK_DOZE_DELAY [
178 label="becomeInactiveIfAppropriateLocked() AND Quick Doze enabled"
179 ]
Kweku Adamsf596cfc2018-10-04 15:15:22 -0700180 STATE_LOCATING -> STATE_IDLE [label="stepIdleStateLocked()"]
181
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700182 STATE_QUICK_DOZE_DELAY -> STATE_ACTIVE [
183 label="handleMotionDetectedLocked(), becomeActiveLocked()"
184 ]
185 STATE_QUICK_DOZE_DELAY -> STATE_IDLE [label="stepIdleStateLocked()"]
186
Kweku Adamsf596cfc2018-10-04 15:15:22 -0700187 STATE_IDLE -> STATE_ACTIVE [label="handleMotionDetectedLocked(), becomeActiveLocked()"]
188 STATE_IDLE -> STATE_IDLE_MAINTENANCE [label="stepIdleStateLocked()"]
189
190 STATE_IDLE_MAINTENANCE -> STATE_ACTIVE [
191 label="handleMotionDetectedLocked(), becomeActiveLocked()"
192 ]
193 STATE_IDLE_MAINTENANCE -> STATE_IDLE [
194 label="stepIdleStateLocked(), exitMaintenanceEarlyIfNeededLocked()"
195 ]
196 }
197
198 subgraph light {
199 label="light"
200
201 LIGHT_STATE_ACTIVE [
202 label="LIGHT_STATE_ACTIVE\nScreen on OR Charging OR Alarm going off soon"
203 ]
204 LIGHT_STATE_INACTIVE [label="LIGHT_STATE_INACTIVE\nScreen off AND Not charging"]
205 LIGHT_STATE_PRE_IDLE [
206 label="LIGHT_STATE_PRE_IDLE\n"
207 + "Delay going into LIGHT_STATE_IDLE due to some running jobs or alarms"
208 ]
209 LIGHT_STATE_IDLE [label="LIGHT_STATE_IDLE\n"]
210 LIGHT_STATE_WAITING_FOR_NETWORK [
211 label="LIGHT_STATE_WAITING_FOR_NETWORK\n"
212 + "Coming out of LIGHT_STATE_IDLE, waiting for network"
213 ]
214 LIGHT_STATE_IDLE_MAINTENANCE [label="LIGHT_STATE_IDLE_MAINTENANCE\n"]
215 LIGHT_STATE_OVERRIDE [
216 label="LIGHT_STATE_OVERRIDE\nDevice in deep doze, light no longer changing states"
217 ]
218
219 LIGHT_STATE_ACTIVE -> LIGHT_STATE_INACTIVE [
220 label="becomeInactiveIfAppropriateLocked()"
221 ]
222 LIGHT_STATE_ACTIVE -> LIGHT_STATE_OVERRIDE [label="deep goes to STATE_IDLE"]
223
224 LIGHT_STATE_INACTIVE -> LIGHT_STATE_ACTIVE [label="becomeActiveLocked()"]
225 LIGHT_STATE_INACTIVE -> LIGHT_STATE_PRE_IDLE [label="active jobs"]
226 LIGHT_STATE_INACTIVE -> LIGHT_STATE_IDLE [label="no active jobs"]
227 LIGHT_STATE_INACTIVE -> LIGHT_STATE_OVERRIDE [label="deep goes to STATE_IDLE"]
228
229 LIGHT_STATE_PRE_IDLE -> LIGHT_STATE_ACTIVE [label="becomeActiveLocked()"]
230 LIGHT_STATE_PRE_IDLE -> LIGHT_STATE_IDLE [
231 label="stepLightIdleStateLocked(), exitMaintenanceEarlyIfNeededLocked()"
232 ]
233 LIGHT_STATE_PRE_IDLE -> LIGHT_STATE_OVERRIDE [label="deep goes to STATE_IDLE"]
234
235 LIGHT_STATE_IDLE -> LIGHT_STATE_ACTIVE [label="becomeActiveLocked()"]
236 LIGHT_STATE_IDLE -> LIGHT_STATE_WAITING_FOR_NETWORK [label="no network"]
237 LIGHT_STATE_IDLE -> LIGHT_STATE_IDLE_MAINTENANCE
238 LIGHT_STATE_IDLE -> LIGHT_STATE_OVERRIDE [label="deep goes to STATE_IDLE"]
239
240 LIGHT_STATE_WAITING_FOR_NETWORK -> LIGHT_STATE_ACTIVE [label="becomeActiveLocked()"]
241 LIGHT_STATE_WAITING_FOR_NETWORK -> LIGHT_STATE_IDLE_MAINTENANCE
242 LIGHT_STATE_WAITING_FOR_NETWORK -> LIGHT_STATE_OVERRIDE [
243 label="deep goes to STATE_IDLE"
244 ]
245
246 LIGHT_STATE_IDLE_MAINTENANCE -> LIGHT_STATE_ACTIVE [label="becomeActiveLocked()"]
247 LIGHT_STATE_IDLE_MAINTENANCE -> LIGHT_STATE_IDLE [
248 label="stepLightIdleStateLocked(), exitMaintenanceEarlyIfNeededLocked()"
249 ]
250 LIGHT_STATE_IDLE_MAINTENANCE -> LIGHT_STATE_OVERRIDE [label="deep goes to STATE_IDLE"]
251
252 LIGHT_STATE_OVERRIDE -> LIGHT_STATE_ACTIVE [
253 label="handleMotionDetectedLocked(), becomeActiveLocked()"
254 ]
255 }
256 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700257 */
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700258public class DeviceIdleController extends SystemService
259 implements AnyMotionDetector.DeviceIdleCallback {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700260 private static final String TAG = "DeviceIdleController";
261
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700262 private static final boolean DEBUG = false;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700263
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700264 private static final boolean COMPRESS_TIME = false;
Amith Yamasani520d8f22015-05-08 16:36:21 -0700265
Dianne Hackborn953fc942016-03-29 15:36:24 -0700266 private static final int EVENT_BUFFER_SIZE = 100;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800267
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700268 private AlarmManager mAlarmManager;
269 private IBatteryStats mBatteryStats;
Dianne Hackborn85e35642017-01-12 15:10:57 -0800270 private ActivityManagerInternal mLocalActivityManager;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700271 private ActivityTaskManagerInternal mLocalActivityTaskManager;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700272 private PowerManagerInternal mLocalPowerManager;
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700273 private PowerManager mPowerManager;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700274 private INetworkPolicyManager mNetworkPolicyManager;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700275 private SensorManager mSensorManager;
Robin Leec4d424c2018-12-07 15:09:13 +0100276 private final boolean mUseMotionSensor;
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700277 private Sensor mMotionSensor;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700278 private LocationRequest mLocationRequest;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700279 private Intent mIdleIntent;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700280 private Intent mLightIdleIntent;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700281 private AnyMotionDetector mAnyMotionDetector;
Makoto Onukie4918212018-02-06 11:30:15 -0800282 private final AppStateTracker mAppStateTracker;
Dianne Hackbornb6843652016-02-22 12:20:13 -0800283 private boolean mLightEnabled;
284 private boolean mDeepEnabled;
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700285 private boolean mQuickDozeActivated;
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700286 private boolean mForceIdle;
Dianne Hackborn88c41352016-04-07 15:18:58 -0700287 private boolean mNetworkConnected;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700288 private boolean mScreenOn;
289 private boolean mCharging;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700290 private boolean mNotMoving;
291 private boolean mLocating;
292 private boolean mLocated;
Joe LaPenna23d681b2015-08-27 15:12:11 -0700293 private boolean mHasGps;
294 private boolean mHasNetworkLocation;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700295 private Location mLastGenericLocation;
296 private Location mLastGpsLocation;
Amith Yamasani396a10c2018-01-19 10:58:07 -0800297 // Current locked state of the screen
298 private boolean mScreenLocked;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700299
300 /** Device is currently active. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700301 @VisibleForTesting
302 static final int STATE_ACTIVE = 0;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700303 /** Device is inactive (screen off, no motion) and we are waiting to for idle. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700304 @VisibleForTesting
305 static final int STATE_INACTIVE = 1;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700306 /** Device is past the initial inactive period, and waiting for the next idle period. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700307 @VisibleForTesting
308 static final int STATE_IDLE_PENDING = 2;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700309 /** Device is currently sensing motion. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700310 @VisibleForTesting
311 static final int STATE_SENSING = 3;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700312 /** Device is currently finding location (and may still be sensing). */
Kweku Adams00e3a372018-09-28 16:57:09 -0700313 @VisibleForTesting
314 static final int STATE_LOCATING = 4;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700315 /** Device is in the idle state, trying to stay asleep as much as possible. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700316 @VisibleForTesting
317 static final int STATE_IDLE = 5;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700318 /** Device is in the idle state, but temporarily out of idle to do regular maintenance. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700319 @VisibleForTesting
320 static final int STATE_IDLE_MAINTENANCE = 6;
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700321 /**
322 * Device is inactive and should go straight into idle (foregoing motion and location
323 * monitoring), but allow some time for current work to complete first.
324 */
325 @VisibleForTesting
326 static final int STATE_QUICK_DOZE_DELAY = 7;
Amith Yamasani396a10c2018-01-19 10:58:07 -0800327
Kweku Adams00e3a372018-09-28 16:57:09 -0700328 @VisibleForTesting
329 static String stateToString(int state) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700330 switch (state) {
331 case STATE_ACTIVE: return "ACTIVE";
332 case STATE_INACTIVE: return "INACTIVE";
333 case STATE_IDLE_PENDING: return "IDLE_PENDING";
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700334 case STATE_SENSING: return "SENSING";
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700335 case STATE_LOCATING: return "LOCATING";
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700336 case STATE_IDLE: return "IDLE";
337 case STATE_IDLE_MAINTENANCE: return "IDLE_MAINTENANCE";
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700338 case STATE_QUICK_DOZE_DELAY: return "QUICK_DOZE_DELAY";
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700339 default: return Integer.toString(state);
340 }
341 }
342
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700343 /** Device is currently active. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700344 @VisibleForTesting
345 static final int LIGHT_STATE_ACTIVE = 0;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700346 /** Device is inactive (screen off) and we are waiting to for the first light idle. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700347 @VisibleForTesting
348 static final int LIGHT_STATE_INACTIVE = 1;
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700349 /** Device is about to go idle for the first time, wait for current work to complete. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700350 @VisibleForTesting
351 static final int LIGHT_STATE_PRE_IDLE = 3;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700352 /** Device is in the light idle state, trying to stay asleep as much as possible. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700353 @VisibleForTesting
354 static final int LIGHT_STATE_IDLE = 4;
Dianne Hackborn88c41352016-04-07 15:18:58 -0700355 /** Device is in the light idle state, we want to go in to idle maintenance but are
356 * waiting for network connectivity before doing so. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700357 @VisibleForTesting
358 static final int LIGHT_STATE_WAITING_FOR_NETWORK = 5;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700359 /** Device is in the light idle state, but temporarily out of idle to do regular maintenance. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700360 @VisibleForTesting
361 static final int LIGHT_STATE_IDLE_MAINTENANCE = 6;
Dianne Hackbornb6843652016-02-22 12:20:13 -0800362 /** Device light idle state is overriden, now applying deep doze state. */
Kweku Adams00e3a372018-09-28 16:57:09 -0700363 @VisibleForTesting
364 static final int LIGHT_STATE_OVERRIDE = 7;
365
366 @VisibleForTesting
367 static String lightStateToString(int state) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700368 switch (state) {
369 case LIGHT_STATE_ACTIVE: return "ACTIVE";
370 case LIGHT_STATE_INACTIVE: return "INACTIVE";
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700371 case LIGHT_STATE_PRE_IDLE: return "PRE_IDLE";
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700372 case LIGHT_STATE_IDLE: return "IDLE";
Dianne Hackborn88c41352016-04-07 15:18:58 -0700373 case LIGHT_STATE_WAITING_FOR_NETWORK: return "WAITING_FOR_NETWORK";
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700374 case LIGHT_STATE_IDLE_MAINTENANCE: return "IDLE_MAINTENANCE";
375 case LIGHT_STATE_OVERRIDE: return "OVERRIDE";
376 default: return Integer.toString(state);
377 }
378 }
379
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700380 private int mState;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700381 private int mLightState;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700382
383 private long mInactiveTimeout;
384 private long mNextAlarmTime;
385 private long mNextIdlePendingDelay;
386 private long mNextIdleDelay;
Dianne Hackborn953fc942016-03-29 15:36:24 -0700387 private long mNextLightIdleDelay;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700388 private long mNextLightAlarmTime;
Kevin Gabayan92f15e62016-04-04 17:52:22 -0700389 private long mNextSensingTimeoutAlarmTime;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800390 private long mCurIdleBudget;
391 private long mMaintenanceStartTime;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700392
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800393 private int mActiveIdleOpCount;
Joe Onorato8f0e9ced2016-12-08 17:48:49 -0800394 private PowerManager.WakeLock mActiveIdleWakeLock; // held when there are operations in progress
395 private PowerManager.WakeLock mGoingIdleWakeLock; // held when we are going idle so hardware
396 // (especially NetworkPolicyManager) can shut
397 // down.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800398 private boolean mJobsActive;
399 private boolean mAlarmsActive;
Yao Chenca5edbb2016-01-13 14:44:36 -0800400 private boolean mReportedMaintenanceActivity;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800401
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700402 public final AtomicFile mConfigFile;
403
Yao Chenca5edbb2016-01-13 14:44:36 -0800404 private final RemoteCallbackList<IMaintenanceActivityListener> mMaintenanceActivityListeners =
405 new RemoteCallbackList<IMaintenanceActivityListener>();
406
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700407 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700408 * Package names the system has white-listed to opt out of power save restrictions,
409 * except for device idle mode.
410 */
411 private final ArrayMap<String, Integer> mPowerSaveWhitelistAppsExceptIdle = new ArrayMap<>();
412
413 /**
Sudheer Shanka3f4d7702017-04-28 17:38:03 -0700414 * Package names the user has white-listed using commandline option to opt out of
415 * power save restrictions, except for device idle mode.
416 */
417 private final ArraySet<String> mPowerSaveWhitelistUserAppsExceptIdle = new ArraySet<>();
418
419 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700420 * Package names the system has white-listed to opt out of power save restrictions for
421 * all modes.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700422 */
423 private final ArrayMap<String, Integer> mPowerSaveWhitelistApps = new ArrayMap<>();
424
425 /**
426 * Package names the user has white-listed to opt out of power save restrictions.
427 */
428 private final ArrayMap<String, Integer> mPowerSaveWhitelistUserApps = new ArrayMap<>();
429
430 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700431 * App IDs of built-in system apps that have been white-listed except for idle modes.
432 */
433 private final SparseBooleanArray mPowerSaveWhitelistSystemAppIdsExceptIdle
434 = new SparseBooleanArray();
435
436 /**
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700437 * App IDs of built-in system apps that have been white-listed.
438 */
439 private final SparseBooleanArray mPowerSaveWhitelistSystemAppIds = new SparseBooleanArray();
440
441 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700442 * App IDs that have been white-listed to opt out of power save restrictions, except
443 * for device idle modes.
444 */
445 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
446
447 /**
448 * Current app IDs that are in the complete power save white list, but shouldn't be
449 * excluded from idle modes. This array can be shared with others because it will not be
450 * modified once set.
451 */
452 private int[] mPowerSaveWhitelistExceptIdleAppIdArray = new int[0];
453
454 /**
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700455 * App IDs that have been white-listed to opt out of power save restrictions.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700456 */
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700457 private final SparseBooleanArray mPowerSaveWhitelistAllAppIds = new SparseBooleanArray();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700458
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700459 /**
460 * Current app IDs that are in the complete power save white list. This array can
461 * be shared with others because it will not be modified once set.
462 */
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700463 private int[] mPowerSaveWhitelistAllAppIdArray = new int[0];
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700464
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700465 /**
Dianne Hackborn262ae5c2016-02-10 16:28:29 -0800466 * App IDs that have been white-listed by the user to opt out of power save restrictions.
467 */
468 private final SparseBooleanArray mPowerSaveWhitelistUserAppIds = new SparseBooleanArray();
469
470 /**
471 * Current app IDs that are in the user power save white list. This array can
472 * be shared with others because it will not be modified once set.
473 */
474 private int[] mPowerSaveWhitelistUserAppIdArray = new int[0];
475
476 /**
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700477 * List of end times for UIDs that are temporarily marked as being allowed to access
478 * the network and acquire wakelocks. Times are in milliseconds.
479 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700480 private final SparseArray<Pair<MutableLong, String>> mTempWhitelistAppIdEndTimes
481 = new SparseArray<>();
482
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -0700483 private NetworkPolicyManagerInternal mNetworkPolicyManagerInternal;
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700484
485 /**
486 * Current app IDs of temporarily whitelist apps for high-priority messages.
487 */
488 private int[] mTempWhitelistAppIdArray = new int[0];
489
Suprabh Shukla08105642017-09-26 14:45:30 -0700490 /**
491 * Apps in the system whitelist that have been taken out (probably because the user wanted to).
492 * They can be restored back by calling restoreAppToSystemWhitelist(String).
493 */
494 private ArrayMap<String, Integer> mRemovedFromSystemWhitelistApps = new ArrayMap<>();
495
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800496 private static final int EVENT_NULL = 0;
497 private static final int EVENT_NORMAL = 1;
498 private static final int EVENT_LIGHT_IDLE = 2;
499 private static final int EVENT_LIGHT_MAINTENANCE = 3;
Dianne Hackbornb6843652016-02-22 12:20:13 -0800500 private static final int EVENT_DEEP_IDLE = 4;
501 private static final int EVENT_DEEP_MAINTENANCE = 5;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800502
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -0700503 private final int[] mEventCmds = new int[EVENT_BUFFER_SIZE];
504 private final long[] mEventTimes = new long[EVENT_BUFFER_SIZE];
Amith Yamasaniac6517a2018-04-23 12:19:34 -0700505 private final String[] mEventReasons = new String[EVENT_BUFFER_SIZE];
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800506
Amith Yamasaniac6517a2018-04-23 12:19:34 -0700507 private void addEvent(int cmd, String reason) {
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800508 if (mEventCmds[0] != cmd) {
509 System.arraycopy(mEventCmds, 0, mEventCmds, 1, EVENT_BUFFER_SIZE - 1);
510 System.arraycopy(mEventTimes, 0, mEventTimes, 1, EVENT_BUFFER_SIZE - 1);
Amith Yamasaniac6517a2018-04-23 12:19:34 -0700511 System.arraycopy(mEventReasons, 0, mEventReasons, 1, EVENT_BUFFER_SIZE - 1);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800512 mEventCmds[0] = cmd;
513 mEventTimes[0] = SystemClock.elapsedRealtime();
Amith Yamasaniac6517a2018-04-23 12:19:34 -0700514 mEventReasons[0] = reason;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800515 }
516 }
517
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700518 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
519 @Override public void onReceive(Context context, Intent intent) {
Dianne Hackborn88c41352016-04-07 15:18:58 -0700520 switch (intent.getAction()) {
521 case ConnectivityManager.CONNECTIVITY_ACTION: {
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -0700522 updateConnectivityState(intent);
Dianne Hackborn88c41352016-04-07 15:18:58 -0700523 } break;
524 case Intent.ACTION_BATTERY_CHANGED: {
Robin Lee204cb222018-12-07 15:17:44 +0100525 boolean present = intent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
526 boolean plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0;
Dianne Hackborn88c41352016-04-07 15:18:58 -0700527 synchronized (DeviceIdleController.this) {
Robin Lee204cb222018-12-07 15:17:44 +0100528 updateChargingLocked(present && plugged);
Dianne Hackborn88c41352016-04-07 15:18:58 -0700529 }
530 } break;
531 case Intent.ACTION_PACKAGE_REMOVED: {
532 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
533 Uri data = intent.getData();
534 String ssp;
535 if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
536 removePowerSaveWhitelistAppInternal(ssp);
537 }
538 }
539 } break;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700540 }
541 }
542 };
543
544 private final AlarmManager.OnAlarmListener mLightAlarmListener
545 = new AlarmManager.OnAlarmListener() {
546 @Override
547 public void onAlarm() {
548 synchronized (DeviceIdleController.this) {
549 stepLightIdleStateLocked("s:alarm");
550 }
551 }
552 };
553
Kevin Gabayan92f15e62016-04-04 17:52:22 -0700554 private final AlarmManager.OnAlarmListener mSensingTimeoutAlarmListener
555 = new AlarmManager.OnAlarmListener() {
556 @Override
557 public void onAlarm() {
558 if (mState == STATE_SENSING) {
559 synchronized (DeviceIdleController.this) {
Kweku Adams00e3a372018-09-28 16:57:09 -0700560 // Restart the device idle progression in case the device moved but the screen
561 // didn't turn on.
Kevin Gabayan92f15e62016-04-04 17:52:22 -0700562 becomeInactiveIfAppropriateLocked();
563 }
564 }
565 }
566 };
567
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700568 private final AlarmManager.OnAlarmListener mDeepAlarmListener
569 = new AlarmManager.OnAlarmListener() {
570 @Override
571 public void onAlarm() {
572 synchronized (DeviceIdleController.this) {
573 stepIdleStateLocked("s:alarm");
574 }
575 }
576 };
577
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800578 private final BroadcastReceiver mIdleStartedDoneReceiver = new BroadcastReceiver() {
579 @Override public void onReceive(Context context, Intent intent) {
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700580 // When coming out of a deep idle, we will add in some delay before we allow
581 // the system to settle down and finish the maintenance window. This is
582 // to give a chance for any pending work to be scheduled.
583 if (PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED.equals(intent.getAction())) {
584 mHandler.sendEmptyMessageDelayed(MSG_FINISH_IDLE_OP,
585 mConstants.MIN_DEEP_MAINTENANCE_TIME);
586 } else {
587 mHandler.sendEmptyMessageDelayed(MSG_FINISH_IDLE_OP,
588 mConstants.MIN_LIGHT_MAINTENANCE_TIME);
589 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800590 }
591 };
592
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -0700593 private final BroadcastReceiver mInteractivityReceiver = new BroadcastReceiver() {
594 @Override
595 public void onReceive(Context context, Intent intent) {
Dianne Hackborn9b5ebc92017-09-08 13:45:35 -0700596 synchronized (DeviceIdleController.this) {
597 updateInteractivityLocked();
598 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700599 }
600 };
601
Kweku Adams00e3a372018-09-28 16:57:09 -0700602 @VisibleForTesting
603 final class MotionListener extends TriggerEventListener
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700604 implements SensorEventListener {
605
606 boolean active = false;
607
Kweku Adams00e3a372018-09-28 16:57:09 -0700608 public boolean isActive() {
609 return active;
610 }
611
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700612 @Override
613 public void onTrigger(TriggerEvent event) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700614 synchronized (DeviceIdleController.this) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700615 active = false;
616 motionLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700617 }
618 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700619
620 @Override
621 public void onSensorChanged(SensorEvent event) {
622 synchronized (DeviceIdleController.this) {
623 mSensorManager.unregisterListener(this, mMotionSensor);
624 active = false;
625 motionLocked();
626 }
627 }
628
629 @Override
630 public void onAccuracyChanged(Sensor sensor, int accuracy) {}
631
632 public boolean registerLocked() {
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700633 boolean success;
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700634 if (mMotionSensor.getReportingMode() == Sensor.REPORTING_MODE_ONE_SHOT) {
635 success = mSensorManager.requestTriggerSensor(mMotionListener, mMotionSensor);
636 } else {
637 success = mSensorManager.registerListener(
638 mMotionListener, mMotionSensor, SensorManager.SENSOR_DELAY_NORMAL);
639 }
640 if (success) {
641 active = true;
642 } else {
643 Slog.e(TAG, "Unable to register for " + mMotionSensor);
644 }
645 return success;
646 }
647
648 public void unregisterLocked() {
649 if (mMotionSensor.getReportingMode() == Sensor.REPORTING_MODE_ONE_SHOT) {
650 mSensorManager.cancelTriggerSensor(mMotionListener, mMotionSensor);
651 } else {
652 mSensorManager.unregisterListener(mMotionListener);
653 }
654 active = false;
655 }
656 }
Kweku Adams00e3a372018-09-28 16:57:09 -0700657 @VisibleForTesting final MotionListener mMotionListener = new MotionListener();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700658
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700659 private final LocationListener mGenericLocationListener = new LocationListener() {
660 @Override
661 public void onLocationChanged(Location location) {
662 synchronized (DeviceIdleController.this) {
663 receivedGenericLocationLocked(location);
664 }
665 }
666
667 @Override
668 public void onStatusChanged(String provider, int status, Bundle extras) {
669 }
670
671 @Override
672 public void onProviderEnabled(String provider) {
673 }
674
675 @Override
676 public void onProviderDisabled(String provider) {
677 }
678 };
679
680 private final LocationListener mGpsLocationListener = new LocationListener() {
681 @Override
682 public void onLocationChanged(Location location) {
683 synchronized (DeviceIdleController.this) {
684 receivedGpsLocationLocked(location);
685 }
686 }
687
688 @Override
689 public void onStatusChanged(String provider, int status, Bundle extras) {
690 }
691
692 @Override
693 public void onProviderEnabled(String provider) {
694 }
695
696 @Override
697 public void onProviderDisabled(String provider) {
698 }
699 };
700
Adam Lesinski31c05d12015-06-09 17:34:04 -0700701 /**
702 * All times are in milliseconds. These constants are kept synchronized with the system
703 * global Settings. Any access to this class or its fields should be done while
704 * holding the DeviceIdleController lock.
705 */
Kweku Adamsa457f4e2018-10-03 15:56:06 -0700706 @VisibleForTesting
707 final class Constants extends ContentObserver {
Adam Lesinski31c05d12015-06-09 17:34:04 -0700708 // Key names stored in the settings value.
Dianne Hackborn953fc942016-03-29 15:36:24 -0700709 private static final String KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT
710 = "light_after_inactive_to";
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700711 private static final String KEY_LIGHT_PRE_IDLE_TIMEOUT = "light_pre_idle_to";
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700712 private static final String KEY_LIGHT_IDLE_TIMEOUT = "light_idle_to";
Dianne Hackborn953fc942016-03-29 15:36:24 -0700713 private static final String KEY_LIGHT_IDLE_FACTOR = "light_idle_factor";
714 private static final String KEY_LIGHT_MAX_IDLE_TIMEOUT = "light_max_idle_to";
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800715 private static final String KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET
716 = "light_idle_maintenance_min_budget";
717 private static final String KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET
718 = "light_idle_maintenance_max_budget";
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700719 private static final String KEY_MIN_LIGHT_MAINTENANCE_TIME = "min_light_maintenance_time";
720 private static final String KEY_MIN_DEEP_MAINTENANCE_TIME = "min_deep_maintenance_time";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700721 private static final String KEY_INACTIVE_TIMEOUT = "inactive_to";
722 private static final String KEY_SENSING_TIMEOUT = "sensing_to";
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700723 private static final String KEY_LOCATING_TIMEOUT = "locating_to";
724 private static final String KEY_LOCATION_ACCURACY = "location_accuracy";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700725 private static final String KEY_MOTION_INACTIVE_TIMEOUT = "motion_inactive_to";
726 private static final String KEY_IDLE_AFTER_INACTIVE_TIMEOUT = "idle_after_inactive_to";
727 private static final String KEY_IDLE_PENDING_TIMEOUT = "idle_pending_to";
728 private static final String KEY_MAX_IDLE_PENDING_TIMEOUT = "max_idle_pending_to";
729 private static final String KEY_IDLE_PENDING_FACTOR = "idle_pending_factor";
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700730 private static final String KEY_QUICK_DOZE_DELAY_TIMEOUT = "quick_doze_delay_to";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700731 private static final String KEY_IDLE_TIMEOUT = "idle_to";
732 private static final String KEY_MAX_IDLE_TIMEOUT = "max_idle_to";
733 private static final String KEY_IDLE_FACTOR = "idle_factor";
734 private static final String KEY_MIN_TIME_TO_ALARM = "min_time_to_alarm";
735 private static final String KEY_MAX_TEMP_APP_WHITELIST_DURATION =
736 "max_temp_app_whitelist_duration";
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700737 private static final String KEY_MMS_TEMP_APP_WHITELIST_DURATION =
738 "mms_temp_app_whitelist_duration";
Dianne Hackborn451c3462015-07-21 17:39:46 -0700739 private static final String KEY_SMS_TEMP_APP_WHITELIST_DURATION =
740 "sms_temp_app_whitelist_duration";
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700741 private static final String KEY_NOTIFICATION_WHITELIST_DURATION =
742 "notification_whitelist_duration";
Amith Yamasani396a10c2018-01-19 10:58:07 -0800743 /**
744 * Whether to wait for the user to unlock the device before causing screen-on to
745 * exit doze. Default = true
746 */
747 private static final String KEY_WAIT_FOR_UNLOCK = "wait_for_unlock";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700748
749 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700750 * This is the time, after becoming inactive, that we go in to the first
751 * light-weight idle mode.
752 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
753 * @see #KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT
754 */
755 public long LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT;
756
757 /**
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700758 * This is amount of time we will wait from the point where we decide we would
759 * like to go idle until we actually do, while waiting for jobs and other current
760 * activity to finish.
761 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
762 * @see #KEY_LIGHT_PRE_IDLE_TIMEOUT
763 */
764 public long LIGHT_PRE_IDLE_TIMEOUT;
765
766 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700767 * This is the initial time that we will run in idle maintenance mode.
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700768 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
769 * @see #KEY_LIGHT_IDLE_TIMEOUT
770 */
771 public long LIGHT_IDLE_TIMEOUT;
772
773 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700774 * Scaling factor to apply to the light idle mode time each time we complete a cycle.
775 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
776 * @see #KEY_LIGHT_IDLE_FACTOR
777 */
778 public float LIGHT_IDLE_FACTOR;
779
780 /**
Kweku Adams00e3a372018-09-28 16:57:09 -0700781 * This is the maximum time we will run in idle maintenance mode.
Dianne Hackborn953fc942016-03-29 15:36:24 -0700782 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
783 * @see #KEY_LIGHT_MAX_IDLE_TIMEOUT
784 */
785 public long LIGHT_MAX_IDLE_TIMEOUT;
786
787 /**
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800788 * This is the minimum amount of time we want to make available for maintenance mode
789 * when lightly idling. That is, we will always have at least this amount of time
790 * available maintenance before timing out and cutting off maintenance mode.
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700791 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800792 * @see #KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700793 */
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800794 public long LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
795
796 /**
797 * This is the maximum amount of time we want to make available for maintenance mode
798 * when lightly idling. That is, if the system isn't using up its minimum maintenance
799 * budget and this time is being added to the budget reserve, this is the maximum
800 * reserve size we will allow to grow and thus the maximum amount of time we will
801 * allow for the maintenance window.
802 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
803 * @see #KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET
804 */
805 public long LIGHT_IDLE_MAINTENANCE_MAX_BUDGET;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700806
807 /**
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700808 * This is the minimum amount of time that we will stay in maintenance mode after
809 * a light doze. We have this minimum to allow various things to respond to switching
810 * in to maintenance mode and scheduling their work -- otherwise we may
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700811 * see there is nothing to do (no jobs pending) and go out of maintenance
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700812 * mode immediately.
813 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
814 * @see #KEY_MIN_LIGHT_MAINTENANCE_TIME
815 */
816 public long MIN_LIGHT_MAINTENANCE_TIME;
817
818 /**
819 * This is the minimum amount of time that we will stay in maintenance mode after
820 * a full doze. We have this minimum to allow various things to respond to switching
821 * in to maintenance mode and scheduling their work -- otherwise we may
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700822 * see there is nothing to do (no jobs pending) and go out of maintenance
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700823 * mode immediately.
824 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
825 * @see #KEY_MIN_DEEP_MAINTENANCE_TIME
826 */
827 public long MIN_DEEP_MAINTENANCE_TIME;
828
829 /**
Adam Lesinski31c05d12015-06-09 17:34:04 -0700830 * This is the time, after becoming inactive, at which we start looking at the
831 * motion sensor to determine if the device is being left alone. We don't do this
832 * immediately after going inactive just because we don't want to be continually running
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700833 * the motion sensor whenever the screen is off.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700834 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
835 * @see #KEY_INACTIVE_TIMEOUT
836 */
837 public long INACTIVE_TIMEOUT;
838
839 /**
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700840 * If we don't receive a callback from AnyMotion in this amount of time +
841 * {@link #LOCATING_TIMEOUT}, we will change from
Adam Lesinski31c05d12015-06-09 17:34:04 -0700842 * STATE_SENSING to STATE_INACTIVE, and any AnyMotion callbacks while not in STATE_SENSING
843 * will be ignored.
844 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
845 * @see #KEY_SENSING_TIMEOUT
846 */
847 public long SENSING_TIMEOUT;
848
849 /**
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700850 * This is how long we will wait to try to get a good location fix before going in to
851 * idle mode.
852 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
853 * @see #KEY_LOCATING_TIMEOUT
854 */
855 public long LOCATING_TIMEOUT;
856
857 /**
858 * The desired maximum accuracy (in meters) we consider the location to be good enough to go
859 * on to idle. We will be trying to get an accuracy fix at least this good or until
860 * {@link #LOCATING_TIMEOUT} expires.
861 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
862 * @see #KEY_LOCATION_ACCURACY
863 */
864 public float LOCATION_ACCURACY;
865
866 /**
Adam Lesinski31c05d12015-06-09 17:34:04 -0700867 * This is the time, after seeing motion, that we wait after becoming inactive from
868 * that until we start looking for motion again.
869 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
870 * @see #KEY_MOTION_INACTIVE_TIMEOUT
871 */
872 public long MOTION_INACTIVE_TIMEOUT;
873
874 /**
875 * This is the time, after the inactive timeout elapses, that we will wait looking
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700876 * for motion until we truly consider the device to be idle.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700877 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
878 * @see #KEY_IDLE_AFTER_INACTIVE_TIMEOUT
879 */
880 public long IDLE_AFTER_INACTIVE_TIMEOUT;
881
882 /**
883 * This is the initial time, after being idle, that we will allow ourself to be back
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700884 * in the IDLE_MAINTENANCE state allowing the system to run normally until we return to
885 * idle.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700886 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
887 * @see #KEY_IDLE_PENDING_TIMEOUT
888 */
889 public long IDLE_PENDING_TIMEOUT;
890
891 /**
892 * Maximum pending idle timeout (time spent running) we will be allowed to use.
893 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
894 * @see #KEY_MAX_IDLE_PENDING_TIMEOUT
895 */
896 public long MAX_IDLE_PENDING_TIMEOUT;
897
898 /**
899 * Scaling factor to apply to current pending idle timeout each time we cycle through
900 * that state.
901 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
902 * @see #KEY_IDLE_PENDING_FACTOR
903 */
904 public float IDLE_PENDING_FACTOR;
905
906 /**
Kweku Adamsb396ccf2018-09-17 16:37:15 -0700907 * This is amount of time we will wait from the point where we go into
908 * STATE_QUICK_DOZE_DELAY until we actually go into STATE_IDLE, while waiting for jobs
909 * and other current activity to finish.
910 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
911 * @see #KEY_QUICK_DOZE_DELAY_TIMEOUT
912 */
913 public long QUICK_DOZE_DELAY_TIMEOUT;
914
915 /**
Adam Lesinski31c05d12015-06-09 17:34:04 -0700916 * This is the initial time that we want to sit in the idle state before waking up
917 * again to return to pending idle and allowing normal work to run.
918 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
919 * @see #KEY_IDLE_TIMEOUT
920 */
921 public long IDLE_TIMEOUT;
922
923 /**
924 * Maximum idle duration we will be allowed to use.
925 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
926 * @see #KEY_MAX_IDLE_TIMEOUT
927 */
928 public long MAX_IDLE_TIMEOUT;
929
930 /**
931 * Scaling factor to apply to current idle timeout each time we cycle through that state.
932 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
933 * @see #KEY_IDLE_FACTOR
934 */
935 public float IDLE_FACTOR;
936
937 /**
938 * This is the minimum time we will allow until the next upcoming alarm for us to
939 * actually go in to idle mode.
940 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
941 * @see #KEY_MIN_TIME_TO_ALARM
942 */
943 public long MIN_TIME_TO_ALARM;
944
945 /**
946 * Max amount of time to temporarily whitelist an app when it receives a high priority
947 * tickle.
948 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
949 * @see #KEY_MAX_TEMP_APP_WHITELIST_DURATION
950 */
951 public long MAX_TEMP_APP_WHITELIST_DURATION;
952
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700953 /**
954 * Amount of time we would like to whitelist an app that is receiving an MMS.
955 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
956 * @see #KEY_MMS_TEMP_APP_WHITELIST_DURATION
957 */
958 public long MMS_TEMP_APP_WHITELIST_DURATION;
959
Dianne Hackborn451c3462015-07-21 17:39:46 -0700960 /**
961 * Amount of time we would like to whitelist an app that is receiving an SMS.
962 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
963 * @see #KEY_SMS_TEMP_APP_WHITELIST_DURATION
964 */
965 public long SMS_TEMP_APP_WHITELIST_DURATION;
966
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700967 /**
968 * Amount of time we would like to whitelist an app that is handling a
969 * {@link android.app.PendingIntent} triggered by a {@link android.app.Notification}.
970 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
971 * @see #KEY_NOTIFICATION_WHITELIST_DURATION
972 */
973 public long NOTIFICATION_WHITELIST_DURATION;
974
Amith Yamasani396a10c2018-01-19 10:58:07 -0800975 public boolean WAIT_FOR_UNLOCK;
976
Adam Lesinski31c05d12015-06-09 17:34:04 -0700977 private final ContentResolver mResolver;
shreerag597da8a2017-07-21 14:24:14 -0700978 private final boolean mSmallBatteryDevice;
Adam Lesinski31c05d12015-06-09 17:34:04 -0700979 private final KeyValueListParser mParser = new KeyValueListParser(',');
980
981 public Constants(Handler handler, ContentResolver resolver) {
982 super(handler);
983 mResolver = resolver;
shreerag597da8a2017-07-21 14:24:14 -0700984 mSmallBatteryDevice = ActivityManager.isSmallBatteryDevice();
985 mResolver.registerContentObserver(
986 Settings.Global.getUriFor(Settings.Global.DEVICE_IDLE_CONSTANTS),
Joe LaPennaf33b5bf2016-03-23 15:19:47 -0700987 false, this);
Adam Lesinski31c05d12015-06-09 17:34:04 -0700988 updateConstants();
989 }
990
991 @Override
992 public void onChange(boolean selfChange, Uri uri) {
993 updateConstants();
994 }
995
996 private void updateConstants() {
997 synchronized (DeviceIdleController.this) {
998 try {
999 mParser.setString(Settings.Global.getString(mResolver,
shreerag597da8a2017-07-21 14:24:14 -07001000 Settings.Global.DEVICE_IDLE_CONSTANTS));
Adam Lesinski31c05d12015-06-09 17:34:04 -07001001 } catch (IllegalArgumentException e) {
1002 // Failed to parse the settings string, log this and move on
1003 // with defaults.
1004 Slog.e(TAG, "Bad device idle settings", e);
1005 }
1006
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001007 LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT = mParser.getDurationMillis(
Dianne Hackborn953fc942016-03-29 15:36:24 -07001008 KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT,
Suprabh Shukla85fff7d2018-05-08 17:39:24 -07001009 !COMPRESS_TIME ? 3 * 60 * 1000L : 15 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001010 LIGHT_PRE_IDLE_TIMEOUT = mParser.getDurationMillis(KEY_LIGHT_PRE_IDLE_TIMEOUT,
Suprabh Shukla85fff7d2018-05-08 17:39:24 -07001011 !COMPRESS_TIME ? 3 * 60 * 1000L : 30 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001012 LIGHT_IDLE_TIMEOUT = mParser.getDurationMillis(KEY_LIGHT_IDLE_TIMEOUT,
Dianne Hackborn953fc942016-03-29 15:36:24 -07001013 !COMPRESS_TIME ? 5 * 60 * 1000L : 15 * 1000L);
1014 LIGHT_IDLE_FACTOR = mParser.getFloat(KEY_LIGHT_IDLE_FACTOR,
1015 2f);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001016 LIGHT_MAX_IDLE_TIMEOUT = mParser.getDurationMillis(KEY_LIGHT_MAX_IDLE_TIMEOUT,
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001017 !COMPRESS_TIME ? 15 * 60 * 1000L : 60 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001018 LIGHT_IDLE_MAINTENANCE_MIN_BUDGET = mParser.getDurationMillis(
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001019 KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET,
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001020 !COMPRESS_TIME ? 1 * 60 * 1000L : 15 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001021 LIGHT_IDLE_MAINTENANCE_MAX_BUDGET = mParser.getDurationMillis(
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001022 KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET,
1023 !COMPRESS_TIME ? 5 * 60 * 1000L : 30 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001024 MIN_LIGHT_MAINTENANCE_TIME = mParser.getDurationMillis(
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07001025 KEY_MIN_LIGHT_MAINTENANCE_TIME,
1026 !COMPRESS_TIME ? 5 * 1000L : 1 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001027 MIN_DEEP_MAINTENANCE_TIME = mParser.getDurationMillis(
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07001028 KEY_MIN_DEEP_MAINTENANCE_TIME,
1029 !COMPRESS_TIME ? 30 * 1000L : 5 * 1000L);
Michael Kwan88871462017-08-21 13:13:37 -07001030 long inactiveTimeoutDefault = (mSmallBatteryDevice ? 15 : 30) * 60 * 1000L;
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001031 INACTIVE_TIMEOUT = mParser.getDurationMillis(KEY_INACTIVE_TIMEOUT,
Joe LaPenna0c5d3e92016-03-24 13:29:56 -07001032 !COMPRESS_TIME ? inactiveTimeoutDefault : (inactiveTimeoutDefault / 10));
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001033 SENSING_TIMEOUT = mParser.getDurationMillis(KEY_SENSING_TIMEOUT,
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001034 !DEBUG ? 4 * 60 * 1000L : 60 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001035 LOCATING_TIMEOUT = mParser.getDurationMillis(KEY_LOCATING_TIMEOUT,
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001036 !DEBUG ? 30 * 1000L : 15 * 1000L);
1037 LOCATION_ACCURACY = mParser.getFloat(KEY_LOCATION_ACCURACY, 20);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001038 MOTION_INACTIVE_TIMEOUT = mParser.getDurationMillis(KEY_MOTION_INACTIVE_TIMEOUT,
Adam Lesinski31c05d12015-06-09 17:34:04 -07001039 !COMPRESS_TIME ? 10 * 60 * 1000L : 60 * 1000L);
Michael Kwan88871462017-08-21 13:13:37 -07001040 long idleAfterInactiveTimeout = (mSmallBatteryDevice ? 15 : 30) * 60 * 1000L;
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001041 IDLE_AFTER_INACTIVE_TIMEOUT = mParser.getDurationMillis(
1042 KEY_IDLE_AFTER_INACTIVE_TIMEOUT,
Joe LaPenna0c5d3e92016-03-24 13:29:56 -07001043 !COMPRESS_TIME ? idleAfterInactiveTimeout
1044 : (idleAfterInactiveTimeout / 10));
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001045 IDLE_PENDING_TIMEOUT = mParser.getDurationMillis(KEY_IDLE_PENDING_TIMEOUT,
Adam Lesinski31c05d12015-06-09 17:34:04 -07001046 !COMPRESS_TIME ? 5 * 60 * 1000L : 30 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001047 MAX_IDLE_PENDING_TIMEOUT = mParser.getDurationMillis(KEY_MAX_IDLE_PENDING_TIMEOUT,
Adam Lesinski31c05d12015-06-09 17:34:04 -07001048 !COMPRESS_TIME ? 10 * 60 * 1000L : 60 * 1000L);
1049 IDLE_PENDING_FACTOR = mParser.getFloat(KEY_IDLE_PENDING_FACTOR,
1050 2f);
Kweku Adamsb396ccf2018-09-17 16:37:15 -07001051 QUICK_DOZE_DELAY_TIMEOUT = mParser.getDurationMillis(
1052 KEY_QUICK_DOZE_DELAY_TIMEOUT, !COMPRESS_TIME ? 60 * 1000L : 15 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001053 IDLE_TIMEOUT = mParser.getDurationMillis(KEY_IDLE_TIMEOUT,
Adam Lesinski31c05d12015-06-09 17:34:04 -07001054 !COMPRESS_TIME ? 60 * 60 * 1000L : 6 * 60 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001055 MAX_IDLE_TIMEOUT = mParser.getDurationMillis(KEY_MAX_IDLE_TIMEOUT,
Adam Lesinski31c05d12015-06-09 17:34:04 -07001056 !COMPRESS_TIME ? 6 * 60 * 60 * 1000L : 30 * 60 * 1000L);
1057 IDLE_FACTOR = mParser.getFloat(KEY_IDLE_FACTOR,
1058 2f);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001059 MIN_TIME_TO_ALARM = mParser.getDurationMillis(KEY_MIN_TIME_TO_ALARM,
Adam Lesinski31c05d12015-06-09 17:34:04 -07001060 !COMPRESS_TIME ? 60 * 60 * 1000L : 6 * 60 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001061 MAX_TEMP_APP_WHITELIST_DURATION = mParser.getDurationMillis(
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001062 KEY_MAX_TEMP_APP_WHITELIST_DURATION, 5 * 60 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001063 MMS_TEMP_APP_WHITELIST_DURATION = mParser.getDurationMillis(
Dianne Hackborn0b6134b2015-07-14 18:48:07 -07001064 KEY_MMS_TEMP_APP_WHITELIST_DURATION, 60 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001065 SMS_TEMP_APP_WHITELIST_DURATION = mParser.getDurationMillis(
Dianne Hackborn451c3462015-07-21 17:39:46 -07001066 KEY_SMS_TEMP_APP_WHITELIST_DURATION, 20 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001067 NOTIFICATION_WHITELIST_DURATION = mParser.getDurationMillis(
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001068 KEY_NOTIFICATION_WHITELIST_DURATION, 30 * 1000L);
Amith Yamasani396a10c2018-01-19 10:58:07 -08001069 WAIT_FOR_UNLOCK = mParser.getBoolean(KEY_WAIT_FOR_UNLOCK, false);
Adam Lesinski31c05d12015-06-09 17:34:04 -07001070 }
1071 }
1072
1073 void dump(PrintWriter pw) {
1074 pw.println(" Settings:");
1075
Dianne Hackborn953fc942016-03-29 15:36:24 -07001076 pw.print(" "); pw.print(KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT); pw.print("=");
1077 TimeUtils.formatDuration(LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT, pw);
1078 pw.println();
1079
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001080 pw.print(" "); pw.print(KEY_LIGHT_PRE_IDLE_TIMEOUT); pw.print("=");
1081 TimeUtils.formatDuration(LIGHT_PRE_IDLE_TIMEOUT, pw);
1082 pw.println();
1083
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001084 pw.print(" "); pw.print(KEY_LIGHT_IDLE_TIMEOUT); pw.print("=");
1085 TimeUtils.formatDuration(LIGHT_IDLE_TIMEOUT, pw);
1086 pw.println();
1087
Dianne Hackborn953fc942016-03-29 15:36:24 -07001088 pw.print(" "); pw.print(KEY_LIGHT_IDLE_FACTOR); pw.print("=");
1089 pw.print(LIGHT_IDLE_FACTOR);
1090 pw.println();
1091
1092 pw.print(" "); pw.print(KEY_LIGHT_MAX_IDLE_TIMEOUT); pw.print("=");
1093 TimeUtils.formatDuration(LIGHT_MAX_IDLE_TIMEOUT, pw);
1094 pw.println();
1095
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001096 pw.print(" "); pw.print(KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET); pw.print("=");
1097 TimeUtils.formatDuration(LIGHT_IDLE_MAINTENANCE_MIN_BUDGET, pw);
1098 pw.println();
1099
1100 pw.print(" "); pw.print(KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET); pw.print("=");
1101 TimeUtils.formatDuration(LIGHT_IDLE_MAINTENANCE_MAX_BUDGET, pw);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001102 pw.println();
1103
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07001104 pw.print(" "); pw.print(KEY_MIN_LIGHT_MAINTENANCE_TIME); pw.print("=");
1105 TimeUtils.formatDuration(MIN_LIGHT_MAINTENANCE_TIME, pw);
1106 pw.println();
1107
1108 pw.print(" "); pw.print(KEY_MIN_DEEP_MAINTENANCE_TIME); pw.print("=");
1109 TimeUtils.formatDuration(MIN_DEEP_MAINTENANCE_TIME, pw);
1110 pw.println();
1111
Dianne Hackborna750a632015-06-16 17:18:23 -07001112 pw.print(" "); pw.print(KEY_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001113 TimeUtils.formatDuration(INACTIVE_TIMEOUT, pw);
1114 pw.println();
1115
Dianne Hackborna750a632015-06-16 17:18:23 -07001116 pw.print(" "); pw.print(KEY_SENSING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001117 TimeUtils.formatDuration(SENSING_TIMEOUT, pw);
1118 pw.println();
1119
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001120 pw.print(" "); pw.print(KEY_LOCATING_TIMEOUT); pw.print("=");
1121 TimeUtils.formatDuration(LOCATING_TIMEOUT, pw);
1122 pw.println();
1123
1124 pw.print(" "); pw.print(KEY_LOCATION_ACCURACY); pw.print("=");
1125 pw.print(LOCATION_ACCURACY); pw.print("m");
1126 pw.println();
1127
Dianne Hackborna750a632015-06-16 17:18:23 -07001128 pw.print(" "); pw.print(KEY_MOTION_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001129 TimeUtils.formatDuration(MOTION_INACTIVE_TIMEOUT, pw);
1130 pw.println();
1131
Dianne Hackborna750a632015-06-16 17:18:23 -07001132 pw.print(" "); pw.print(KEY_IDLE_AFTER_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001133 TimeUtils.formatDuration(IDLE_AFTER_INACTIVE_TIMEOUT, pw);
1134 pw.println();
1135
Dianne Hackborna750a632015-06-16 17:18:23 -07001136 pw.print(" "); pw.print(KEY_IDLE_PENDING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001137 TimeUtils.formatDuration(IDLE_PENDING_TIMEOUT, pw);
1138 pw.println();
1139
Dianne Hackborna750a632015-06-16 17:18:23 -07001140 pw.print(" "); pw.print(KEY_MAX_IDLE_PENDING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001141 TimeUtils.formatDuration(MAX_IDLE_PENDING_TIMEOUT, pw);
1142 pw.println();
1143
Dianne Hackborna750a632015-06-16 17:18:23 -07001144 pw.print(" "); pw.print(KEY_IDLE_PENDING_FACTOR); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001145 pw.println(IDLE_PENDING_FACTOR);
1146
Kweku Adamsb396ccf2018-09-17 16:37:15 -07001147 pw.print(" "); pw.print(KEY_QUICK_DOZE_DELAY_TIMEOUT); pw.print("=");
1148 TimeUtils.formatDuration(QUICK_DOZE_DELAY_TIMEOUT, pw);
1149 pw.println();
1150
Dianne Hackborna750a632015-06-16 17:18:23 -07001151 pw.print(" "); pw.print(KEY_IDLE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001152 TimeUtils.formatDuration(IDLE_TIMEOUT, pw);
1153 pw.println();
1154
Dianne Hackborna750a632015-06-16 17:18:23 -07001155 pw.print(" "); pw.print(KEY_MAX_IDLE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001156 TimeUtils.formatDuration(MAX_IDLE_TIMEOUT, pw);
1157 pw.println();
1158
Dianne Hackborna750a632015-06-16 17:18:23 -07001159 pw.print(" "); pw.print(KEY_IDLE_FACTOR); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001160 pw.println(IDLE_FACTOR);
1161
Dianne Hackborna750a632015-06-16 17:18:23 -07001162 pw.print(" "); pw.print(KEY_MIN_TIME_TO_ALARM); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001163 TimeUtils.formatDuration(MIN_TIME_TO_ALARM, pw);
1164 pw.println();
1165
Dianne Hackborna750a632015-06-16 17:18:23 -07001166 pw.print(" "); pw.print(KEY_MAX_TEMP_APP_WHITELIST_DURATION); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001167 TimeUtils.formatDuration(MAX_TEMP_APP_WHITELIST_DURATION, pw);
1168 pw.println();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001169
1170 pw.print(" "); pw.print(KEY_MMS_TEMP_APP_WHITELIST_DURATION); pw.print("=");
1171 TimeUtils.formatDuration(MMS_TEMP_APP_WHITELIST_DURATION, pw);
1172 pw.println();
Dianne Hackborn451c3462015-07-21 17:39:46 -07001173
1174 pw.print(" "); pw.print(KEY_SMS_TEMP_APP_WHITELIST_DURATION); pw.print("=");
1175 TimeUtils.formatDuration(SMS_TEMP_APP_WHITELIST_DURATION, pw);
1176 pw.println();
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001177
1178 pw.print(" "); pw.print(KEY_NOTIFICATION_WHITELIST_DURATION); pw.print("=");
1179 TimeUtils.formatDuration(NOTIFICATION_WHITELIST_DURATION, pw);
1180 pw.println();
Amith Yamasani396a10c2018-01-19 10:58:07 -08001181
1182 pw.print(" "); pw.print(KEY_WAIT_FOR_UNLOCK); pw.print("=");
1183 pw.println(WAIT_FOR_UNLOCK);
Adam Lesinski31c05d12015-06-09 17:34:04 -07001184 }
1185 }
1186
1187 private Constants mConstants;
1188
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001189 @Override
1190 public void onAnyMotionResult(int result) {
1191 if (DEBUG) Slog.d(TAG, "onAnyMotionResult(" + result + ")");
Kevin Gabayan92f15e62016-04-04 17:52:22 -07001192 if (result != AnyMotionDetector.RESULT_UNKNOWN) {
1193 synchronized (this) {
1194 cancelSensingTimeoutAlarmLocked();
1195 }
1196 }
Kevin Gabayandcf47012016-07-08 10:41:24 -07001197 if ((result == AnyMotionDetector.RESULT_MOVED) ||
1198 (result == AnyMotionDetector.RESULT_UNKNOWN)) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001199 synchronized (this) {
Kevin Gabayandcf47012016-07-08 10:41:24 -07001200 handleMotionDetectedLocked(mConstants.INACTIVE_TIMEOUT, "non_stationary");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001201 }
1202 } else if (result == AnyMotionDetector.RESULT_STATIONARY) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001203 if (mState == STATE_SENSING) {
1204 // If we are currently sensing, it is time to move to locating.
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001205 synchronized (this) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001206 mNotMoving = true;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001207 stepIdleStateLocked("s:stationary");
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001208 }
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001209 } else if (mState == STATE_LOCATING) {
1210 // If we are currently locating, note that we are not moving and step
1211 // if we have located the position.
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001212 synchronized (this) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001213 mNotMoving = true;
1214 if (mLocated) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001215 stepIdleStateLocked("s:stationary");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001216 }
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001217 }
1218 }
1219 }
1220 }
1221
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001222 private static final int MSG_WRITE_CONFIG = 1;
1223 private static final int MSG_REPORT_IDLE_ON = 2;
1224 private static final int MSG_REPORT_IDLE_ON_LIGHT = 3;
1225 private static final int MSG_REPORT_IDLE_OFF = 4;
1226 private static final int MSG_REPORT_ACTIVE = 5;
1227 private static final int MSG_TEMP_APP_WHITELIST_TIMEOUT = 6;
1228 private static final int MSG_REPORT_MAINTENANCE_ACTIVITY = 7;
1229 private static final int MSG_FINISH_IDLE_OP = 8;
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001230 private static final int MSG_REPORT_TEMP_APP_WHITELIST_CHANGED = 9;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001231
1232 final class MyHandler extends Handler {
1233 MyHandler(Looper looper) {
1234 super(looper);
1235 }
1236
1237 @Override public void handleMessage(Message msg) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001238 if (DEBUG) Slog.d(TAG, "handleMessage(" + msg.what + ")");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001239 switch (msg.what) {
1240 case MSG_WRITE_CONFIG: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001241 // Does not hold a wakelock. Just let this happen whenever.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001242 handleWriteConfigFile();
1243 } break;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001244 case MSG_REPORT_IDLE_ON:
1245 case MSG_REPORT_IDLE_ON_LIGHT: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001246 // mGoingIdleWakeLock is held at this point
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001247 EventLogTags.writeDeviceIdleOnStart();
Dianne Hackbornb6843652016-02-22 12:20:13 -08001248 final boolean deepChanged;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001249 final boolean lightChanged;
1250 if (msg.what == MSG_REPORT_IDLE_ON) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001251 deepChanged = mLocalPowerManager.setDeviceIdleMode(true);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001252 lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
1253 } else {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001254 deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001255 lightChanged = mLocalPowerManager.setLightDeviceIdleMode(true);
1256 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001257 try {
1258 mNetworkPolicyManager.setDeviceIdleMode(true);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001259 mBatteryStats.noteDeviceIdleMode(msg.what == MSG_REPORT_IDLE_ON
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07001260 ? BatteryStats.DEVICE_IDLE_MODE_DEEP
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001261 : BatteryStats.DEVICE_IDLE_MODE_LIGHT, null, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001262 } catch (RemoteException e) {
1263 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001264 if (deepChanged) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001265 getContext().sendBroadcastAsUser(mIdleIntent, UserHandle.ALL);
1266 }
1267 if (lightChanged) {
1268 getContext().sendBroadcastAsUser(mLightIdleIntent, UserHandle.ALL);
1269 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001270 EventLogTags.writeDeviceIdleOnComplete();
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001271 mGoingIdleWakeLock.release();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001272 } break;
1273 case MSG_REPORT_IDLE_OFF: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001274 // mActiveIdleWakeLock is held at this point
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001275 EventLogTags.writeDeviceIdleOffStart("unknown");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001276 final boolean deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001277 final boolean lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001278 try {
1279 mNetworkPolicyManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001280 mBatteryStats.noteDeviceIdleMode(BatteryStats.DEVICE_IDLE_MODE_OFF,
1281 null, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001282 } catch (RemoteException e) {
1283 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001284 if (deepChanged) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001285 incActiveIdleOps();
1286 getContext().sendOrderedBroadcastAsUser(mIdleIntent, UserHandle.ALL,
1287 null, mIdleStartedDoneReceiver, null, 0, null, null);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001288 }
1289 if (lightChanged) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001290 incActiveIdleOps();
1291 getContext().sendOrderedBroadcastAsUser(mLightIdleIntent, UserHandle.ALL,
1292 null, mIdleStartedDoneReceiver, null, 0, null, null);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001293 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001294 // Always start with one active op for the message being sent here.
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001295 // Now we are done!
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001296 decActiveIdleOps();
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001297 EventLogTags.writeDeviceIdleOffComplete();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001298 } break;
1299 case MSG_REPORT_ACTIVE: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001300 // The device is awake at this point, so no wakelock necessary.
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001301 String activeReason = (String)msg.obj;
1302 int activeUid = msg.arg1;
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001303 EventLogTags.writeDeviceIdleOffStart(
1304 activeReason != null ? activeReason : "unknown");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001305 final boolean deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001306 final boolean lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001307 try {
1308 mNetworkPolicyManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001309 mBatteryStats.noteDeviceIdleMode(BatteryStats.DEVICE_IDLE_MODE_OFF,
1310 activeReason, activeUid);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001311 } catch (RemoteException e) {
1312 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001313 if (deepChanged) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001314 getContext().sendBroadcastAsUser(mIdleIntent, UserHandle.ALL);
1315 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001316 if (lightChanged) {
1317 getContext().sendBroadcastAsUser(mLightIdleIntent, UserHandle.ALL);
1318 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001319 EventLogTags.writeDeviceIdleOffComplete();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001320 } break;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001321 case MSG_TEMP_APP_WHITELIST_TIMEOUT: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001322 // TODO: What is keeping the device awake at this point? Does it need to be?
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001323 int uid = msg.arg1;
1324 checkTempAppWhitelistTimeout(uid);
1325 } break;
Yao Chenca5edbb2016-01-13 14:44:36 -08001326 case MSG_REPORT_MAINTENANCE_ACTIVITY: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001327 // TODO: What is keeping the device awake at this point? Does it need to be?
Yao Chenca5edbb2016-01-13 14:44:36 -08001328 boolean active = (msg.arg1 == 1);
1329 final int size = mMaintenanceActivityListeners.beginBroadcast();
1330 try {
1331 for (int i = 0; i < size; i++) {
1332 try {
1333 mMaintenanceActivityListeners.getBroadcastItem(i)
1334 .onMaintenanceActivityChanged(active);
1335 } catch (RemoteException ignored) {
1336 }
1337 }
1338 } finally {
1339 mMaintenanceActivityListeners.finishBroadcast();
1340 }
1341 } break;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001342 case MSG_FINISH_IDLE_OP: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001343 // mActiveIdleWakeLock is held at this point
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001344 decActiveIdleOps();
1345 } break;
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001346 case MSG_REPORT_TEMP_APP_WHITELIST_CHANGED: {
1347 final int appId = msg.arg1;
1348 final boolean added = (msg.arg2 == 1);
1349 mNetworkPolicyManagerInternal.onTempPowerSaveWhitelistChange(appId, added);
1350 } break;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001351 }
1352 }
1353 }
1354
1355 final MyHandler mHandler;
1356
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001357 BinderService mBinderService;
1358
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001359 private final class BinderService extends IDeviceIdleController.Stub {
1360 @Override public void addPowerSaveWhitelistApp(String name) {
Eugene Susla6a7006a2017-03-13 12:57:58 -07001361 if (DEBUG) {
1362 Slog.i(TAG, "addPowerSaveWhitelistApp(name = " + name + ")");
1363 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001364 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1365 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001366 long ident = Binder.clearCallingIdentity();
1367 try {
1368 addPowerSaveWhitelistAppInternal(name);
1369 } finally {
1370 Binder.restoreCallingIdentity(ident);
1371 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001372 }
1373
1374 @Override public void removePowerSaveWhitelistApp(String name) {
Eugene Susla6a7006a2017-03-13 12:57:58 -07001375 if (DEBUG) {
1376 Slog.i(TAG, "removePowerSaveWhitelistApp(name = " + name + ")");
1377 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001378 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1379 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001380 long ident = Binder.clearCallingIdentity();
1381 try {
1382 removePowerSaveWhitelistAppInternal(name);
1383 } finally {
1384 Binder.restoreCallingIdentity(ident);
1385 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001386 }
1387
Suprabh Shukla08105642017-09-26 14:45:30 -07001388 @Override public void removeSystemPowerWhitelistApp(String name) {
1389 if (DEBUG) {
1390 Slog.d(TAG, "removeAppFromSystemWhitelist(name = " + name + ")");
1391 }
1392 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1393 null);
1394 long ident = Binder.clearCallingIdentity();
1395 try {
1396 removeSystemPowerWhitelistAppInternal(name);
1397 } finally {
1398 Binder.restoreCallingIdentity(ident);
1399 }
1400 }
1401
1402 @Override public void restoreSystemPowerWhitelistApp(String name) {
1403 if (DEBUG) {
1404 Slog.d(TAG, "restoreAppToSystemWhitelist(name = " + name + ")");
1405 }
1406 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1407 null);
1408 long ident = Binder.clearCallingIdentity();
1409 try {
1410 restoreSystemPowerWhitelistAppInternal(name);
1411 } finally {
1412 Binder.restoreCallingIdentity(ident);
1413 }
1414 }
1415
1416 public String[] getRemovedSystemPowerWhitelistApps() {
1417 return getRemovedSystemPowerWhitelistAppsInternal();
1418 }
1419
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001420 @Override public String[] getSystemPowerWhitelistExceptIdle() {
1421 return getSystemPowerWhitelistExceptIdleInternal();
1422 }
1423
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001424 @Override public String[] getSystemPowerWhitelist() {
1425 return getSystemPowerWhitelistInternal();
1426 }
1427
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001428 @Override public String[] getUserPowerWhitelist() {
1429 return getUserPowerWhitelistInternal();
1430 }
1431
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001432 @Override public String[] getFullPowerWhitelistExceptIdle() {
1433 return getFullPowerWhitelistExceptIdleInternal();
1434 }
1435
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001436 @Override public String[] getFullPowerWhitelist() {
1437 return getFullPowerWhitelistInternal();
1438 }
1439
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001440 @Override public int[] getAppIdWhitelistExceptIdle() {
1441 return getAppIdWhitelistExceptIdleInternal();
1442 }
1443
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001444 @Override public int[] getAppIdWhitelist() {
1445 return getAppIdWhitelistInternal();
1446 }
1447
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001448 @Override public int[] getAppIdUserWhitelist() {
1449 return getAppIdUserWhitelistInternal();
1450 }
1451
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001452 @Override public int[] getAppIdTempWhitelist() {
1453 return getAppIdTempWhitelistInternal();
1454 }
1455
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001456 @Override public boolean isPowerSaveWhitelistExceptIdleApp(String name) {
1457 return isPowerSaveWhitelistExceptIdleAppInternal(name);
1458 }
1459
Amith Yamasani06bf8242015-05-08 16:36:21 -07001460 @Override public boolean isPowerSaveWhitelistApp(String name) {
1461 return isPowerSaveWhitelistAppInternal(name);
1462 }
1463
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001464 @Override public void addPowerSaveTempWhitelistApp(String packageName, long duration,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001465 int userId, String reason) throws RemoteException {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001466 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001467 }
1468
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001469 @Override public long addPowerSaveTempWhitelistAppForMms(String packageName,
1470 int userId, String reason) throws RemoteException {
1471 long duration = mConstants.MMS_TEMP_APP_WHITELIST_DURATION;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001472 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001473 return duration;
1474 }
1475
Dianne Hackborn451c3462015-07-21 17:39:46 -07001476 @Override public long addPowerSaveTempWhitelistAppForSms(String packageName,
1477 int userId, String reason) throws RemoteException {
1478 long duration = mConstants.SMS_TEMP_APP_WHITELIST_DURATION;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001479 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Dianne Hackborn451c3462015-07-21 17:39:46 -07001480 return duration;
1481 }
1482
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001483 @Override public void exitIdle(String reason) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001484 getContext().enforceCallingOrSelfPermission(Manifest.permission.DEVICE_POWER,
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001485 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001486 long ident = Binder.clearCallingIdentity();
1487 try {
1488 exitIdleInternal(reason);
1489 } finally {
1490 Binder.restoreCallingIdentity(ident);
1491 }
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001492 }
1493
Yao Chenca5edbb2016-01-13 14:44:36 -08001494 @Override public boolean registerMaintenanceActivityListener(
1495 IMaintenanceActivityListener listener) {
1496 return DeviceIdleController.this.registerMaintenanceActivityListener(listener);
1497 }
1498
1499 @Override public void unregisterMaintenanceActivityListener(
1500 IMaintenanceActivityListener listener) {
1501 DeviceIdleController.this.unregisterMaintenanceActivityListener(listener);
1502 }
1503
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001504 @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1505 DeviceIdleController.this.dump(fd, pw, args);
1506 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001507
1508 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07001509 FileDescriptor err, String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
1510 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001511 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001512 }
1513
Felipe Lemeef134662016-08-10 14:46:39 -07001514 public class LocalService {
Christopher Tatee0be7e82017-02-08 17:38:20 -08001515 // duration in milliseconds
1516 public void addPowerSaveTempWhitelistApp(int callingUid, String packageName,
1517 long duration, int userId, boolean sync, String reason) {
1518 addPowerSaveTempWhitelistAppInternal(callingUid, packageName, duration,
1519 userId, sync, reason);
1520 }
1521
1522 // duration in milliseconds
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001523 public void addPowerSaveTempWhitelistAppDirect(int appId, long duration, boolean sync,
1524 String reason) {
1525 addPowerSaveTempWhitelistAppDirectInternal(0, appId, duration, sync, reason);
1526 }
1527
Christopher Tatee0be7e82017-02-08 17:38:20 -08001528 // duration in milliseconds
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001529 public long getNotificationWhitelistDuration() {
1530 return mConstants.NOTIFICATION_WHITELIST_DURATION;
1531 }
1532
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001533 public void setJobsActive(boolean active) {
1534 DeviceIdleController.this.setJobsActive(active);
1535 }
1536
1537 // Up-call from alarm manager.
1538 public void setAlarmsActive(boolean active) {
1539 DeviceIdleController.this.setAlarmsActive(active);
1540 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001541
Christopher Tate42a386b2016-11-07 12:21:21 -08001542 /** Is the app on any of the power save whitelists, whether system or user? */
1543 public boolean isAppOnWhitelist(int appid) {
1544 return DeviceIdleController.this.isAppOnWhitelistInternal(appid);
1545 }
1546
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001547 /**
1548 * Returns the array of app ids whitelisted by user. Take care not to
1549 * modify this, as it is a reference to the original copy. But the reference
1550 * can change when the list changes, so it needs to be re-acquired when
1551 * {@link PowerManager#ACTION_POWER_SAVE_WHITELIST_CHANGED} is sent.
1552 */
1553 public int[] getPowerSaveWhitelistUserAppIds() {
1554 return DeviceIdleController.this.getPowerSaveWhitelistUserAppIds();
1555 }
Suprabh Shuklaa78acfd2017-10-13 19:29:36 -07001556
1557 public int[] getPowerSaveTempWhitelistAppIds() {
1558 return DeviceIdleController.this.getAppIdTempWhitelistInternal();
1559 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001560 }
1561
Kweku Adams00e3a372018-09-28 16:57:09 -07001562 static class Injector {
1563 private final Context mContext;
Kweku Adams799858b2018-10-08 17:19:08 -07001564 private ConnectivityService mConnectivityService;
1565 private LocationManager mLocationManager;
Kweku Adams00e3a372018-09-28 16:57:09 -07001566
1567 Injector(Context ctx) {
1568 mContext = ctx;
1569 }
1570
1571 AlarmManager getAlarmManager() {
1572 return mContext.getSystemService(AlarmManager.class);
1573 }
1574
1575 AnyMotionDetector getAnyMotionDetector(Handler handler, SensorManager sm,
1576 AnyMotionDetector.DeviceIdleCallback callback, float angleThreshold) {
1577 return new AnyMotionDetector(getPowerManager(), handler, sm, callback, angleThreshold);
1578 }
1579
1580 AppStateTracker getAppStateTracker(Context ctx, Looper looper) {
1581 return new AppStateTracker(ctx, looper);
1582 }
1583
1584 ConnectivityService getConnectivityService() {
Kweku Adams799858b2018-10-08 17:19:08 -07001585 if (mConnectivityService == null) {
1586 mConnectivityService = (ConnectivityService) ServiceManager.getService(
1587 Context.CONNECTIVITY_SERVICE);
1588 }
1589 return mConnectivityService;
Kweku Adams00e3a372018-09-28 16:57:09 -07001590 }
1591
Kweku Adamsa457f4e2018-10-03 15:56:06 -07001592 Constants getConstants(DeviceIdleController controller, Handler handler,
1593 ContentResolver resolver) {
1594 return controller.new Constants(handler, resolver);
1595 }
1596
Kweku Adams00e3a372018-09-28 16:57:09 -07001597 LocationManager getLocationManager() {
Kweku Adams799858b2018-10-08 17:19:08 -07001598 if (mLocationManager == null) {
1599 mLocationManager = mContext.getSystemService(LocationManager.class);
1600 }
1601 return mLocationManager;
Kweku Adams00e3a372018-09-28 16:57:09 -07001602 }
1603
Kweku Adamsa457f4e2018-10-03 15:56:06 -07001604 MyHandler getHandler(DeviceIdleController controller) {
1605 return controller.new MyHandler(BackgroundThread.getHandler().getLooper());
Kweku Adams00e3a372018-09-28 16:57:09 -07001606 }
1607
1608 PowerManager getPowerManager() {
1609 return mContext.getSystemService(PowerManager.class);
1610 }
1611 }
1612
1613 private final Injector mInjector;
1614
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001615 private ActivityTaskManagerInternal.ScreenObserver mScreenObserver =
1616 new ActivityTaskManagerInternal.ScreenObserver() {
Amith Yamasani396a10c2018-01-19 10:58:07 -08001617 @Override
1618 public void onAwakeStateChanged(boolean isAwake) { }
1619
1620 @Override
1621 public void onKeyguardStateChanged(boolean isShowing) {
1622 synchronized (DeviceIdleController.this) {
1623 DeviceIdleController.this.keyguardShowingLocked(isShowing);
1624 }
1625 }
1626 };
1627
Kweku Adams00e3a372018-09-28 16:57:09 -07001628 @VisibleForTesting DeviceIdleController(Context context, Injector injector) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001629 super(context);
Kweku Adams00e3a372018-09-28 16:57:09 -07001630 mInjector = injector;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001631 mConfigFile = new AtomicFile(new File(getSystemDir(), "deviceidle.xml"));
Kweku Adams00e3a372018-09-28 16:57:09 -07001632 mHandler = mInjector.getHandler(this);
1633 mAppStateTracker = mInjector.getAppStateTracker(context, FgThread.get().getLooper());
Makoto Onukie4918212018-02-06 11:30:15 -08001634 LocalServices.addService(AppStateTracker.class, mAppStateTracker);
Robin Leec4d424c2018-12-07 15:09:13 +01001635
1636 mUseMotionSensor = context.getResources().getBoolean(
1637 com.android.internal.R.bool.config_autoPowerModeUseMotionSensor);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001638 }
1639
Kweku Adams00e3a372018-09-28 16:57:09 -07001640 public DeviceIdleController(Context context) {
1641 this(context, new Injector(context));
1642 }
1643
Christopher Tate42a386b2016-11-07 12:21:21 -08001644 boolean isAppOnWhitelistInternal(int appid) {
1645 synchronized (this) {
1646 return Arrays.binarySearch(mPowerSaveWhitelistAllAppIdArray, appid) >= 0;
1647 }
1648 }
1649
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001650 int[] getPowerSaveWhitelistUserAppIds() {
1651 synchronized (this) {
1652 return mPowerSaveWhitelistUserAppIdArray;
1653 }
1654 }
1655
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001656 private static File getSystemDir() {
1657 return new File(Environment.getDataDirectory(), "system");
1658 }
1659
1660 @Override
1661 public void onStart() {
1662 final PackageManager pm = getContext().getPackageManager();
1663
1664 synchronized (this) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001665 mLightEnabled = mDeepEnabled = getContext().getResources().getBoolean(
Dianne Hackborn92617032015-06-19 15:32:19 -07001666 com.android.internal.R.bool.config_enableAutoPowerModes);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001667 SystemConfig sysConfig = SystemConfig.getInstance();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001668 ArraySet<String> allowPowerExceptIdle = sysConfig.getAllowInPowerSaveExceptIdle();
1669 for (int i=0; i<allowPowerExceptIdle.size(); i++) {
1670 String pkg = allowPowerExceptIdle.valueAt(i);
1671 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001672 ApplicationInfo ai = pm.getApplicationInfo(pkg,
1673 PackageManager.MATCH_SYSTEM_ONLY);
1674 int appid = UserHandle.getAppId(ai.uid);
1675 mPowerSaveWhitelistAppsExceptIdle.put(ai.packageName, appid);
1676 mPowerSaveWhitelistSystemAppIdsExceptIdle.put(appid, true);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001677 } catch (PackageManager.NameNotFoundException e) {
1678 }
1679 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001680 ArraySet<String> allowPower = sysConfig.getAllowInPowerSave();
1681 for (int i=0; i<allowPower.size(); i++) {
1682 String pkg = allowPower.valueAt(i);
1683 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001684 ApplicationInfo ai = pm.getApplicationInfo(pkg,
1685 PackageManager.MATCH_SYSTEM_ONLY);
1686 int appid = UserHandle.getAppId(ai.uid);
1687 // These apps are on both the whitelist-except-idle as well
1688 // as the full whitelist, so they apply in all cases.
1689 mPowerSaveWhitelistAppsExceptIdle.put(ai.packageName, appid);
1690 mPowerSaveWhitelistSystemAppIdsExceptIdle.put(appid, true);
1691 mPowerSaveWhitelistApps.put(ai.packageName, appid);
1692 mPowerSaveWhitelistSystemAppIds.put(appid, true);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001693 } catch (PackageManager.NameNotFoundException e) {
1694 }
1695 }
1696
Kweku Adamsa457f4e2018-10-03 15:56:06 -07001697 mConstants = mInjector.getConstants(this, mHandler, getContext().getContentResolver());
Adam Lesinski31c05d12015-06-09 17:34:04 -07001698
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001699 readConfigFileLocked();
1700 updateWhitelistAppIdsLocked();
1701
Dianne Hackborn88c41352016-04-07 15:18:58 -07001702 mNetworkConnected = true;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001703 mScreenOn = true;
Amith Yamasani396a10c2018-01-19 10:58:07 -08001704 mScreenLocked = false;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001705 // Start out assuming we are charging. If we aren't, we will at least get
1706 // a battery update the next time the level drops.
1707 mCharging = true;
1708 mState = STATE_ACTIVE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001709 mLightState = LIGHT_STATE_ACTIVE;
Adam Lesinski31c05d12015-06-09 17:34:04 -07001710 mInactiveTimeout = mConstants.INACTIVE_TIMEOUT;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001711 }
1712
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001713 mBinderService = new BinderService();
1714 publishBinderService(Context.DEVICE_IDLE_CONTROLLER, mBinderService);
Dianne Hackborna750a632015-06-16 17:18:23 -07001715 publishLocalService(LocalService.class, new LocalService());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001716 }
1717
1718 @Override
1719 public void onBootPhase(int phase) {
1720 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1721 synchronized (this) {
Kweku Adams00e3a372018-09-28 16:57:09 -07001722 mAlarmManager = mInjector.getAlarmManager();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001723 mBatteryStats = BatteryStatsService.getService();
Dianne Hackborn85e35642017-01-12 15:10:57 -08001724 mLocalActivityManager = getLocalService(ActivityManagerInternal.class);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001725 mLocalActivityTaskManager = getLocalService(ActivityTaskManagerInternal.class);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001726 mLocalPowerManager = getLocalService(PowerManagerInternal.class);
Kweku Adams00e3a372018-09-28 16:57:09 -07001727 mPowerManager = mInjector.getPowerManager();
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001728 mActiveIdleWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
1729 "deviceidle_maint");
1730 mActiveIdleWakeLock.setReferenceCounted(false);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001731 mGoingIdleWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
1732 "deviceidle_going_idle");
1733 mGoingIdleWakeLock.setReferenceCounted(true);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001734 mNetworkPolicyManager = INetworkPolicyManager.Stub.asInterface(
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001735 ServiceManager.getService(Context.NETWORK_POLICY_SERVICE));
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001736 mNetworkPolicyManagerInternal = getLocalService(NetworkPolicyManagerInternal.class);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001737 mSensorManager = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
Robin Leec4d424c2018-12-07 15:09:13 +01001738
1739 if (mUseMotionSensor) {
1740 int sigMotionSensorId = getContext().getResources().getInteger(
1741 com.android.internal.R.integer.config_autoPowerModeAnyMotionSensor);
1742 if (sigMotionSensorId > 0) {
1743 mMotionSensor = mSensorManager.getDefaultSensor(sigMotionSensorId, true);
1744 }
1745 if (mMotionSensor == null && getContext().getResources().getBoolean(
1746 com.android.internal.R.bool.config_autoPowerModePreferWristTilt)) {
1747 mMotionSensor = mSensorManager.getDefaultSensor(
1748 Sensor.TYPE_WRIST_TILT_GESTURE, true);
1749 }
1750 if (mMotionSensor == null) {
1751 // As a last ditch, fall back to SMD.
1752 mMotionSensor = mSensorManager.getDefaultSensor(
1753 Sensor.TYPE_SIGNIFICANT_MOTION, true);
1754 }
Joe LaPenna23d681b2015-08-27 15:12:11 -07001755 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001756
Joe LaPenna23d681b2015-08-27 15:12:11 -07001757 if (getContext().getResources().getBoolean(
1758 com.android.internal.R.bool.config_autoPowerModePrefetchLocation)) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07001759 mLocationRequest = new LocationRequest()
1760 .setQuality(LocationRequest.ACCURACY_FINE)
1761 .setInterval(0)
1762 .setFastestInterval(0)
1763 .setNumUpdates(1);
1764 }
1765
1766 float angleThreshold = getContext().getResources().getInteger(
1767 com.android.internal.R.integer.config_autoPowerModeThresholdAngle) / 100f;
Kweku Adams00e3a372018-09-28 16:57:09 -07001768 mAnyMotionDetector = mInjector.getAnyMotionDetector(mHandler, mSensorManager, this,
1769 angleThreshold);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001770
Makoto Onukie4918212018-02-06 11:30:15 -08001771 mAppStateTracker.onSystemServicesReady();
1772
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001773 mIdleIntent = new Intent(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001774 mIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1775 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001776 mLightIdleIntent = new Intent(PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED);
1777 mLightIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1778 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001779
1780 IntentFilter filter = new IntentFilter();
1781 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001782 getContext().registerReceiver(mReceiver, filter);
Amith Yamasaniac59f75e2016-05-05 12:38:17 -07001783
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001784 filter = new IntentFilter();
1785 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1786 filter.addDataScheme("package");
Amith Yamasaniac59f75e2016-05-05 12:38:17 -07001787 getContext().registerReceiver(mReceiver, filter);
1788
Dianne Hackborn88c41352016-04-07 15:18:58 -07001789 filter = new IntentFilter();
1790 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001791 getContext().registerReceiver(mReceiver, filter);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001792
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -07001793 filter = new IntentFilter();
1794 filter.addAction(Intent.ACTION_SCREEN_OFF);
1795 filter.addAction(Intent.ACTION_SCREEN_ON);
1796 getContext().registerReceiver(mInteractivityReceiver, filter);
1797
Makoto Onukiaf8ff4f2018-06-04 14:44:19 -07001798 mLocalActivityManager.setDeviceIdleWhitelist(
1799 mPowerSaveWhitelistAllAppIdArray, mPowerSaveWhitelistExceptIdleAppIdArray);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001800 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -07001801
Kweku Adamsb396ccf2018-09-17 16:37:15 -07001802 mLocalPowerManager.registerLowPowerModeObserver(ServiceType.QUICK_DOZE,
1803 state -> {
1804 synchronized (DeviceIdleController.this) {
1805 updateQuickDozeFlagLocked(state.batterySaverEnabled);
1806 }
1807 });
1808 updateQuickDozeFlagLocked(
1809 mLocalPowerManager.getLowPowerState(
1810 ServiceType.QUICK_DOZE).batterySaverEnabled);
1811
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001812 mLocalActivityTaskManager.registerScreenObserver(mScreenObserver);
Amith Yamasani396a10c2018-01-19 10:58:07 -08001813
Suprabh Shukla5bf49812018-05-24 18:38:50 -07001814 passWhiteListsToForceAppStandbyTrackerLocked();
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -07001815 updateInteractivityLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001816 }
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -07001817 updateConnectivityState(null);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001818 }
1819 }
1820
1821 public boolean addPowerSaveWhitelistAppInternal(String name) {
1822 synchronized (this) {
1823 try {
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001824 ApplicationInfo ai = getContext().getPackageManager().getApplicationInfo(name,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07001825 PackageManager.MATCH_ANY_USER);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001826 if (mPowerSaveWhitelistUserApps.put(name, UserHandle.getAppId(ai.uid)) == null) {
1827 reportPowerSaveWhitelistChangedLocked();
1828 updateWhitelistAppIdsLocked();
1829 writeConfigFileLocked();
1830 }
1831 return true;
1832 } catch (PackageManager.NameNotFoundException e) {
1833 return false;
1834 }
1835 }
1836 }
1837
1838 public boolean removePowerSaveWhitelistAppInternal(String name) {
1839 synchronized (this) {
1840 if (mPowerSaveWhitelistUserApps.remove(name) != null) {
1841 reportPowerSaveWhitelistChangedLocked();
1842 updateWhitelistAppIdsLocked();
1843 writeConfigFileLocked();
1844 return true;
1845 }
1846 }
1847 return false;
1848 }
1849
Felipe Lemef8a46232016-02-10 13:51:54 -08001850 public boolean getPowerSaveWhitelistAppInternal(String name) {
1851 synchronized (this) {
1852 return mPowerSaveWhitelistUserApps.containsKey(name);
1853 }
1854 }
1855
Suprabh Shukla08105642017-09-26 14:45:30 -07001856 void resetSystemPowerWhitelistInternal() {
1857 synchronized (this) {
1858 mPowerSaveWhitelistApps.putAll(mRemovedFromSystemWhitelistApps);
1859 mRemovedFromSystemWhitelistApps.clear();
1860 reportPowerSaveWhitelistChangedLocked();
1861 updateWhitelistAppIdsLocked();
1862 writeConfigFileLocked();
1863 }
1864 }
1865
1866 public boolean restoreSystemPowerWhitelistAppInternal(String name) {
1867 synchronized (this) {
1868 if (!mRemovedFromSystemWhitelistApps.containsKey(name)) {
1869 return false;
1870 }
1871 mPowerSaveWhitelistApps.put(name, mRemovedFromSystemWhitelistApps.remove(name));
1872 reportPowerSaveWhitelistChangedLocked();
1873 updateWhitelistAppIdsLocked();
1874 writeConfigFileLocked();
1875 return true;
1876 }
1877 }
1878
1879 public boolean removeSystemPowerWhitelistAppInternal(String name) {
1880 synchronized (this) {
1881 if (!mPowerSaveWhitelistApps.containsKey(name)) {
1882 return false;
1883 }
1884 mRemovedFromSystemWhitelistApps.put(name, mPowerSaveWhitelistApps.remove(name));
1885 reportPowerSaveWhitelistChangedLocked();
1886 updateWhitelistAppIdsLocked();
1887 writeConfigFileLocked();
1888 return true;
1889 }
1890 }
1891
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07001892 public boolean addPowerSaveWhitelistExceptIdleInternal(String name) {
1893 synchronized (this) {
1894 try {
1895 final ApplicationInfo ai = getContext().getPackageManager().getApplicationInfo(name,
1896 PackageManager.MATCH_ANY_USER);
1897 if (mPowerSaveWhitelistAppsExceptIdle.put(name, UserHandle.getAppId(ai.uid))
1898 == null) {
1899 mPowerSaveWhitelistUserAppsExceptIdle.add(name);
1900 reportPowerSaveWhitelistChangedLocked();
1901 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(
1902 mPowerSaveWhitelistAppsExceptIdle, mPowerSaveWhitelistUserApps,
1903 mPowerSaveWhitelistExceptIdleAppIds);
Makoto Onuki71755c92018-01-16 14:15:44 -08001904
Suprabh Shukla5bf49812018-05-24 18:38:50 -07001905 passWhiteListsToForceAppStandbyTrackerLocked();
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07001906 }
1907 return true;
1908 } catch (PackageManager.NameNotFoundException e) {
1909 return false;
1910 }
1911 }
1912 }
1913
1914 public void resetPowerSaveWhitelistExceptIdleInternal() {
1915 synchronized (this) {
1916 if (mPowerSaveWhitelistAppsExceptIdle.removeAll(
1917 mPowerSaveWhitelistUserAppsExceptIdle)) {
1918 reportPowerSaveWhitelistChangedLocked();
1919 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(
1920 mPowerSaveWhitelistAppsExceptIdle, mPowerSaveWhitelistUserApps,
1921 mPowerSaveWhitelistExceptIdleAppIds);
1922 mPowerSaveWhitelistUserAppsExceptIdle.clear();
Makoto Onuki71755c92018-01-16 14:15:44 -08001923
Suprabh Shukla5bf49812018-05-24 18:38:50 -07001924 passWhiteListsToForceAppStandbyTrackerLocked();
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07001925 }
1926 }
1927 }
1928
1929 public boolean getPowerSaveWhitelistExceptIdleInternal(String name) {
1930 synchronized (this) {
1931 return mPowerSaveWhitelistAppsExceptIdle.containsKey(name);
1932 }
1933 }
1934
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001935 public String[] getSystemPowerWhitelistExceptIdleInternal() {
1936 synchronized (this) {
1937 int size = mPowerSaveWhitelistAppsExceptIdle.size();
1938 String[] apps = new String[size];
1939 for (int i = 0; i < size; i++) {
1940 apps[i] = mPowerSaveWhitelistAppsExceptIdle.keyAt(i);
1941 }
1942 return apps;
1943 }
1944 }
1945
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001946 public String[] getSystemPowerWhitelistInternal() {
1947 synchronized (this) {
1948 int size = mPowerSaveWhitelistApps.size();
1949 String[] apps = new String[size];
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001950 for (int i = 0; i < size; i++) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001951 apps[i] = mPowerSaveWhitelistApps.keyAt(i);
1952 }
1953 return apps;
1954 }
1955 }
1956
Suprabh Shukla08105642017-09-26 14:45:30 -07001957 public String[] getRemovedSystemPowerWhitelistAppsInternal() {
1958 synchronized (this) {
1959 int size = mRemovedFromSystemWhitelistApps.size();
1960 final String[] apps = new String[size];
1961 for (int i = 0; i < size; i++) {
1962 apps[i] = mRemovedFromSystemWhitelistApps.keyAt(i);
1963 }
1964 return apps;
1965 }
1966 }
1967
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001968 public String[] getUserPowerWhitelistInternal() {
1969 synchronized (this) {
1970 int size = mPowerSaveWhitelistUserApps.size();
1971 String[] apps = new String[size];
1972 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1973 apps[i] = mPowerSaveWhitelistUserApps.keyAt(i);
1974 }
1975 return apps;
1976 }
1977 }
1978
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001979 public String[] getFullPowerWhitelistExceptIdleInternal() {
1980 synchronized (this) {
1981 int size = mPowerSaveWhitelistAppsExceptIdle.size() + mPowerSaveWhitelistUserApps.size();
1982 String[] apps = new String[size];
1983 int cur = 0;
1984 for (int i = 0; i < mPowerSaveWhitelistAppsExceptIdle.size(); i++) {
1985 apps[cur] = mPowerSaveWhitelistAppsExceptIdle.keyAt(i);
1986 cur++;
1987 }
1988 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1989 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
1990 cur++;
1991 }
1992 return apps;
1993 }
1994 }
1995
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001996 public String[] getFullPowerWhitelistInternal() {
1997 synchronized (this) {
1998 int size = mPowerSaveWhitelistApps.size() + mPowerSaveWhitelistUserApps.size();
1999 String[] apps = new String[size];
2000 int cur = 0;
2001 for (int i = 0; i < mPowerSaveWhitelistApps.size(); i++) {
2002 apps[cur] = mPowerSaveWhitelistApps.keyAt(i);
2003 cur++;
2004 }
2005 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
2006 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
2007 cur++;
2008 }
2009 return apps;
2010 }
2011 }
2012
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002013 public boolean isPowerSaveWhitelistExceptIdleAppInternal(String packageName) {
2014 synchronized (this) {
2015 return mPowerSaveWhitelistAppsExceptIdle.containsKey(packageName)
2016 || mPowerSaveWhitelistUserApps.containsKey(packageName);
2017 }
2018 }
2019
Amith Yamasani06bf8242015-05-08 16:36:21 -07002020 public boolean isPowerSaveWhitelistAppInternal(String packageName) {
2021 synchronized (this) {
2022 return mPowerSaveWhitelistApps.containsKey(packageName)
2023 || mPowerSaveWhitelistUserApps.containsKey(packageName);
2024 }
2025 }
2026
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002027 public int[] getAppIdWhitelistExceptIdleInternal() {
2028 synchronized (this) {
2029 return mPowerSaveWhitelistExceptIdleAppIdArray;
2030 }
2031 }
2032
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002033 public int[] getAppIdWhitelistInternal() {
2034 synchronized (this) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002035 return mPowerSaveWhitelistAllAppIdArray;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002036 }
2037 }
2038
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002039 public int[] getAppIdUserWhitelistInternal() {
2040 synchronized (this) {
2041 return mPowerSaveWhitelistUserAppIdArray;
2042 }
2043 }
2044
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002045 public int[] getAppIdTempWhitelistInternal() {
2046 synchronized (this) {
2047 return mTempWhitelistAppIdArray;
2048 }
2049 }
2050
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002051 void addPowerSaveTempWhitelistAppChecked(String packageName, long duration,
2052 int userId, String reason) throws RemoteException {
2053 getContext().enforceCallingPermission(
2054 Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
2055 "No permission to change device idle whitelist");
2056 final int callingUid = Binder.getCallingUid();
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002057 userId = ActivityManager.getService().handleIncomingUser(
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002058 Binder.getCallingPid(),
2059 callingUid,
2060 userId,
2061 /*allowAll=*/ false,
2062 /*requireFull=*/ false,
2063 "addPowerSaveTempWhitelistApp", null);
2064 final long token = Binder.clearCallingIdentity();
2065 try {
2066 addPowerSaveTempWhitelistAppInternal(callingUid,
2067 packageName, duration, userId, true, reason);
2068 } finally {
2069 Binder.restoreCallingIdentity(token);
2070 }
2071 }
2072
Sudheer Shanka326b3112017-11-27 14:40:57 -08002073 void removePowerSaveTempWhitelistAppChecked(String packageName, int userId)
2074 throws RemoteException {
2075 getContext().enforceCallingPermission(
2076 Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
2077 "No permission to change device idle whitelist");
2078 final int callingUid = Binder.getCallingUid();
2079 userId = ActivityManager.getService().handleIncomingUser(
2080 Binder.getCallingPid(),
2081 callingUid,
2082 userId,
2083 /*allowAll=*/ false,
2084 /*requireFull=*/ false,
2085 "removePowerSaveTempWhitelistApp", null);
2086 final long token = Binder.clearCallingIdentity();
2087 try {
2088 removePowerSaveTempWhitelistAppInternal(packageName, userId);
2089 } finally {
2090 Binder.restoreCallingIdentity(token);
2091 }
2092 }
2093
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002094 /**
2095 * Adds an app to the temporary whitelist and resets the endTime for granting the
2096 * app an exemption to access network and acquire wakelocks.
2097 */
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002098 void addPowerSaveTempWhitelistAppInternal(int callingUid, String packageName,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002099 long duration, int userId, boolean sync, String reason) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002100 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07002101 int uid = getContext().getPackageManager().getPackageUidAsUser(packageName, userId);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002102 int appId = UserHandle.getAppId(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002103 addPowerSaveTempWhitelistAppDirectInternal(callingUid, appId, duration, sync, reason);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002104 } catch (NameNotFoundException e) {
2105 }
2106 }
2107
Dianne Hackborna750a632015-06-16 17:18:23 -07002108 /**
2109 * Adds an app to the temporary whitelist and resets the endTime for granting the
2110 * app an exemption to access network and acquire wakelocks.
2111 */
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002112 void addPowerSaveTempWhitelistAppDirectInternal(int callingUid, int appId,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002113 long duration, boolean sync, String reason) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002114 final long timeNow = SystemClock.elapsedRealtime();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07002115 boolean informWhitelistChanged = false;
Dianne Hackborna750a632015-06-16 17:18:23 -07002116 synchronized (this) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002117 int callingAppId = UserHandle.getAppId(callingUid);
2118 if (callingAppId >= Process.FIRST_APPLICATION_UID) {
2119 if (!mPowerSaveWhitelistSystemAppIds.get(callingAppId)) {
2120 throw new SecurityException("Calling app " + UserHandle.formatUid(callingUid)
2121 + " is not on whitelist");
2122 }
2123 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002124 duration = Math.min(duration, mConstants.MAX_TEMP_APP_WHITELIST_DURATION);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002125 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.get(appId);
2126 final boolean newEntry = entry == null;
Dianne Hackborna750a632015-06-16 17:18:23 -07002127 // Set the new end time
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002128 if (newEntry) {
2129 entry = new Pair<>(new MutableLong(0), reason);
2130 mTempWhitelistAppIdEndTimes.put(appId, entry);
2131 }
2132 entry.first.value = timeNow + duration;
Dianne Hackborna750a632015-06-16 17:18:23 -07002133 if (DEBUG) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002134 Slog.d(TAG, "Adding AppId " + appId + " to temp whitelist. New entry: " + newEntry);
Dianne Hackborna750a632015-06-16 17:18:23 -07002135 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002136 if (newEntry) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002137 // No pending timeout for the app id, post a delayed message
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002138 try {
2139 mBatteryStats.noteEvent(BatteryStats.HistoryItem.EVENT_TEMP_WHITELIST_START,
2140 reason, appId);
2141 } catch (RemoteException e) {
2142 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002143 postTempActiveTimeoutMessage(appId, duration);
Dianne Hackborn85e35642017-01-12 15:10:57 -08002144 updateTempWhitelistAppIdsLocked(appId, true);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07002145 if (sync) {
2146 informWhitelistChanged = true;
2147 } else {
2148 mHandler.obtainMessage(MSG_REPORT_TEMP_APP_WHITELIST_CHANGED, appId, 1)
2149 .sendToTarget();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002150 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002151 reportTempWhitelistChangedLocked();
2152 }
2153 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07002154 if (informWhitelistChanged) {
2155 mNetworkPolicyManagerInternal.onTempPowerSaveWhitelistChange(appId, true);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002156 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002157 }
2158
Sudheer Shanka326b3112017-11-27 14:40:57 -08002159 /**
2160 * Removes an app from the temporary whitelist and notifies the observers.
2161 */
2162 private void removePowerSaveTempWhitelistAppInternal(String packageName, int userId) {
2163 try {
2164 final int uid = getContext().getPackageManager().getPackageUidAsUser(
2165 packageName, userId);
2166 final int appId = UserHandle.getAppId(uid);
2167 removePowerSaveTempWhitelistAppDirectInternal(appId);
2168 } catch (NameNotFoundException e) {
2169 }
2170 }
2171
2172 private void removePowerSaveTempWhitelistAppDirectInternal(int appId) {
2173 synchronized (this) {
2174 final int idx = mTempWhitelistAppIdEndTimes.indexOfKey(appId);
2175 if (idx < 0) {
2176 // Nothing else to do
2177 return;
2178 }
2179 final String reason = mTempWhitelistAppIdEndTimes.valueAt(idx).second;
2180 mTempWhitelistAppIdEndTimes.removeAt(idx);
2181 onAppRemovedFromTempWhitelistLocked(appId, reason);
2182 }
2183 }
2184
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002185 private void postTempActiveTimeoutMessage(int uid, long delay) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002186 if (DEBUG) {
2187 Slog.d(TAG, "postTempActiveTimeoutMessage: uid=" + uid + ", delay=" + delay);
2188 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002189 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_TEMP_APP_WHITELIST_TIMEOUT, uid, 0),
2190 delay);
2191 }
2192
2193 void checkTempAppWhitelistTimeout(int uid) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002194 final long timeNow = SystemClock.elapsedRealtime();
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002195 if (DEBUG) {
2196 Slog.d(TAG, "checkTempAppWhitelistTimeout: uid=" + uid + ", timeNow=" + timeNow);
2197 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002198 synchronized (this) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002199 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.get(uid);
2200 if (entry == null) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002201 // Nothing to do
2202 return;
2203 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002204 if (timeNow >= entry.first.value) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002205 mTempWhitelistAppIdEndTimes.delete(uid);
Sudheer Shanka326b3112017-11-27 14:40:57 -08002206 onAppRemovedFromTempWhitelistLocked(uid, entry.second);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002207 } else {
2208 // Need more time
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002209 if (DEBUG) {
2210 Slog.d(TAG, "Time to remove UID " + uid + ": " + entry.first.value);
2211 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002212 postTempActiveTimeoutMessage(uid, entry.first.value - timeNow);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002213 }
2214 }
2215 }
2216
Sudheer Shanka326b3112017-11-27 14:40:57 -08002217 @GuardedBy("this")
2218 private void onAppRemovedFromTempWhitelistLocked(int appId, String reason) {
2219 if (DEBUG) {
2220 Slog.d(TAG, "Removing appId " + appId + " from temp whitelist");
2221 }
2222 updateTempWhitelistAppIdsLocked(appId, false);
2223 mHandler.obtainMessage(MSG_REPORT_TEMP_APP_WHITELIST_CHANGED, appId, 0)
2224 .sendToTarget();
2225 reportTempWhitelistChangedLocked();
2226 try {
2227 mBatteryStats.noteEvent(BatteryStats.HistoryItem.EVENT_TEMP_WHITELIST_FINISH,
2228 reason, appId);
2229 } catch (RemoteException e) {
2230 }
2231 }
2232
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002233 public void exitIdleInternal(String reason) {
2234 synchronized (this) {
2235 becomeActiveLocked(reason, Binder.getCallingUid());
2236 }
2237 }
2238
Kweku Adams799858b2018-10-08 17:19:08 -07002239 @VisibleForTesting
2240 boolean isNetworkConnected() {
2241 synchronized (this) {
2242 return mNetworkConnected;
2243 }
2244 }
2245
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -07002246 void updateConnectivityState(Intent connIntent) {
2247 ConnectivityService cm;
2248 synchronized (this) {
Kweku Adams799858b2018-10-08 17:19:08 -07002249 cm = mInjector.getConnectivityService();
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -07002250 }
2251 if (cm == null) {
2252 return;
2253 }
2254 // Note: can't call out to ConnectivityService with our lock held.
2255 NetworkInfo ni = cm.getActiveNetworkInfo();
2256 synchronized (this) {
Dianne Hackborn88c41352016-04-07 15:18:58 -07002257 boolean conn;
2258 if (ni == null) {
2259 conn = false;
2260 } else {
2261 if (connIntent == null) {
2262 conn = ni.isConnected();
2263 } else {
2264 final int networkType =
2265 connIntent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
2266 ConnectivityManager.TYPE_NONE);
2267 if (ni.getType() != networkType) {
2268 return;
2269 }
2270 conn = !connIntent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,
2271 false);
2272 }
2273 }
2274 if (conn != mNetworkConnected) {
2275 mNetworkConnected = conn;
2276 if (conn && mLightState == LIGHT_STATE_WAITING_FOR_NETWORK) {
2277 stepLightIdleStateLocked("network");
2278 }
2279 }
2280 }
2281 }
2282
Kweku Adams00e3a372018-09-28 16:57:09 -07002283 @VisibleForTesting
2284 boolean isScreenOn() {
Kweku Adamsb396ccf2018-09-17 16:37:15 -07002285 synchronized (this) {
2286 return mScreenOn;
2287 }
Kweku Adams00e3a372018-09-28 16:57:09 -07002288 }
2289
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -07002290 void updateInteractivityLocked() {
2291 // The interactivity state from the power manager tells us whether the display is
2292 // in a state that we need to keep things running so they will update at a normal
2293 // frequency.
2294 boolean screenOn = mPowerManager.isInteractive();
2295 if (DEBUG) Slog.d(TAG, "updateInteractivityLocked: screenOn=" + screenOn);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002296 if (!screenOn && mScreenOn) {
2297 mScreenOn = false;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002298 if (!mForceIdle) {
2299 becomeInactiveIfAppropriateLocked();
2300 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002301 } else if (screenOn) {
2302 mScreenOn = true;
Amith Yamasani396a10c2018-01-19 10:58:07 -08002303 if (!mForceIdle && (!mScreenLocked || !mConstants.WAIT_FOR_UNLOCK)) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002304 becomeActiveLocked("screen", Process.myUid());
2305 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002306 }
2307 }
2308
Kweku Adams00e3a372018-09-28 16:57:09 -07002309 @VisibleForTesting
2310 boolean isCharging() {
Kweku Adamsb396ccf2018-09-17 16:37:15 -07002311 synchronized (this) {
2312 return mCharging;
2313 }
Kweku Adams00e3a372018-09-28 16:57:09 -07002314 }
2315
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002316 void updateChargingLocked(boolean charging) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002317 if (DEBUG) Slog.i(TAG, "updateChargingLocked: charging=" + charging);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002318 if (!charging && mCharging) {
2319 mCharging = false;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002320 if (!mForceIdle) {
2321 becomeInactiveIfAppropriateLocked();
2322 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002323 } else if (charging) {
2324 mCharging = charging;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002325 if (!mForceIdle) {
2326 becomeActiveLocked("charging", Process.myUid());
2327 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002328 }
2329 }
2330
Kweku Adamsb396ccf2018-09-17 16:37:15 -07002331 @VisibleForTesting
2332 boolean isQuickDozeEnabled() {
2333 synchronized (this) {
2334 return mQuickDozeActivated;
2335 }
2336 }
2337
2338 /** Updates the quick doze flag and enters deep doze if appropriate. */
2339 @VisibleForTesting
2340 void updateQuickDozeFlagLocked(boolean enabled) {
2341 if (DEBUG) Slog.i(TAG, "updateQuickDozeFlagLocked: enabled=" + enabled);
2342 mQuickDozeActivated = enabled;
2343 if (enabled) {
2344 // If Quick Doze is enabled, see if we should go straight into it.
2345 becomeInactiveIfAppropriateLocked();
2346 }
2347 // Going from Deep Doze to Light Idle (if quick doze becomes disabled) is tricky and
2348 // probably not worth the overhead, so leave in deep doze if that's the case until the
2349 // next natural time to come out of it.
2350 }
2351
Amith Yamasani396a10c2018-01-19 10:58:07 -08002352 void keyguardShowingLocked(boolean showing) {
2353 if (DEBUG) Slog.i(TAG, "keyguardShowing=" + showing);
2354 if (mScreenLocked != showing) {
2355 mScreenLocked = showing;
2356 if (mScreenOn && !mForceIdle && !mScreenLocked) {
2357 becomeActiveLocked("unlocked", Process.myUid());
2358 }
2359 }
2360 }
2361
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002362 void scheduleReportActiveLocked(String activeReason, int activeUid) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002363 Message msg = mHandler.obtainMessage(MSG_REPORT_ACTIVE, activeUid, 0, activeReason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002364 mHandler.sendMessage(msg);
2365 }
2366
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002367 void becomeActiveLocked(String activeReason, int activeUid) {
2368 if (DEBUG) Slog.i(TAG, "becomeActiveLocked, reason = " + activeReason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002369 if (mState != STATE_ACTIVE || mLightState != STATE_ACTIVE) {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002370 EventLogTags.writeDeviceIdle(STATE_ACTIVE, activeReason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002371 EventLogTags.writeDeviceIdleLight(LIGHT_STATE_ACTIVE, activeReason);
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002372 scheduleReportActiveLocked(activeReason, activeUid);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002373 mState = STATE_ACTIVE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002374 mLightState = LIGHT_STATE_ACTIVE;
Adam Lesinski31c05d12015-06-09 17:34:04 -07002375 mInactiveTimeout = mConstants.INACTIVE_TIMEOUT;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002376 mCurIdleBudget = 0;
2377 mMaintenanceStartTime = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002378 resetIdleManagementLocked();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002379 resetLightIdleManagementLocked();
Amith Yamasaniac6517a2018-04-23 12:19:34 -07002380 addEvent(EVENT_NORMAL, activeReason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002381 }
2382 }
2383
Kweku Adams00e3a372018-09-28 16:57:09 -07002384 /** Must only be used in tests. */
2385 @VisibleForTesting
2386 void setDeepEnabledForTest(boolean enabled) {
Kweku Adams799858b2018-10-08 17:19:08 -07002387 synchronized (this) {
2388 mDeepEnabled = enabled;
2389 }
Kweku Adams00e3a372018-09-28 16:57:09 -07002390 }
2391
2392 /** Must only be used in tests. */
2393 @VisibleForTesting
2394 void setLightEnabledForTest(boolean enabled) {
Kweku Adams799858b2018-10-08 17:19:08 -07002395 synchronized (this) {
2396 mLightEnabled = enabled;
2397 }
Kweku Adams00e3a372018-09-28 16:57:09 -07002398 }
2399
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002400 void becomeInactiveIfAppropriateLocked() {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002401 if (DEBUG) Slog.d(TAG, "becomeInactiveIfAppropriateLocked()");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002402 if ((!mScreenOn && !mCharging) || mForceIdle) {
Kweku Adamsb396ccf2018-09-17 16:37:15 -07002403 // Become inactive and determine if we will ultimately go idle.
2404 if (mDeepEnabled) {
2405 if (mQuickDozeActivated) {
2406 if (mState == STATE_QUICK_DOZE_DELAY || mState == STATE_IDLE
2407 || mState == STATE_IDLE_MAINTENANCE) {
2408 // Already "idling". Don't want to restart the process.
2409 // mLightState can't be LIGHT_STATE_ACTIVE if mState is any of these 3
2410 // values, so returning here is safe.
2411 return;
2412 }
2413 if (DEBUG) {
2414 Slog.d(TAG, "Moved from "
2415 + stateToString(mState) + " to STATE_QUICK_DOZE_DELAY");
2416 }
2417 mState = STATE_QUICK_DOZE_DELAY;
2418 // Make sure any motion sensing or locating is stopped.
2419 resetIdleManagementLocked();
2420 // Wait a small amount of time in case something (eg: background service from
2421 // recently closed app) needs to finish running.
2422 scheduleAlarmLocked(mConstants.QUICK_DOZE_DELAY_TIMEOUT, false);
2423 EventLogTags.writeDeviceIdle(mState, "no activity");
2424 } else if (mState == STATE_ACTIVE) {
2425 mState = STATE_INACTIVE;
2426 if (DEBUG) Slog.d(TAG, "Moved from STATE_ACTIVE to STATE_INACTIVE");
2427 resetIdleManagementLocked();
2428 scheduleAlarmLocked(mInactiveTimeout, false);
2429 EventLogTags.writeDeviceIdle(mState, "no activity");
2430 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002431 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08002432 if (mLightState == LIGHT_STATE_ACTIVE && mLightEnabled) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002433 mLightState = LIGHT_STATE_INACTIVE;
2434 if (DEBUG) Slog.d(TAG, "Moved from LIGHT_STATE_ACTIVE to LIGHT_STATE_INACTIVE");
2435 resetLightIdleManagementLocked();
Dianne Hackborn953fc942016-03-29 15:36:24 -07002436 scheduleLightAlarmLocked(mConstants.LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002437 EventLogTags.writeDeviceIdleLight(mLightState, "no activity");
2438 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002439 }
2440 }
2441
Kweku Adams00e3a372018-09-28 16:57:09 -07002442 private void resetIdleManagementLocked() {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002443 mNextIdlePendingDelay = 0;
2444 mNextIdleDelay = 0;
Dianne Hackborn953fc942016-03-29 15:36:24 -07002445 mNextLightIdleDelay = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002446 cancelAlarmLocked();
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002447 cancelSensingTimeoutAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002448 cancelLocatingLocked();
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002449 stopMonitoringMotionLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002450 mAnyMotionDetector.stop();
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002451 }
2452
Kweku Adams00e3a372018-09-28 16:57:09 -07002453 private void resetLightIdleManagementLocked() {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002454 cancelLightAlarmLocked();
2455 }
2456
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002457 void exitForceIdleLocked() {
2458 if (mForceIdle) {
2459 mForceIdle = false;
2460 if (mScreenOn || mCharging) {
Dianne Hackborn88c41352016-04-07 15:18:58 -07002461 becomeActiveLocked("exit-force", Process.myUid());
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002462 }
2463 }
2464 }
2465
Kweku Adamsa457f4e2018-10-03 15:56:06 -07002466 /**
2467 * Must only be used in tests.
2468 *
2469 * This sets the state value directly and thus doesn't trigger any behavioral changes.
2470 */
2471 @VisibleForTesting
2472 void setLightStateForTest(int lightState) {
Kweku Adams799858b2018-10-08 17:19:08 -07002473 synchronized (this) {
2474 mLightState = lightState;
2475 }
Kweku Adamsa457f4e2018-10-03 15:56:06 -07002476 }
2477
Kweku Adams00e3a372018-09-28 16:57:09 -07002478 @VisibleForTesting
2479 int getLightState() {
2480 return mLightState;
2481 }
2482
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002483 void stepLightIdleStateLocked(String reason) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002484 if (mLightState == LIGHT_STATE_OVERRIDE) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002485 // If we are already in deep device idle mode, then
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002486 // there is nothing left to do for light mode.
2487 return;
2488 }
2489
2490 if (DEBUG) Slog.d(TAG, "stepLightIdleStateLocked: mLightState=" + mLightState);
2491 EventLogTags.writeDeviceIdleLightStep();
2492
2493 switch (mLightState) {
2494 case LIGHT_STATE_INACTIVE:
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002495 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
Dianne Hackborn953fc942016-03-29 15:36:24 -07002496 // Reset the upcoming idle delays.
2497 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002498 mMaintenanceStartTime = 0;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002499 if (!isOpsInactiveLocked()) {
2500 // We have some active ops going on... give them a chance to finish
2501 // before going in to our first idle.
2502 mLightState = LIGHT_STATE_PRE_IDLE;
2503 EventLogTags.writeDeviceIdleLight(mLightState, reason);
2504 scheduleLightAlarmLocked(mConstants.LIGHT_PRE_IDLE_TIMEOUT);
2505 break;
2506 }
2507 // Nothing active, fall through to immediately idle.
2508 case LIGHT_STATE_PRE_IDLE:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002509 case LIGHT_STATE_IDLE_MAINTENANCE:
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002510 if (mMaintenanceStartTime != 0) {
2511 long duration = SystemClock.elapsedRealtime() - mMaintenanceStartTime;
2512 if (duration < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
2513 // We didn't use up all of our minimum budget; add this to the reserve.
2514 mCurIdleBudget += (mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET-duration);
2515 } else {
2516 // We used more than our minimum budget; this comes out of the reserve.
2517 mCurIdleBudget -= (duration-mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET);
2518 }
2519 }
2520 mMaintenanceStartTime = 0;
Dianne Hackborn953fc942016-03-29 15:36:24 -07002521 scheduleLightAlarmLocked(mNextLightIdleDelay);
2522 mNextLightIdleDelay = Math.min(mConstants.LIGHT_MAX_IDLE_TIMEOUT,
2523 (long)(mNextLightIdleDelay * mConstants.LIGHT_IDLE_FACTOR));
2524 if (mNextLightIdleDelay < mConstants.LIGHT_IDLE_TIMEOUT) {
2525 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
2526 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002527 if (DEBUG) Slog.d(TAG, "Moved to LIGHT_STATE_IDLE.");
2528 mLightState = LIGHT_STATE_IDLE;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002529 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Amith Yamasaniac6517a2018-04-23 12:19:34 -07002530 addEvent(EVENT_LIGHT_IDLE, null);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08002531 mGoingIdleWakeLock.acquire();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002532 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON_LIGHT);
2533 break;
2534 case LIGHT_STATE_IDLE:
Dianne Hackborn88c41352016-04-07 15:18:58 -07002535 case LIGHT_STATE_WAITING_FOR_NETWORK:
2536 if (mNetworkConnected || mLightState == LIGHT_STATE_WAITING_FOR_NETWORK) {
2537 // We have been idling long enough, now it is time to do some work.
2538 mActiveIdleOpCount = 1;
2539 mActiveIdleWakeLock.acquire();
2540 mMaintenanceStartTime = SystemClock.elapsedRealtime();
2541 if (mCurIdleBudget < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
2542 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
2543 } else if (mCurIdleBudget > mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET) {
2544 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET;
2545 }
2546 scheduleLightAlarmLocked(mCurIdleBudget);
2547 if (DEBUG) Slog.d(TAG,
2548 "Moved from LIGHT_STATE_IDLE to LIGHT_STATE_IDLE_MAINTENANCE.");
2549 mLightState = LIGHT_STATE_IDLE_MAINTENANCE;
2550 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Amith Yamasaniac6517a2018-04-23 12:19:34 -07002551 addEvent(EVENT_LIGHT_MAINTENANCE, null);
Dianne Hackborn88c41352016-04-07 15:18:58 -07002552 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
2553 } else {
2554 // We'd like to do maintenance, but currently don't have network
2555 // connectivity... let's try to wait until the network comes back.
2556 // We'll only wait for another full idle period, however, and then give up.
2557 scheduleLightAlarmLocked(mNextLightIdleDelay);
2558 if (DEBUG) Slog.d(TAG, "Moved to LIGHT_WAITING_FOR_NETWORK.");
2559 mLightState = LIGHT_STATE_WAITING_FOR_NETWORK;
2560 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002561 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002562 break;
2563 }
2564 }
2565
Kweku Adams00e3a372018-09-28 16:57:09 -07002566 @VisibleForTesting
2567 int getState() {
2568 return mState;
2569 }
2570
2571 @VisibleForTesting
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002572 void stepIdleStateLocked(String reason) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002573 if (DEBUG) Slog.d(TAG, "stepIdleStateLocked: mState=" + mState);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002574 EventLogTags.writeDeviceIdleStep();
2575
2576 final long now = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07002577 if ((now+mConstants.MIN_TIME_TO_ALARM) > mAlarmManager.getNextWakeFromIdleTime()) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002578 // Whoops, there is an upcoming alarm. We don't actually want to go idle.
2579 if (mState != STATE_ACTIVE) {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002580 becomeActiveLocked("alarm", Process.myUid());
Koji Fukui27b33302015-12-16 19:43:01 +09002581 becomeInactiveIfAppropriateLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002582 }
2583 return;
2584 }
2585
2586 switch (mState) {
2587 case STATE_INACTIVE:
2588 // We have now been inactive long enough, it is time to start looking
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002589 // for motion and sleep some more while doing so.
2590 startMonitoringMotionLocked();
Adam Lesinski31c05d12015-06-09 17:34:04 -07002591 scheduleAlarmLocked(mConstants.IDLE_AFTER_INACTIVE_TIMEOUT, false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002592 mState = STATE_IDLE_PENDING;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002593 if (DEBUG) Slog.d(TAG, "Moved from STATE_INACTIVE to STATE_IDLE_PENDING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002594 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002595 break;
2596 case STATE_IDLE_PENDING:
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002597 mState = STATE_SENSING;
2598 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE_PENDING to STATE_SENSING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002599 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002600 cancelLocatingLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002601 mLocated = false;
2602 mLastGenericLocation = null;
2603 mLastGpsLocation = null;
Robin Leec4d424c2018-12-07 15:09:13 +01002604
2605 // If we have an accelerometer, wait to find out whether we are moving.
2606 if (mUseMotionSensor && mAnyMotionDetector.hasSensor()) {
2607 scheduleSensingTimeoutAlarmLocked(mConstants.SENSING_TIMEOUT);
2608 mNotMoving = false;
2609 mAnyMotionDetector.checkForAnyMotion();
2610 break;
2611 }
2612
2613 mNotMoving = true;
2614 // Otherwise, fall through and check this off the list of requirements.
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002615 case STATE_SENSING:
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002616 cancelSensingTimeoutAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002617 mState = STATE_LOCATING;
2618 if (DEBUG) Slog.d(TAG, "Moved from STATE_SENSING to STATE_LOCATING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002619 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002620 scheduleAlarmLocked(mConstants.LOCATING_TIMEOUT, false);
Kweku Adams799858b2018-10-08 17:19:08 -07002621 LocationManager locationManager = mInjector.getLocationManager();
2622 if (locationManager != null
2623 && locationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
2624 locationManager.requestLocationUpdates(mLocationRequest,
Joe LaPenna23d681b2015-08-27 15:12:11 -07002625 mGenericLocationListener, mHandler.getLooper());
2626 mLocating = true;
2627 } else {
2628 mHasNetworkLocation = false;
2629 }
Kweku Adams799858b2018-10-08 17:19:08 -07002630 if (locationManager != null
2631 && locationManager.getProvider(LocationManager.GPS_PROVIDER) != null) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07002632 mHasGps = true;
Kweku Adams799858b2018-10-08 17:19:08 -07002633 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 5,
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002634 mGpsLocationListener, mHandler.getLooper());
Joe LaPenna23d681b2015-08-27 15:12:11 -07002635 mLocating = true;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002636 } else {
Joe LaPenna23d681b2015-08-27 15:12:11 -07002637 mHasGps = false;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002638 }
Joe LaPenna23d681b2015-08-27 15:12:11 -07002639 // If we have a location provider, we're all set, the listeners will move state
2640 // forward.
2641 if (mLocating) {
2642 break;
2643 }
2644
2645 // Otherwise, we have to move from locating into idle maintenance.
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002646 case STATE_LOCATING:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002647 cancelAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002648 cancelLocatingLocked();
2649 mAnyMotionDetector.stop();
Dianne Hackborn953fc942016-03-29 15:36:24 -07002650
Kweku Adamsb396ccf2018-09-17 16:37:15 -07002651 // Intentional fallthrough -- time to go into IDLE state.
2652 case STATE_QUICK_DOZE_DELAY:
2653 // Reset the upcoming idle delays.
2654 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
2655 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
2656
2657 // Everything is in place to go into IDLE state.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002658 case STATE_IDLE_MAINTENANCE:
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002659 scheduleAlarmLocked(mNextIdleDelay, true);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002660 if (DEBUG) Slog.d(TAG, "Moved to STATE_IDLE. Next alarm in " + mNextIdleDelay +
2661 " ms.");
Adam Lesinski31c05d12015-06-09 17:34:04 -07002662 mNextIdleDelay = (long)(mNextIdleDelay * mConstants.IDLE_FACTOR);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002663 if (DEBUG) Slog.d(TAG, "Setting mNextIdleDelay = " + mNextIdleDelay);
Adam Lesinski31c05d12015-06-09 17:34:04 -07002664 mNextIdleDelay = Math.min(mNextIdleDelay, mConstants.MAX_IDLE_TIMEOUT);
Dianne Hackborn953fc942016-03-29 15:36:24 -07002665 if (mNextIdleDelay < mConstants.IDLE_TIMEOUT) {
2666 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
2667 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002668 mState = STATE_IDLE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002669 if (mLightState != LIGHT_STATE_OVERRIDE) {
2670 mLightState = LIGHT_STATE_OVERRIDE;
2671 cancelLightAlarmLocked();
2672 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002673 EventLogTags.writeDeviceIdle(mState, reason);
Amith Yamasaniac6517a2018-04-23 12:19:34 -07002674 addEvent(EVENT_DEEP_IDLE, null);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08002675 mGoingIdleWakeLock.acquire();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002676 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON);
2677 break;
2678 case STATE_IDLE:
2679 // We have been idling long enough, now it is time to do some work.
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002680 mActiveIdleOpCount = 1;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002681 mActiveIdleWakeLock.acquire();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002682 scheduleAlarmLocked(mNextIdlePendingDelay, false);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002683 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE to STATE_IDLE_MAINTENANCE. " +
2684 "Next alarm in " + mNextIdlePendingDelay + " ms.");
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002685 mMaintenanceStartTime = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07002686 mNextIdlePendingDelay = Math.min(mConstants.MAX_IDLE_PENDING_TIMEOUT,
2687 (long)(mNextIdlePendingDelay * mConstants.IDLE_PENDING_FACTOR));
Dianne Hackborn953fc942016-03-29 15:36:24 -07002688 if (mNextIdlePendingDelay < mConstants.IDLE_PENDING_TIMEOUT) {
2689 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
2690 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002691 mState = STATE_IDLE_MAINTENANCE;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002692 EventLogTags.writeDeviceIdle(mState, reason);
Amith Yamasaniac6517a2018-04-23 12:19:34 -07002693 addEvent(EVENT_DEEP_MAINTENANCE, null);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002694 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
2695 break;
2696 }
2697 }
2698
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002699 void incActiveIdleOps() {
2700 synchronized (this) {
2701 mActiveIdleOpCount++;
2702 }
2703 }
2704
2705 void decActiveIdleOps() {
2706 synchronized (this) {
2707 mActiveIdleOpCount--;
2708 if (mActiveIdleOpCount <= 0) {
2709 exitMaintenanceEarlyIfNeededLocked();
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002710 mActiveIdleWakeLock.release();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002711 }
2712 }
2713 }
2714
Kweku Adamsa457f4e2018-10-03 15:56:06 -07002715 /** Must only be used in tests. */
2716 @VisibleForTesting
2717 void setActiveIdleOpsForTest(int count) {
Kweku Adams799858b2018-10-08 17:19:08 -07002718 synchronized (this) {
2719 mActiveIdleOpCount = count;
2720 }
Kweku Adamsa457f4e2018-10-03 15:56:06 -07002721 }
2722
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002723 void setJobsActive(boolean active) {
2724 synchronized (this) {
2725 mJobsActive = active;
Yao Chenca5edbb2016-01-13 14:44:36 -08002726 reportMaintenanceActivityIfNeededLocked();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002727 if (!active) {
2728 exitMaintenanceEarlyIfNeededLocked();
2729 }
2730 }
2731 }
2732
2733 void setAlarmsActive(boolean active) {
2734 synchronized (this) {
2735 mAlarmsActive = active;
2736 if (!active) {
2737 exitMaintenanceEarlyIfNeededLocked();
2738 }
2739 }
2740 }
2741
Yao Chenca5edbb2016-01-13 14:44:36 -08002742 boolean registerMaintenanceActivityListener(IMaintenanceActivityListener listener) {
2743 synchronized (this) {
2744 mMaintenanceActivityListeners.register(listener);
2745 return mReportedMaintenanceActivity;
2746 }
2747 }
2748
2749 void unregisterMaintenanceActivityListener(IMaintenanceActivityListener listener) {
2750 synchronized (this) {
2751 mMaintenanceActivityListeners.unregister(listener);
2752 }
2753 }
2754
2755 void reportMaintenanceActivityIfNeededLocked() {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07002756 boolean active = mJobsActive;
Yao Chenca5edbb2016-01-13 14:44:36 -08002757 if (active == mReportedMaintenanceActivity) {
2758 return;
2759 }
2760 mReportedMaintenanceActivity = active;
2761 Message msg = mHandler.obtainMessage(MSG_REPORT_MAINTENANCE_ACTIVITY,
2762 mReportedMaintenanceActivity ? 1 : 0, 0);
2763 mHandler.sendMessage(msg);
2764 }
2765
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002766 boolean isOpsInactiveLocked() {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07002767 return mActiveIdleOpCount <= 0 && !mJobsActive && !mAlarmsActive;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002768 }
2769
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002770 void exitMaintenanceEarlyIfNeededLocked() {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002771 if (mState == STATE_IDLE_MAINTENANCE || mLightState == LIGHT_STATE_IDLE_MAINTENANCE
2772 || mLightState == LIGHT_STATE_PRE_IDLE) {
2773 if (isOpsInactiveLocked()) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002774 final long now = SystemClock.elapsedRealtime();
2775 if (DEBUG) {
2776 StringBuilder sb = new StringBuilder();
2777 sb.append("Exit: start=");
2778 TimeUtils.formatDuration(mMaintenanceStartTime, sb);
2779 sb.append(" now=");
2780 TimeUtils.formatDuration(now, sb);
2781 Slog.d(TAG, sb.toString());
2782 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002783 if (mState == STATE_IDLE_MAINTENANCE) {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002784 stepIdleStateLocked("s:early");
2785 } else if (mLightState == LIGHT_STATE_PRE_IDLE) {
2786 stepLightIdleStateLocked("s:predone");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002787 } else {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002788 stepLightIdleStateLocked("s:early");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002789 }
2790 }
2791 }
2792 }
2793
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002794 void motionLocked() {
2795 if (DEBUG) Slog.d(TAG, "motionLocked()");
2796 // The motion sensor will have been disabled at this point
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002797 handleMotionDetectedLocked(mConstants.MOTION_INACTIVE_TIMEOUT, "motion");
2798 }
2799
2800 void handleMotionDetectedLocked(long timeout, String type) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002801 // The device is not yet active, so we want to go back to the pending idle
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002802 // state to wait again for no motion. Note that we only monitor for motion
2803 // after moving out of the inactive state, so no need to worry about that.
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002804 boolean becomeInactive = false;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002805 if (mState != STATE_ACTIVE) {
Amith Yamasani4cb42572018-04-27 10:02:57 -07002806 // Motion shouldn't affect light state, if it's already in doze-light or maintenance
2807 boolean lightIdle = mLightState == LIGHT_STATE_IDLE
2808 || mLightState == LIGHT_STATE_WAITING_FOR_NETWORK
2809 || mLightState == LIGHT_STATE_IDLE_MAINTENANCE;
2810 if (!lightIdle) {
2811 // Only switch to active state if we're not in either idle state
2812 scheduleReportActiveLocked(type, Process.myUid());
2813 addEvent(EVENT_NORMAL, type);
2814 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002815 mState = STATE_ACTIVE;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002816 mInactiveTimeout = timeout;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002817 mCurIdleBudget = 0;
2818 mMaintenanceStartTime = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002819 EventLogTags.writeDeviceIdle(mState, type);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002820 becomeInactive = true;
2821 }
2822 if (mLightState == LIGHT_STATE_OVERRIDE) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002823 // We went out of light idle mode because we had started deep idle mode... let's
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002824 // now go back and reset things so we resume light idling if appropriate.
Amith Yamasani4cb42572018-04-27 10:02:57 -07002825 mLightState = LIGHT_STATE_ACTIVE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002826 EventLogTags.writeDeviceIdleLight(mLightState, type);
2827 becomeInactive = true;
2828 }
2829 if (becomeInactive) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002830 becomeInactiveIfAppropriateLocked();
2831 }
2832 }
2833
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002834 void receivedGenericLocationLocked(Location location) {
2835 if (mState != STATE_LOCATING) {
2836 cancelLocatingLocked();
2837 return;
2838 }
2839 if (DEBUG) Slog.d(TAG, "Generic location: " + location);
2840 mLastGenericLocation = new Location(location);
Joe LaPenna23d681b2015-08-27 15:12:11 -07002841 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY && mHasGps) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002842 return;
2843 }
2844 mLocated = true;
2845 if (mNotMoving) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002846 stepIdleStateLocked("s:location");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002847 }
2848 }
2849
2850 void receivedGpsLocationLocked(Location location) {
2851 if (mState != STATE_LOCATING) {
2852 cancelLocatingLocked();
2853 return;
2854 }
2855 if (DEBUG) Slog.d(TAG, "GPS location: " + location);
2856 mLastGpsLocation = new Location(location);
2857 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY) {
2858 return;
2859 }
2860 mLocated = true;
2861 if (mNotMoving) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002862 stepIdleStateLocked("s:gps");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002863 }
2864 }
2865
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002866 void startMonitoringMotionLocked() {
2867 if (DEBUG) Slog.d(TAG, "startMonitoringMotionLocked()");
2868 if (mMotionSensor != null && !mMotionListener.active) {
2869 mMotionListener.registerLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002870 }
2871 }
2872
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002873 void stopMonitoringMotionLocked() {
2874 if (DEBUG) Slog.d(TAG, "stopMonitoringMotionLocked()");
2875 if (mMotionSensor != null && mMotionListener.active) {
2876 mMotionListener.unregisterLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002877 }
2878 }
2879
2880 void cancelAlarmLocked() {
2881 if (mNextAlarmTime != 0) {
2882 mNextAlarmTime = 0;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002883 mAlarmManager.cancel(mDeepAlarmListener);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002884 }
2885 }
2886
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002887 void cancelLightAlarmLocked() {
2888 if (mNextLightAlarmTime != 0) {
2889 mNextLightAlarmTime = 0;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002890 mAlarmManager.cancel(mLightAlarmListener);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002891 }
2892 }
2893
2894 void cancelLocatingLocked() {
2895 if (mLocating) {
Kweku Adams799858b2018-10-08 17:19:08 -07002896 LocationManager locationManager = mInjector.getLocationManager();
2897 locationManager.removeUpdates(mGenericLocationListener);
2898 locationManager.removeUpdates(mGpsLocationListener);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002899 mLocating = false;
2900 }
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002901 }
2902
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002903 void cancelSensingTimeoutAlarmLocked() {
2904 if (mNextSensingTimeoutAlarmTime != 0) {
2905 mNextSensingTimeoutAlarmTime = 0;
2906 mAlarmManager.cancel(mSensingTimeoutAlarmListener);
2907 }
2908 }
2909
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002910 void scheduleAlarmLocked(long delay, boolean idleUntil) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002911 if (DEBUG) Slog.d(TAG, "scheduleAlarmLocked(" + delay + ", " + idleUntil + ")");
Robin Leec4d424c2018-12-07 15:09:13 +01002912
2913 if (mUseMotionSensor && mMotionSensor == null
2914 && mState != STATE_QUICK_DOZE_DELAY
2915 && mState != STATE_IDLE
2916 && mState != STATE_IDLE_MAINTENANCE) {
2917 // If there is no motion sensor on this device, but we need one, then we won't schedule
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002918 // alarms, because we can't determine if the device is not moving. This effectively
Joe LaPenna23d681b2015-08-27 15:12:11 -07002919 // turns off normal execution of device idling, although it is still possible to
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002920 // manually poke it by pretending like the alarm is going off.
Kweku Adamsb396ccf2018-09-17 16:37:15 -07002921 // STATE_QUICK_DOZE_DELAY skips the motion sensing so if the state is past the motion
2922 // sensing stage (ie, is QUICK_DOZE_DELAY, IDLE, or IDLE_MAINTENANCE), then idling
2923 // can continue until the user interacts with the device.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002924 return;
2925 }
2926 mNextAlarmTime = SystemClock.elapsedRealtime() + delay;
2927 if (idleUntil) {
2928 mAlarmManager.setIdleUntil(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002929 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002930 } else {
2931 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002932 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002933 }
2934 }
2935
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002936 void scheduleLightAlarmLocked(long delay) {
2937 if (DEBUG) Slog.d(TAG, "scheduleLightAlarmLocked(" + delay + ")");
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002938 mNextLightAlarmTime = SystemClock.elapsedRealtime() + delay;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002939 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002940 mNextLightAlarmTime, "DeviceIdleController.light", mLightAlarmListener, mHandler);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002941 }
2942
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002943 void scheduleSensingTimeoutAlarmLocked(long delay) {
2944 if (DEBUG) Slog.d(TAG, "scheduleSensingAlarmLocked(" + delay + ")");
2945 mNextSensingTimeoutAlarmTime = SystemClock.elapsedRealtime() + delay;
2946 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, mNextSensingTimeoutAlarmTime,
2947 "DeviceIdleController.sensing", mSensingTimeoutAlarmListener, mHandler);
2948 }
2949
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002950 private static int[] buildAppIdArray(ArrayMap<String, Integer> systemApps,
2951 ArrayMap<String, Integer> userApps, SparseBooleanArray outAppIds) {
2952 outAppIds.clear();
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002953 if (systemApps != null) {
2954 for (int i = 0; i < systemApps.size(); i++) {
2955 outAppIds.put(systemApps.valueAt(i), true);
2956 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002957 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002958 if (userApps != null) {
2959 for (int i = 0; i < userApps.size(); i++) {
2960 outAppIds.put(userApps.valueAt(i), true);
2961 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002962 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002963 int size = outAppIds.size();
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002964 int[] appids = new int[size];
2965 for (int i = 0; i < size; i++) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002966 appids[i] = outAppIds.keyAt(i);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002967 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002968 return appids;
2969 }
2970
2971 private void updateWhitelistAppIdsLocked() {
2972 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(mPowerSaveWhitelistAppsExceptIdle,
2973 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistExceptIdleAppIds);
2974 mPowerSaveWhitelistAllAppIdArray = buildAppIdArray(mPowerSaveWhitelistApps,
2975 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistAllAppIds);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002976 mPowerSaveWhitelistUserAppIdArray = buildAppIdArray(null,
2977 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistUserAppIds);
Dianne Hackborn85e35642017-01-12 15:10:57 -08002978 if (mLocalActivityManager != null) {
Makoto Onukiaf8ff4f2018-06-04 14:44:19 -07002979 mLocalActivityManager.setDeviceIdleWhitelist(
2980 mPowerSaveWhitelistAllAppIdArray, mPowerSaveWhitelistExceptIdleAppIdArray);
Dianne Hackborn85e35642017-01-12 15:10:57 -08002981 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002982 if (mLocalPowerManager != null) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002983 if (DEBUG) {
2984 Slog.d(TAG, "Setting wakelock whitelist to "
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002985 + Arrays.toString(mPowerSaveWhitelistAllAppIdArray));
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002986 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002987 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002988 }
Suprabh Shukla5bf49812018-05-24 18:38:50 -07002989 passWhiteListsToForceAppStandbyTrackerLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002990 }
2991
Dianne Hackborn85e35642017-01-12 15:10:57 -08002992 private void updateTempWhitelistAppIdsLocked(int appId, boolean adding) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002993 final int size = mTempWhitelistAppIdEndTimes.size();
2994 if (mTempWhitelistAppIdArray.length != size) {
2995 mTempWhitelistAppIdArray = new int[size];
2996 }
2997 for (int i = 0; i < size; i++) {
2998 mTempWhitelistAppIdArray[i] = mTempWhitelistAppIdEndTimes.keyAt(i);
2999 }
Dianne Hackborn85e35642017-01-12 15:10:57 -08003000 if (mLocalActivityManager != null) {
3001 if (DEBUG) {
3002 Slog.d(TAG, "Setting activity manager temp whitelist to "
3003 + Arrays.toString(mTempWhitelistAppIdArray));
3004 }
3005 mLocalActivityManager.updateDeviceIdleTempWhitelist(mTempWhitelistAppIdArray, appId,
3006 adding);
3007 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003008 if (mLocalPowerManager != null) {
3009 if (DEBUG) {
3010 Slog.d(TAG, "Setting wakelock temp whitelist to "
3011 + Arrays.toString(mTempWhitelistAppIdArray));
3012 }
3013 mLocalPowerManager.setDeviceIdleTempWhitelist(mTempWhitelistAppIdArray);
3014 }
Suprabh Shukla5bf49812018-05-24 18:38:50 -07003015 passWhiteListsToForceAppStandbyTrackerLocked();
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003016 }
3017
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003018 private void reportPowerSaveWhitelistChangedLocked() {
3019 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
3020 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Xiaohui Chene4de5a02015-09-22 15:33:31 -07003021 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003022 }
3023
3024 private void reportTempWhitelistChangedLocked() {
3025 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_TEMP_WHITELIST_CHANGED);
3026 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Xiaohui Chene4de5a02015-09-22 15:33:31 -07003027 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003028 }
3029
Suprabh Shukla5bf49812018-05-24 18:38:50 -07003030 private void passWhiteListsToForceAppStandbyTrackerLocked() {
Makoto Onukie4918212018-02-06 11:30:15 -08003031 mAppStateTracker.setPowerSaveWhitelistAppIds(
Makoto Onuki71755c92018-01-16 14:15:44 -08003032 mPowerSaveWhitelistExceptIdleAppIdArray,
Suprabh Shukla5bf49812018-05-24 18:38:50 -07003033 mPowerSaveWhitelistUserAppIdArray,
Makoto Onuki2206af32017-11-21 16:25:35 -08003034 mTempWhitelistAppIdArray);
3035 }
3036
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003037 void readConfigFileLocked() {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003038 if (DEBUG) Slog.d(TAG, "Reading config from " + mConfigFile.getBaseFile());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003039 mPowerSaveWhitelistUserApps.clear();
3040 FileInputStream stream;
3041 try {
3042 stream = mConfigFile.openRead();
3043 } catch (FileNotFoundException e) {
3044 return;
3045 }
3046 try {
3047 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003048 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003049 readConfigFileLocked(parser);
3050 } catch (XmlPullParserException e) {
3051 } finally {
3052 try {
3053 stream.close();
3054 } catch (IOException e) {
3055 }
3056 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003057 }
3058
3059 private void readConfigFileLocked(XmlPullParser parser) {
3060 final PackageManager pm = getContext().getPackageManager();
3061
3062 try {
3063 int type;
3064 while ((type = parser.next()) != XmlPullParser.START_TAG
3065 && type != XmlPullParser.END_DOCUMENT) {
3066 ;
3067 }
3068
3069 if (type != XmlPullParser.START_TAG) {
3070 throw new IllegalStateException("no start tag found");
3071 }
3072
3073 int outerDepth = parser.getDepth();
3074 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3075 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3076 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3077 continue;
3078 }
3079
3080 String tagName = parser.getName();
Suprabh Shukla08105642017-09-26 14:45:30 -07003081 switch (tagName) {
3082 case "wl":
3083 String name = parser.getAttributeValue(null, "n");
3084 if (name != null) {
3085 try {
3086 ApplicationInfo ai = pm.getApplicationInfo(name,
3087 PackageManager.MATCH_ANY_USER);
3088 mPowerSaveWhitelistUserApps.put(ai.packageName,
3089 UserHandle.getAppId(ai.uid));
3090 } catch (PackageManager.NameNotFoundException e) {
3091 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003092 }
Suprabh Shukla08105642017-09-26 14:45:30 -07003093 break;
3094 case "un-wl":
3095 final String packageName = parser.getAttributeValue(null, "n");
3096 if (mPowerSaveWhitelistApps.containsKey(packageName)) {
3097 mRemovedFromSystemWhitelistApps.put(packageName,
3098 mPowerSaveWhitelistApps.remove(packageName));
3099 }
3100 break;
3101 default:
3102 Slog.w(TAG, "Unknown element under <config>: "
3103 + parser.getName());
3104 XmlUtils.skipCurrentTag(parser);
3105 break;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003106 }
3107 }
3108
3109 } catch (IllegalStateException e) {
3110 Slog.w(TAG, "Failed parsing config " + e);
3111 } catch (NullPointerException e) {
3112 Slog.w(TAG, "Failed parsing config " + e);
3113 } catch (NumberFormatException e) {
3114 Slog.w(TAG, "Failed parsing config " + e);
3115 } catch (XmlPullParserException e) {
3116 Slog.w(TAG, "Failed parsing config " + e);
3117 } catch (IOException e) {
3118 Slog.w(TAG, "Failed parsing config " + e);
3119 } catch (IndexOutOfBoundsException e) {
3120 Slog.w(TAG, "Failed parsing config " + e);
3121 }
3122 }
3123
3124 void writeConfigFileLocked() {
3125 mHandler.removeMessages(MSG_WRITE_CONFIG);
3126 mHandler.sendEmptyMessageDelayed(MSG_WRITE_CONFIG, 5000);
3127 }
3128
3129 void handleWriteConfigFile() {
3130 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
3131
3132 try {
3133 synchronized (this) {
3134 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003135 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003136 writeConfigFileLocked(out);
3137 }
3138 } catch (IOException e) {
3139 }
3140
3141 synchronized (mConfigFile) {
3142 FileOutputStream stream = null;
3143 try {
3144 stream = mConfigFile.startWrite();
3145 memStream.writeTo(stream);
3146 stream.flush();
3147 FileUtils.sync(stream);
3148 stream.close();
3149 mConfigFile.finishWrite(stream);
3150 } catch (IOException e) {
3151 Slog.w(TAG, "Error writing config file", e);
3152 mConfigFile.failWrite(stream);
3153 }
3154 }
3155 }
3156
3157 void writeConfigFileLocked(XmlSerializer out) throws IOException {
3158 out.startDocument(null, true);
3159 out.startTag(null, "config");
3160 for (int i=0; i<mPowerSaveWhitelistUserApps.size(); i++) {
3161 String name = mPowerSaveWhitelistUserApps.keyAt(i);
3162 out.startTag(null, "wl");
3163 out.attribute(null, "n", name);
3164 out.endTag(null, "wl");
3165 }
Suprabh Shukla08105642017-09-26 14:45:30 -07003166 for (int i = 0; i < mRemovedFromSystemWhitelistApps.size(); i++) {
3167 out.startTag(null, "un-wl");
3168 out.attribute(null, "n", mRemovedFromSystemWhitelistApps.keyAt(i));
3169 out.endTag(null, "un-wl");
3170 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003171 out.endTag(null, "config");
3172 out.endDocument();
3173 }
3174
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003175 static void dumpHelp(PrintWriter pw) {
3176 pw.println("Device idle controller (deviceidle) commands:");
3177 pw.println(" help");
3178 pw.println(" Print this help text.");
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003179 pw.println(" step [light|deep]");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003180 pw.println(" Immediately step to next state, without waiting for alarm.");
Dianne Hackborn88c41352016-04-07 15:18:58 -07003181 pw.println(" force-idle [light|deep]");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003182 pw.println(" Force directly into idle mode, regardless of other device state.");
Dianne Hackborn88c41352016-04-07 15:18:58 -07003183 pw.println(" force-inactive");
3184 pw.println(" Force to be inactive, ready to freely step idle states.");
3185 pw.println(" unforce");
3186 pw.println(" Resume normal functioning after force-idle or force-inactive.");
3187 pw.println(" get [light|deep|force|screen|charging|network]");
3188 pw.println(" Retrieve the current given state.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08003189 pw.println(" disable [light|deep|all]");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003190 pw.println(" Completely disable device idle mode.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08003191 pw.println(" enable [light|deep|all]");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003192 pw.println(" Re-enable device idle mode after it had previously been disabled.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08003193 pw.println(" enabled [light|deep|all]");
Dianne Hackborn92617032015-06-19 15:32:19 -07003194 pw.println(" Print 1 if device idle mode is currently enabled, else 0.");
Dianne Hackborn1b139682015-07-06 15:13:37 -07003195 pw.println(" whitelist");
3196 pw.println(" Print currently whitelisted apps.");
Dianne Hackborn92617032015-06-19 15:32:19 -07003197 pw.println(" whitelist [package ...]");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003198 pw.println(" Add (prefix with +) or remove (prefix with -) packages.");
Suprabh Shukla08105642017-09-26 14:45:30 -07003199 pw.println(" sys-whitelist [package ...|reset]");
3200 pw.println(" Prefix the package with '-' to remove it from the system whitelist or '+'"
3201 + " to put it back in the system whitelist.");
3202 pw.println(" Note that only packages that were"
3203 + " earlier removed from the system whitelist can be added back.");
3204 pw.println(" reset will reset the whitelist to the original state");
3205 pw.println(" Prints the system whitelist if no arguments are specified");
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07003206 pw.println(" except-idle-whitelist [package ...|reset]");
3207 pw.println(" Prefix the package with '+' to add it to whitelist or "
3208 + "'=' to check if it is already whitelisted");
3209 pw.println(" [reset] will reset the whitelist to it's original state");
3210 pw.println(" Note that unlike <whitelist> cmd, "
3211 + "changes made using this won't be persisted across boots");
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003212 pw.println(" tempwhitelist");
3213 pw.println(" Print packages that are temporarily whitelisted.");
Sudheer Shanka326b3112017-11-27 14:40:57 -08003214 pw.println(" tempwhitelist [-u USER] [-d DURATION] [-r] [package]");
3215 pw.println(" Temporarily place package in whitelist for DURATION milliseconds.");
Dianne Hackborn85e35642017-01-12 15:10:57 -08003216 pw.println(" If no DURATION is specified, 10 seconds is used");
Sudheer Shanka326b3112017-11-27 14:40:57 -08003217 pw.println(" If [-r] option is used, then the package is removed from temp whitelist "
3218 + "and any [-d] is ignored");
Amith Yamasani4cb42572018-04-27 10:02:57 -07003219 pw.println(" motion");
3220 pw.println(" Simulate a motion event to bring the device out of deep doze");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003221 }
3222
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003223 class Shell extends ShellCommand {
3224 int userId = UserHandle.USER_SYSTEM;
3225
3226 @Override
3227 public int onCommand(String cmd) {
3228 return onShellCommand(this, cmd);
3229 }
3230
3231 @Override
3232 public void onHelp() {
3233 PrintWriter pw = getOutPrintWriter();
3234 dumpHelp(pw);
3235 }
3236 }
3237
3238 int onShellCommand(Shell shell, String cmd) {
3239 PrintWriter pw = shell.getOutPrintWriter();
3240 if ("step".equals(cmd)) {
3241 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3242 null);
3243 synchronized (this) {
3244 long token = Binder.clearCallingIdentity();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003245 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003246 try {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003247 if (arg == null || "deep".equals(arg)) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003248 stepIdleStateLocked("s:shell");
3249 pw.print("Stepped to deep: ");
3250 pw.println(stateToString(mState));
3251 } else if ("light".equals(arg)) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003252 stepLightIdleStateLocked("s:shell");
3253 pw.print("Stepped to light: "); pw.println(lightStateToString(mLightState));
3254 } else {
3255 pw.println("Unknown idle mode: " + arg);
3256 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003257 } finally {
3258 Binder.restoreCallingIdentity(token);
3259 }
3260 }
3261 } else if ("force-idle".equals(cmd)) {
3262 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3263 null);
3264 synchronized (this) {
3265 long token = Binder.clearCallingIdentity();
Dianne Hackborn88c41352016-04-07 15:18:58 -07003266 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003267 try {
Dianne Hackborn88c41352016-04-07 15:18:58 -07003268 if (arg == null || "deep".equals(arg)) {
3269 if (!mDeepEnabled) {
3270 pw.println("Unable to go deep idle; not enabled");
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003271 return -1;
3272 }
Dianne Hackborn88c41352016-04-07 15:18:58 -07003273 mForceIdle = true;
3274 becomeInactiveIfAppropriateLocked();
3275 int curState = mState;
3276 while (curState != STATE_IDLE) {
3277 stepIdleStateLocked("s:shell");
3278 if (curState == mState) {
3279 pw.print("Unable to go deep idle; stopped at ");
3280 pw.println(stateToString(mState));
3281 exitForceIdleLocked();
3282 return -1;
3283 }
3284 curState = mState;
3285 }
3286 pw.println("Now forced in to deep idle mode");
3287 } else if ("light".equals(arg)) {
3288 mForceIdle = true;
3289 becomeInactiveIfAppropriateLocked();
3290 int curLightState = mLightState;
3291 while (curLightState != LIGHT_STATE_IDLE) {
Tej Singh93cf3e32017-12-07 13:05:38 -08003292 stepLightIdleStateLocked("s:shell");
Dianne Hackborn88c41352016-04-07 15:18:58 -07003293 if (curLightState == mLightState) {
3294 pw.print("Unable to go light idle; stopped at ");
3295 pw.println(lightStateToString(mLightState));
3296 exitForceIdleLocked();
3297 return -1;
3298 }
3299 curLightState = mLightState;
3300 }
3301 pw.println("Now forced in to light idle mode");
3302 } else {
3303 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003304 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003305 } finally {
3306 Binder.restoreCallingIdentity(token);
3307 }
3308 }
Dianne Hackborn88c41352016-04-07 15:18:58 -07003309 } else if ("force-inactive".equals(cmd)) {
3310 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3311 null);
3312 synchronized (this) {
3313 long token = Binder.clearCallingIdentity();
3314 try {
3315 mForceIdle = true;
3316 becomeInactiveIfAppropriateLocked();
3317 pw.print("Light state: ");
3318 pw.print(lightStateToString(mLightState));
3319 pw.print(", deep state: ");
3320 pw.println(stateToString(mState));
3321 } finally {
3322 Binder.restoreCallingIdentity(token);
3323 }
3324 }
3325 } else if ("unforce".equals(cmd)) {
3326 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3327 null);
3328 synchronized (this) {
3329 long token = Binder.clearCallingIdentity();
3330 try {
3331 exitForceIdleLocked();
3332 pw.print("Light state: ");
3333 pw.print(lightStateToString(mLightState));
3334 pw.print(", deep state: ");
3335 pw.println(stateToString(mState));
3336 } finally {
3337 Binder.restoreCallingIdentity(token);
3338 }
3339 }
3340 } else if ("get".equals(cmd)) {
3341 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3342 null);
3343 synchronized (this) {
3344 String arg = shell.getNextArg();
3345 if (arg != null) {
3346 long token = Binder.clearCallingIdentity();
3347 try {
3348 switch (arg) {
3349 case "light": pw.println(lightStateToString(mLightState)); break;
3350 case "deep": pw.println(stateToString(mState)); break;
3351 case "force": pw.println(mForceIdle); break;
Kweku Adamsb396ccf2018-09-17 16:37:15 -07003352 case "quick": pw.println(mQuickDozeActivated); break;
Dianne Hackborn88c41352016-04-07 15:18:58 -07003353 case "screen": pw.println(mScreenOn); break;
3354 case "charging": pw.println(mCharging); break;
3355 case "network": pw.println(mNetworkConnected); break;
3356 default: pw.println("Unknown get option: " + arg); break;
3357 }
3358 } finally {
3359 Binder.restoreCallingIdentity(token);
3360 }
3361 } else {
3362 pw.println("Argument required");
3363 }
3364 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003365 } else if ("disable".equals(cmd)) {
3366 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3367 null);
3368 synchronized (this) {
3369 long token = Binder.clearCallingIdentity();
Dianne Hackbornb6843652016-02-22 12:20:13 -08003370 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003371 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08003372 boolean becomeActive = false;
3373 boolean valid = false;
3374 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
3375 valid = true;
3376 if (mDeepEnabled) {
3377 mDeepEnabled = false;
3378 becomeActive = true;
3379 pw.println("Deep idle mode disabled");
3380 }
3381 }
3382 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
3383 valid = true;
3384 if (mLightEnabled) {
3385 mLightEnabled = false;
3386 becomeActive = true;
3387 pw.println("Light idle mode disabled");
3388 }
3389 }
3390 if (becomeActive) {
3391 becomeActiveLocked((arg == null ? "all" : arg) + "-disabled",
3392 Process.myUid());
3393 }
3394 if (!valid) {
3395 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003396 }
3397 } finally {
3398 Binder.restoreCallingIdentity(token);
3399 }
3400 }
3401 } else if ("enable".equals(cmd)) {
3402 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3403 null);
3404 synchronized (this) {
3405 long token = Binder.clearCallingIdentity();
Dianne Hackbornb6843652016-02-22 12:20:13 -08003406 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003407 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08003408 boolean becomeInactive = false;
3409 boolean valid = false;
3410 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
3411 valid = true;
3412 if (!mDeepEnabled) {
3413 mDeepEnabled = true;
3414 becomeInactive = true;
3415 pw.println("Deep idle mode enabled");
3416 }
3417 }
3418 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
3419 valid = true;
3420 if (!mLightEnabled) {
3421 mLightEnabled = true;
3422 becomeInactive = true;
3423 pw.println("Light idle mode enable");
3424 }
3425 }
3426 if (becomeInactive) {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003427 becomeInactiveIfAppropriateLocked();
Dianne Hackbornb6843652016-02-22 12:20:13 -08003428 }
3429 if (!valid) {
3430 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003431 }
3432 } finally {
3433 Binder.restoreCallingIdentity(token);
3434 }
3435 }
3436 } else if ("enabled".equals(cmd)) {
3437 synchronized (this) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08003438 String arg = shell.getNextArg();
3439 if (arg == null || "all".equals(arg)) {
3440 pw.println(mDeepEnabled && mLightEnabled ? "1" : 0);
3441 } else if ("deep".equals(arg)) {
3442 pw.println(mDeepEnabled ? "1" : 0);
3443 } else if ("light".equals(arg)) {
3444 pw.println(mLightEnabled ? "1" : 0);
3445 } else {
3446 pw.println("Unknown idle mode: " + arg);
3447 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003448 }
3449 } else if ("whitelist".equals(cmd)) {
Dianne Hackborneb909e32016-09-29 14:35:15 -07003450 String arg = shell.getNextArg();
3451 if (arg != null) {
3452 getContext().enforceCallingOrSelfPermission(
3453 android.Manifest.permission.DEVICE_POWER, null);
3454 long token = Binder.clearCallingIdentity();
3455 try {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003456 do {
3457 if (arg.length() < 1 || (arg.charAt(0) != '-'
Felipe Lemef8a46232016-02-10 13:51:54 -08003458 && arg.charAt(0) != '+' && arg.charAt(0) != '=')) {
3459 pw.println("Package must be prefixed with +, -, or =: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003460 return -1;
3461 }
3462 char op = arg.charAt(0);
3463 String pkg = arg.substring(1);
3464 if (op == '+') {
3465 if (addPowerSaveWhitelistAppInternal(pkg)) {
3466 pw.println("Added: " + pkg);
3467 } else {
3468 pw.println("Unknown package: " + pkg);
3469 }
Felipe Lemef8a46232016-02-10 13:51:54 -08003470 } else if (op == '-') {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003471 if (removePowerSaveWhitelistAppInternal(pkg)) {
3472 pw.println("Removed: " + pkg);
3473 }
Felipe Lemef8a46232016-02-10 13:51:54 -08003474 } else {
3475 pw.println(getPowerSaveWhitelistAppInternal(pkg));
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003476 }
3477 } while ((arg=shell.getNextArg()) != null);
Dianne Hackborneb909e32016-09-29 14:35:15 -07003478 } finally {
3479 Binder.restoreCallingIdentity(token);
3480 }
3481 } else {
3482 synchronized (this) {
3483 for (int j=0; j<mPowerSaveWhitelistAppsExceptIdle.size(); j++) {
3484 pw.print("system-excidle,");
3485 pw.print(mPowerSaveWhitelistAppsExceptIdle.keyAt(j));
3486 pw.print(",");
3487 pw.println(mPowerSaveWhitelistAppsExceptIdle.valueAt(j));
3488 }
3489 for (int j=0; j<mPowerSaveWhitelistApps.size(); j++) {
3490 pw.print("system,");
3491 pw.print(mPowerSaveWhitelistApps.keyAt(j));
3492 pw.print(",");
3493 pw.println(mPowerSaveWhitelistApps.valueAt(j));
3494 }
3495 for (int j=0; j<mPowerSaveWhitelistUserApps.size(); j++) {
3496 pw.print("user,");
3497 pw.print(mPowerSaveWhitelistUserApps.keyAt(j));
3498 pw.print(",");
3499 pw.println(mPowerSaveWhitelistUserApps.valueAt(j));
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003500 }
3501 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003502 }
3503 } else if ("tempwhitelist".equals(cmd)) {
Dianne Hackborn85e35642017-01-12 15:10:57 -08003504 long duration = 10000;
Sudheer Shanka326b3112017-11-27 14:40:57 -08003505 boolean removePkg = false;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003506 String opt;
3507 while ((opt=shell.getNextOption()) != null) {
3508 if ("-u".equals(opt)) {
3509 opt = shell.getNextArg();
3510 if (opt == null) {
3511 pw.println("-u requires a user number");
3512 return -1;
3513 }
3514 shell.userId = Integer.parseInt(opt);
Dianne Hackborn85e35642017-01-12 15:10:57 -08003515 } else if ("-d".equals(opt)) {
3516 opt = shell.getNextArg();
3517 if (opt == null) {
3518 pw.println("-d requires a duration");
3519 return -1;
3520 }
3521 duration = Long.parseLong(opt);
Sudheer Shanka326b3112017-11-27 14:40:57 -08003522 } else if ("-r".equals(opt)) {
3523 removePkg = true;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003524 }
3525 }
3526 String arg = shell.getNextArg();
3527 if (arg != null) {
3528 try {
Sudheer Shanka326b3112017-11-27 14:40:57 -08003529 if (removePkg) {
3530 removePowerSaveTempWhitelistAppChecked(arg, shell.userId);
3531 } else {
3532 addPowerSaveTempWhitelistAppChecked(arg, duration, shell.userId, "shell");
3533 }
Christopher Tateec3a9f32017-03-21 17:43:47 -07003534 } catch (Exception e) {
3535 pw.println("Failed: " + e);
3536 return -1;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003537 }
Sudheer Shanka326b3112017-11-27 14:40:57 -08003538 } else if (removePkg) {
3539 pw.println("[-r] requires a package name");
3540 return -1;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003541 } else {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003542 dumpTempWhitelistSchedule(pw, false);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003543 }
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07003544 } else if ("except-idle-whitelist".equals(cmd)) {
3545 getContext().enforceCallingOrSelfPermission(
3546 android.Manifest.permission.DEVICE_POWER, null);
3547 final long token = Binder.clearCallingIdentity();
3548 try {
3549 String arg = shell.getNextArg();
3550 if (arg == null) {
3551 pw.println("No arguments given");
3552 return -1;
3553 } else if ("reset".equals(arg)) {
3554 resetPowerSaveWhitelistExceptIdleInternal();
3555 } else {
3556 do {
3557 if (arg.length() < 1 || (arg.charAt(0) != '-'
3558 && arg.charAt(0) != '+' && arg.charAt(0) != '=')) {
3559 pw.println("Package must be prefixed with +, -, or =: " + arg);
3560 return -1;
3561 }
3562 char op = arg.charAt(0);
3563 String pkg = arg.substring(1);
3564 if (op == '+') {
3565 if (addPowerSaveWhitelistExceptIdleInternal(pkg)) {
3566 pw.println("Added: " + pkg);
3567 } else {
3568 pw.println("Unknown package: " + pkg);
3569 }
3570 } else if (op == '=') {
3571 pw.println(getPowerSaveWhitelistExceptIdleInternal(pkg));
3572 } else {
3573 pw.println("Unknown argument: " + arg);
3574 return -1;
3575 }
3576 } while ((arg = shell.getNextArg()) != null);
3577 }
3578 } finally {
3579 Binder.restoreCallingIdentity(token);
3580 }
Suprabh Shukla08105642017-09-26 14:45:30 -07003581 } else if ("sys-whitelist".equals(cmd)) {
3582 String arg = shell.getNextArg();
3583 if (arg != null) {
3584 getContext().enforceCallingOrSelfPermission(
3585 android.Manifest.permission.DEVICE_POWER, null);
3586 final long token = Binder.clearCallingIdentity();
3587 try {
3588 if ("reset".equals(arg)) {
3589 resetSystemPowerWhitelistInternal();
3590 } else {
3591 do {
3592 if (arg.length() < 1
3593 || (arg.charAt(0) != '-' && arg.charAt(0) != '+')) {
3594 pw.println("Package must be prefixed with + or - " + arg);
3595 return -1;
3596 }
3597 final char op = arg.charAt(0);
3598 final String pkg = arg.substring(1);
3599 switch (op) {
3600 case '+':
3601 if (restoreSystemPowerWhitelistAppInternal(pkg)) {
3602 pw.println("Restored " + pkg);
3603 }
3604 break;
3605 case '-':
3606 if (removeSystemPowerWhitelistAppInternal(pkg)) {
3607 pw.println("Removed " + pkg);
3608 }
3609 break;
3610 }
3611 } while ((arg = shell.getNextArg()) != null);
3612 }
3613 } finally {
3614 Binder.restoreCallingIdentity(token);
3615 }
3616 } else {
3617 synchronized (this) {
Amith Yamasani4cb42572018-04-27 10:02:57 -07003618 for (int j = 0; j < mPowerSaveWhitelistApps.size(); j++) {
Suprabh Shukla08105642017-09-26 14:45:30 -07003619 pw.print(mPowerSaveWhitelistApps.keyAt(j));
3620 pw.print(",");
3621 pw.println(mPowerSaveWhitelistApps.valueAt(j));
3622 }
3623 }
3624 }
Amith Yamasani4cb42572018-04-27 10:02:57 -07003625 } else if ("motion".equals(cmd)) {
3626 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3627 null);
3628 synchronized (this) {
3629 long token = Binder.clearCallingIdentity();
3630 try {
3631 motionLocked();
3632 pw.print("Light state: ");
3633 pw.print(lightStateToString(mLightState));
3634 pw.print(", deep state: ");
3635 pw.println(stateToString(mState));
3636 } finally {
3637 Binder.restoreCallingIdentity(token);
3638 }
3639 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003640 } else {
3641 return shell.handleDefaultCommands(cmd);
3642 }
3643 return 0;
3644 }
3645
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003646 void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003647 if (!DumpUtils.checkDumpPermission(getContext(), TAG, pw)) return;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003648
3649 if (args != null) {
Xiaohui Chen7c696362015-09-16 09:56:14 -07003650 int userId = UserHandle.USER_SYSTEM;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003651 for (int i=0; i<args.length; i++) {
3652 String arg = args[i];
3653 if ("-h".equals(arg)) {
3654 dumpHelp(pw);
3655 return;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003656 } else if ("-u".equals(arg)) {
3657 i++;
3658 if (i < args.length) {
3659 arg = args[i];
3660 userId = Integer.parseInt(arg);
3661 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003662 } else if ("-a".equals(arg)) {
3663 // Ignore, we always dump all.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003664 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
3665 pw.println("Unknown option: " + arg);
3666 return;
3667 } else {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003668 Shell shell = new Shell();
3669 shell.userId = userId;
3670 String[] newArgs = new String[args.length-i];
3671 System.arraycopy(args, i, newArgs, 0, args.length-i);
Dianne Hackborn354736e2016-08-22 17:00:05 -07003672 shell.exec(mBinderService, null, fd, null, newArgs, null,
3673 new ResultReceiver(null));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003674 return;
3675 }
3676 }
3677 }
3678
3679 synchronized (this) {
Dianne Hackborna750a632015-06-16 17:18:23 -07003680 mConstants.dump(pw);
3681
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08003682 if (mEventCmds[0] != EVENT_NULL) {
3683 pw.println(" Idling history:");
3684 long now = SystemClock.elapsedRealtime();
3685 for (int i=EVENT_BUFFER_SIZE-1; i>=0; i--) {
3686 int cmd = mEventCmds[i];
3687 if (cmd == EVENT_NULL) {
3688 continue;
3689 }
3690 String label;
3691 switch (mEventCmds[i]) {
3692 case EVENT_NORMAL: label = " normal"; break;
3693 case EVENT_LIGHT_IDLE: label = " light-idle"; break;
3694 case EVENT_LIGHT_MAINTENANCE: label = "light-maint"; break;
Dianne Hackbornb6843652016-02-22 12:20:13 -08003695 case EVENT_DEEP_IDLE: label = " deep-idle"; break;
3696 case EVENT_DEEP_MAINTENANCE: label = " deep-maint"; break;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08003697 default: label = " ??"; break;
3698 }
3699 pw.print(" ");
3700 pw.print(label);
3701 pw.print(": ");
Amith Yamasaniac6517a2018-04-23 12:19:34 -07003702 TimeUtils.formatDuration(mEventTimes[i], now, pw);
3703 if (mEventReasons[i] != null) {
3704 pw.print(" (");
3705 pw.print(mEventReasons[i]);
3706 pw.print(")");
3707 }
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08003708 pw.println();
Amith Yamasaniac6517a2018-04-23 12:19:34 -07003709
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08003710 }
3711 }
3712
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003713 int size = mPowerSaveWhitelistAppsExceptIdle.size();
3714 if (size > 0) {
3715 pw.println(" Whitelist (except idle) system apps:");
3716 for (int i = 0; i < size; i++) {
3717 pw.print(" ");
3718 pw.println(mPowerSaveWhitelistAppsExceptIdle.keyAt(i));
3719 }
3720 }
3721 size = mPowerSaveWhitelistApps.size();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003722 if (size > 0) {
3723 pw.println(" Whitelist system apps:");
3724 for (int i = 0; i < size; i++) {
3725 pw.print(" ");
3726 pw.println(mPowerSaveWhitelistApps.keyAt(i));
3727 }
3728 }
Suprabh Shukla08105642017-09-26 14:45:30 -07003729 size = mRemovedFromSystemWhitelistApps.size();
3730 if (size > 0) {
3731 pw.println(" Removed from whitelist system apps:");
3732 for (int i = 0; i < size; i++) {
3733 pw.print(" ");
3734 pw.println(mRemovedFromSystemWhitelistApps.keyAt(i));
3735 }
3736 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003737 size = mPowerSaveWhitelistUserApps.size();
3738 if (size > 0) {
3739 pw.println(" Whitelist user apps:");
3740 for (int i = 0; i < size; i++) {
3741 pw.print(" ");
3742 pw.println(mPowerSaveWhitelistUserApps.keyAt(i));
3743 }
3744 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003745 size = mPowerSaveWhitelistExceptIdleAppIds.size();
3746 if (size > 0) {
3747 pw.println(" Whitelist (except idle) all app ids:");
3748 for (int i = 0; i < size; i++) {
3749 pw.print(" ");
3750 pw.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
3751 pw.println();
3752 }
3753 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08003754 size = mPowerSaveWhitelistUserAppIds.size();
3755 if (size > 0) {
3756 pw.println(" Whitelist user app ids:");
3757 for (int i = 0; i < size; i++) {
3758 pw.print(" ");
3759 pw.print(mPowerSaveWhitelistUserAppIds.keyAt(i));
3760 pw.println();
3761 }
3762 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07003763 size = mPowerSaveWhitelistAllAppIds.size();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003764 if (size > 0) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07003765 pw.println(" Whitelist all app ids:");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003766 for (int i = 0; i < size; i++) {
Dianne Hackborna750a632015-06-16 17:18:23 -07003767 pw.print(" ");
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07003768 pw.print(mPowerSaveWhitelistAllAppIds.keyAt(i));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003769 pw.println();
3770 }
3771 }
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003772 dumpTempWhitelistSchedule(pw, true);
3773
Dianne Hackborna750a632015-06-16 17:18:23 -07003774 size = mTempWhitelistAppIdArray != null ? mTempWhitelistAppIdArray.length : 0;
3775 if (size > 0) {
3776 pw.println(" Temp whitelist app ids:");
3777 for (int i = 0; i < size; i++) {
3778 pw.print(" ");
3779 pw.print(mTempWhitelistAppIdArray[i]);
3780 pw.println();
3781 }
3782 }
Adam Lesinski31c05d12015-06-09 17:34:04 -07003783
Dianne Hackbornb6843652016-02-22 12:20:13 -08003784 pw.print(" mLightEnabled="); pw.print(mLightEnabled);
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003785 pw.print(" mDeepEnabled="); pw.println(mDeepEnabled);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003786 pw.print(" mForceIdle="); pw.println(mForceIdle);
Robin Leec4d424c2018-12-07 15:09:13 +01003787 pw.print(" mUseMotionSensor="); pw.print(mUseMotionSensor);
3788 if (mUseMotionSensor) {
3789 pw.print(" mMotionSensor="); pw.println(mMotionSensor);
3790 } else {
3791 pw.println();
3792 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003793 pw.print(" mScreenOn="); pw.println(mScreenOn);
Amith Yamasani396a10c2018-01-19 10:58:07 -08003794 pw.print(" mScreenLocked="); pw.println(mScreenLocked);
Dianne Hackborn88c41352016-04-07 15:18:58 -07003795 pw.print(" mNetworkConnected="); pw.println(mNetworkConnected);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003796 pw.print(" mCharging="); pw.println(mCharging);
Nick Vaccaro20feaea2015-09-17 17:22:44 -07003797 pw.print(" mMotionActive="); pw.println(mMotionListener.active);
Robin Leec4d424c2018-12-07 15:09:13 +01003798 if (mUseMotionSensor) {
3799 pw.print(" mNotMoving="); pw.println(mNotMoving);
3800 }
Joe LaPenna23d681b2015-08-27 15:12:11 -07003801 pw.print(" mLocating="); pw.print(mLocating); pw.print(" mHasGps=");
3802 pw.print(mHasGps); pw.print(" mHasNetwork=");
3803 pw.print(mHasNetworkLocation); pw.print(" mLocated="); pw.println(mLocated);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07003804 if (mLastGenericLocation != null) {
3805 pw.print(" mLastGenericLocation="); pw.println(mLastGenericLocation);
3806 }
3807 if (mLastGpsLocation != null) {
3808 pw.print(" mLastGpsLocation="); pw.println(mLastGpsLocation);
3809 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003810 pw.print(" mState="); pw.print(stateToString(mState));
3811 pw.print(" mLightState=");
3812 pw.println(lightStateToString(mLightState));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003813 pw.print(" mInactiveTimeout="); TimeUtils.formatDuration(mInactiveTimeout, pw);
3814 pw.println();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003815 if (mActiveIdleOpCount != 0) {
3816 pw.print(" mActiveIdleOpCount="); pw.println(mActiveIdleOpCount);
3817 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003818 if (mNextAlarmTime != 0) {
3819 pw.print(" mNextAlarmTime=");
3820 TimeUtils.formatDuration(mNextAlarmTime, SystemClock.elapsedRealtime(), pw);
3821 pw.println();
3822 }
3823 if (mNextIdlePendingDelay != 0) {
3824 pw.print(" mNextIdlePendingDelay=");
3825 TimeUtils.formatDuration(mNextIdlePendingDelay, pw);
3826 pw.println();
3827 }
3828 if (mNextIdleDelay != 0) {
3829 pw.print(" mNextIdleDelay=");
3830 TimeUtils.formatDuration(mNextIdleDelay, pw);
3831 pw.println();
3832 }
Dianne Hackborn953fc942016-03-29 15:36:24 -07003833 if (mNextLightIdleDelay != 0) {
3834 pw.print(" mNextIdleDelay=");
3835 TimeUtils.formatDuration(mNextLightIdleDelay, pw);
3836 pw.println();
3837 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003838 if (mNextLightAlarmTime != 0) {
3839 pw.print(" mNextLightAlarmTime=");
3840 TimeUtils.formatDuration(mNextLightAlarmTime, SystemClock.elapsedRealtime(), pw);
3841 pw.println();
3842 }
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08003843 if (mCurIdleBudget != 0) {
3844 pw.print(" mCurIdleBudget=");
3845 TimeUtils.formatDuration(mCurIdleBudget, pw);
3846 pw.println();
3847 }
3848 if (mMaintenanceStartTime != 0) {
3849 pw.print(" mMaintenanceStartTime=");
3850 TimeUtils.formatDuration(mMaintenanceStartTime, SystemClock.elapsedRealtime(), pw);
3851 pw.println();
3852 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003853 if (mJobsActive) {
3854 pw.print(" mJobsActive="); pw.println(mJobsActive);
3855 }
3856 if (mAlarmsActive) {
3857 pw.print(" mAlarmsActive="); pw.println(mAlarmsActive);
3858 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003859 }
3860 }
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003861
3862 void dumpTempWhitelistSchedule(PrintWriter pw, boolean printTitle) {
3863 final int size = mTempWhitelistAppIdEndTimes.size();
3864 if (size > 0) {
3865 String prefix = "";
3866 if (printTitle) {
3867 pw.println(" Temp whitelist schedule:");
3868 prefix = " ";
3869 }
3870 final long timeNow = SystemClock.elapsedRealtime();
3871 for (int i = 0; i < size; i++) {
3872 pw.print(prefix);
3873 pw.print("UID=");
3874 pw.print(mTempWhitelistAppIdEndTimes.keyAt(i));
3875 pw.print(": ");
3876 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.valueAt(i);
3877 TimeUtils.formatDuration(entry.first.value, timeNow, pw);
3878 pw.print(" - ");
3879 pw.println(entry.second);
3880 }
3881 }
3882 }
3883 }