blob: ac17d878684df0ffe083ea2ca0cd6a285970a4c2 [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,
Kweku Adams9da2bb92018-12-20 06:34:39 -08001034 !COMPRESS_TIME ? 4 * 60 * 1000L : 60 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -08001035 LOCATING_TIMEOUT = mParser.getDurationMillis(KEY_LOCATING_TIMEOUT,
Kweku Adams9da2bb92018-12-20 06:34:39 -08001036 !COMPRESS_TIME ? 30 * 1000L : 15 * 1000L);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001037 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;
Kweku Adams9da2bb92018-12-20 06:34:39 -08001565 private Constants mConstants;
Kweku Adams799858b2018-10-08 17:19:08 -07001566 private LocationManager mLocationManager;
Kweku Adams00e3a372018-09-28 16:57:09 -07001567
1568 Injector(Context ctx) {
1569 mContext = ctx;
1570 }
1571
1572 AlarmManager getAlarmManager() {
1573 return mContext.getSystemService(AlarmManager.class);
1574 }
1575
1576 AnyMotionDetector getAnyMotionDetector(Handler handler, SensorManager sm,
1577 AnyMotionDetector.DeviceIdleCallback callback, float angleThreshold) {
1578 return new AnyMotionDetector(getPowerManager(), handler, sm, callback, angleThreshold);
1579 }
1580
1581 AppStateTracker getAppStateTracker(Context ctx, Looper looper) {
1582 return new AppStateTracker(ctx, looper);
1583 }
1584
1585 ConnectivityService getConnectivityService() {
Kweku Adams799858b2018-10-08 17:19:08 -07001586 if (mConnectivityService == null) {
1587 mConnectivityService = (ConnectivityService) ServiceManager.getService(
1588 Context.CONNECTIVITY_SERVICE);
1589 }
1590 return mConnectivityService;
Kweku Adams00e3a372018-09-28 16:57:09 -07001591 }
1592
Kweku Adamsa457f4e2018-10-03 15:56:06 -07001593 Constants getConstants(DeviceIdleController controller, Handler handler,
1594 ContentResolver resolver) {
Kweku Adams9da2bb92018-12-20 06:34:39 -08001595 if (mConstants == null) {
1596 mConstants = controller.new Constants(handler, resolver);
1597 }
1598 return mConstants;
Kweku Adamsa457f4e2018-10-03 15:56:06 -07001599 }
1600
Kweku Adams00e3a372018-09-28 16:57:09 -07001601 LocationManager getLocationManager() {
Kweku Adams799858b2018-10-08 17:19:08 -07001602 if (mLocationManager == null) {
1603 mLocationManager = mContext.getSystemService(LocationManager.class);
1604 }
1605 return mLocationManager;
Kweku Adams00e3a372018-09-28 16:57:09 -07001606 }
1607
Kweku Adamsa457f4e2018-10-03 15:56:06 -07001608 MyHandler getHandler(DeviceIdleController controller) {
1609 return controller.new MyHandler(BackgroundThread.getHandler().getLooper());
Kweku Adams00e3a372018-09-28 16:57:09 -07001610 }
1611
1612 PowerManager getPowerManager() {
1613 return mContext.getSystemService(PowerManager.class);
1614 }
1615 }
1616
1617 private final Injector mInjector;
1618
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001619 private ActivityTaskManagerInternal.ScreenObserver mScreenObserver =
1620 new ActivityTaskManagerInternal.ScreenObserver() {
Amith Yamasani396a10c2018-01-19 10:58:07 -08001621 @Override
1622 public void onAwakeStateChanged(boolean isAwake) { }
1623
1624 @Override
1625 public void onKeyguardStateChanged(boolean isShowing) {
1626 synchronized (DeviceIdleController.this) {
1627 DeviceIdleController.this.keyguardShowingLocked(isShowing);
1628 }
1629 }
1630 };
1631
Kweku Adams00e3a372018-09-28 16:57:09 -07001632 @VisibleForTesting DeviceIdleController(Context context, Injector injector) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001633 super(context);
Kweku Adams00e3a372018-09-28 16:57:09 -07001634 mInjector = injector;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001635 mConfigFile = new AtomicFile(new File(getSystemDir(), "deviceidle.xml"));
Kweku Adams00e3a372018-09-28 16:57:09 -07001636 mHandler = mInjector.getHandler(this);
1637 mAppStateTracker = mInjector.getAppStateTracker(context, FgThread.get().getLooper());
Makoto Onukie4918212018-02-06 11:30:15 -08001638 LocalServices.addService(AppStateTracker.class, mAppStateTracker);
Robin Leec4d424c2018-12-07 15:09:13 +01001639
1640 mUseMotionSensor = context.getResources().getBoolean(
1641 com.android.internal.R.bool.config_autoPowerModeUseMotionSensor);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001642 }
1643
Kweku Adams00e3a372018-09-28 16:57:09 -07001644 public DeviceIdleController(Context context) {
1645 this(context, new Injector(context));
1646 }
1647
Christopher Tate42a386b2016-11-07 12:21:21 -08001648 boolean isAppOnWhitelistInternal(int appid) {
1649 synchronized (this) {
1650 return Arrays.binarySearch(mPowerSaveWhitelistAllAppIdArray, appid) >= 0;
1651 }
1652 }
1653
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001654 int[] getPowerSaveWhitelistUserAppIds() {
1655 synchronized (this) {
1656 return mPowerSaveWhitelistUserAppIdArray;
1657 }
1658 }
1659
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001660 private static File getSystemDir() {
1661 return new File(Environment.getDataDirectory(), "system");
1662 }
1663
1664 @Override
1665 public void onStart() {
1666 final PackageManager pm = getContext().getPackageManager();
1667
1668 synchronized (this) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001669 mLightEnabled = mDeepEnabled = getContext().getResources().getBoolean(
Dianne Hackborn92617032015-06-19 15:32:19 -07001670 com.android.internal.R.bool.config_enableAutoPowerModes);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001671 SystemConfig sysConfig = SystemConfig.getInstance();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001672 ArraySet<String> allowPowerExceptIdle = sysConfig.getAllowInPowerSaveExceptIdle();
1673 for (int i=0; i<allowPowerExceptIdle.size(); i++) {
1674 String pkg = allowPowerExceptIdle.valueAt(i);
1675 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001676 ApplicationInfo ai = pm.getApplicationInfo(pkg,
1677 PackageManager.MATCH_SYSTEM_ONLY);
1678 int appid = UserHandle.getAppId(ai.uid);
1679 mPowerSaveWhitelistAppsExceptIdle.put(ai.packageName, appid);
1680 mPowerSaveWhitelistSystemAppIdsExceptIdle.put(appid, true);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001681 } catch (PackageManager.NameNotFoundException e) {
1682 }
1683 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001684 ArraySet<String> allowPower = sysConfig.getAllowInPowerSave();
1685 for (int i=0; i<allowPower.size(); i++) {
1686 String pkg = allowPower.valueAt(i);
1687 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001688 ApplicationInfo ai = pm.getApplicationInfo(pkg,
1689 PackageManager.MATCH_SYSTEM_ONLY);
1690 int appid = UserHandle.getAppId(ai.uid);
1691 // These apps are on both the whitelist-except-idle as well
1692 // as the full whitelist, so they apply in all cases.
1693 mPowerSaveWhitelistAppsExceptIdle.put(ai.packageName, appid);
1694 mPowerSaveWhitelistSystemAppIdsExceptIdle.put(appid, true);
1695 mPowerSaveWhitelistApps.put(ai.packageName, appid);
1696 mPowerSaveWhitelistSystemAppIds.put(appid, true);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001697 } catch (PackageManager.NameNotFoundException e) {
1698 }
1699 }
1700
Kweku Adamsa457f4e2018-10-03 15:56:06 -07001701 mConstants = mInjector.getConstants(this, mHandler, getContext().getContentResolver());
Adam Lesinski31c05d12015-06-09 17:34:04 -07001702
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001703 readConfigFileLocked();
1704 updateWhitelistAppIdsLocked();
1705
Dianne Hackborn88c41352016-04-07 15:18:58 -07001706 mNetworkConnected = true;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001707 mScreenOn = true;
Amith Yamasani396a10c2018-01-19 10:58:07 -08001708 mScreenLocked = false;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001709 // Start out assuming we are charging. If we aren't, we will at least get
1710 // a battery update the next time the level drops.
1711 mCharging = true;
1712 mState = STATE_ACTIVE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001713 mLightState = LIGHT_STATE_ACTIVE;
Adam Lesinski31c05d12015-06-09 17:34:04 -07001714 mInactiveTimeout = mConstants.INACTIVE_TIMEOUT;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001715 }
1716
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001717 mBinderService = new BinderService();
1718 publishBinderService(Context.DEVICE_IDLE_CONTROLLER, mBinderService);
Dianne Hackborna750a632015-06-16 17:18:23 -07001719 publishLocalService(LocalService.class, new LocalService());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001720 }
1721
1722 @Override
1723 public void onBootPhase(int phase) {
1724 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1725 synchronized (this) {
Kweku Adams00e3a372018-09-28 16:57:09 -07001726 mAlarmManager = mInjector.getAlarmManager();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001727 mBatteryStats = BatteryStatsService.getService();
Dianne Hackborn85e35642017-01-12 15:10:57 -08001728 mLocalActivityManager = getLocalService(ActivityManagerInternal.class);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001729 mLocalActivityTaskManager = getLocalService(ActivityTaskManagerInternal.class);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001730 mLocalPowerManager = getLocalService(PowerManagerInternal.class);
Kweku Adams00e3a372018-09-28 16:57:09 -07001731 mPowerManager = mInjector.getPowerManager();
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001732 mActiveIdleWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
1733 "deviceidle_maint");
1734 mActiveIdleWakeLock.setReferenceCounted(false);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001735 mGoingIdleWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
1736 "deviceidle_going_idle");
1737 mGoingIdleWakeLock.setReferenceCounted(true);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001738 mNetworkPolicyManager = INetworkPolicyManager.Stub.asInterface(
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001739 ServiceManager.getService(Context.NETWORK_POLICY_SERVICE));
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001740 mNetworkPolicyManagerInternal = getLocalService(NetworkPolicyManagerInternal.class);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001741 mSensorManager = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
Robin Leec4d424c2018-12-07 15:09:13 +01001742
1743 if (mUseMotionSensor) {
1744 int sigMotionSensorId = getContext().getResources().getInteger(
1745 com.android.internal.R.integer.config_autoPowerModeAnyMotionSensor);
1746 if (sigMotionSensorId > 0) {
1747 mMotionSensor = mSensorManager.getDefaultSensor(sigMotionSensorId, true);
1748 }
1749 if (mMotionSensor == null && getContext().getResources().getBoolean(
1750 com.android.internal.R.bool.config_autoPowerModePreferWristTilt)) {
1751 mMotionSensor = mSensorManager.getDefaultSensor(
1752 Sensor.TYPE_WRIST_TILT_GESTURE, true);
1753 }
1754 if (mMotionSensor == null) {
1755 // As a last ditch, fall back to SMD.
1756 mMotionSensor = mSensorManager.getDefaultSensor(
1757 Sensor.TYPE_SIGNIFICANT_MOTION, true);
1758 }
Joe LaPenna23d681b2015-08-27 15:12:11 -07001759 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001760
Joe LaPenna23d681b2015-08-27 15:12:11 -07001761 if (getContext().getResources().getBoolean(
1762 com.android.internal.R.bool.config_autoPowerModePrefetchLocation)) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07001763 mLocationRequest = new LocationRequest()
1764 .setQuality(LocationRequest.ACCURACY_FINE)
1765 .setInterval(0)
1766 .setFastestInterval(0)
1767 .setNumUpdates(1);
1768 }
1769
1770 float angleThreshold = getContext().getResources().getInteger(
1771 com.android.internal.R.integer.config_autoPowerModeThresholdAngle) / 100f;
Kweku Adams00e3a372018-09-28 16:57:09 -07001772 mAnyMotionDetector = mInjector.getAnyMotionDetector(mHandler, mSensorManager, this,
1773 angleThreshold);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001774
Makoto Onukie4918212018-02-06 11:30:15 -08001775 mAppStateTracker.onSystemServicesReady();
1776
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001777 mIdleIntent = new Intent(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001778 mIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1779 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001780 mLightIdleIntent = new Intent(PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED);
1781 mLightIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1782 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001783
1784 IntentFilter filter = new IntentFilter();
1785 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001786 getContext().registerReceiver(mReceiver, filter);
Amith Yamasaniac59f75e2016-05-05 12:38:17 -07001787
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001788 filter = new IntentFilter();
1789 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1790 filter.addDataScheme("package");
Amith Yamasaniac59f75e2016-05-05 12:38:17 -07001791 getContext().registerReceiver(mReceiver, filter);
1792
Dianne Hackborn88c41352016-04-07 15:18:58 -07001793 filter = new IntentFilter();
1794 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001795 getContext().registerReceiver(mReceiver, filter);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001796
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -07001797 filter = new IntentFilter();
1798 filter.addAction(Intent.ACTION_SCREEN_OFF);
1799 filter.addAction(Intent.ACTION_SCREEN_ON);
1800 getContext().registerReceiver(mInteractivityReceiver, filter);
1801
Makoto Onukiaf8ff4f2018-06-04 14:44:19 -07001802 mLocalActivityManager.setDeviceIdleWhitelist(
1803 mPowerSaveWhitelistAllAppIdArray, mPowerSaveWhitelistExceptIdleAppIdArray);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001804 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -07001805
Kweku Adamsb396ccf2018-09-17 16:37:15 -07001806 mLocalPowerManager.registerLowPowerModeObserver(ServiceType.QUICK_DOZE,
1807 state -> {
1808 synchronized (DeviceIdleController.this) {
1809 updateQuickDozeFlagLocked(state.batterySaverEnabled);
1810 }
1811 });
1812 updateQuickDozeFlagLocked(
1813 mLocalPowerManager.getLowPowerState(
1814 ServiceType.QUICK_DOZE).batterySaverEnabled);
1815
Wale Ogunwale6767eae2018-05-03 15:52:51 -07001816 mLocalActivityTaskManager.registerScreenObserver(mScreenObserver);
Amith Yamasani396a10c2018-01-19 10:58:07 -08001817
Suprabh Shukla5bf49812018-05-24 18:38:50 -07001818 passWhiteListsToForceAppStandbyTrackerLocked();
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -07001819 updateInteractivityLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001820 }
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -07001821 updateConnectivityState(null);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001822 }
1823 }
1824
1825 public boolean addPowerSaveWhitelistAppInternal(String name) {
1826 synchronized (this) {
1827 try {
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001828 ApplicationInfo ai = getContext().getPackageManager().getApplicationInfo(name,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07001829 PackageManager.MATCH_ANY_USER);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001830 if (mPowerSaveWhitelistUserApps.put(name, UserHandle.getAppId(ai.uid)) == null) {
1831 reportPowerSaveWhitelistChangedLocked();
1832 updateWhitelistAppIdsLocked();
1833 writeConfigFileLocked();
1834 }
1835 return true;
1836 } catch (PackageManager.NameNotFoundException e) {
1837 return false;
1838 }
1839 }
1840 }
1841
1842 public boolean removePowerSaveWhitelistAppInternal(String name) {
1843 synchronized (this) {
1844 if (mPowerSaveWhitelistUserApps.remove(name) != null) {
1845 reportPowerSaveWhitelistChangedLocked();
1846 updateWhitelistAppIdsLocked();
1847 writeConfigFileLocked();
1848 return true;
1849 }
1850 }
1851 return false;
1852 }
1853
Felipe Lemef8a46232016-02-10 13:51:54 -08001854 public boolean getPowerSaveWhitelistAppInternal(String name) {
1855 synchronized (this) {
1856 return mPowerSaveWhitelistUserApps.containsKey(name);
1857 }
1858 }
1859
Suprabh Shukla08105642017-09-26 14:45:30 -07001860 void resetSystemPowerWhitelistInternal() {
1861 synchronized (this) {
1862 mPowerSaveWhitelistApps.putAll(mRemovedFromSystemWhitelistApps);
1863 mRemovedFromSystemWhitelistApps.clear();
1864 reportPowerSaveWhitelistChangedLocked();
1865 updateWhitelistAppIdsLocked();
1866 writeConfigFileLocked();
1867 }
1868 }
1869
1870 public boolean restoreSystemPowerWhitelistAppInternal(String name) {
1871 synchronized (this) {
1872 if (!mRemovedFromSystemWhitelistApps.containsKey(name)) {
1873 return false;
1874 }
1875 mPowerSaveWhitelistApps.put(name, mRemovedFromSystemWhitelistApps.remove(name));
1876 reportPowerSaveWhitelistChangedLocked();
1877 updateWhitelistAppIdsLocked();
1878 writeConfigFileLocked();
1879 return true;
1880 }
1881 }
1882
1883 public boolean removeSystemPowerWhitelistAppInternal(String name) {
1884 synchronized (this) {
1885 if (!mPowerSaveWhitelistApps.containsKey(name)) {
1886 return false;
1887 }
1888 mRemovedFromSystemWhitelistApps.put(name, mPowerSaveWhitelistApps.remove(name));
1889 reportPowerSaveWhitelistChangedLocked();
1890 updateWhitelistAppIdsLocked();
1891 writeConfigFileLocked();
1892 return true;
1893 }
1894 }
1895
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07001896 public boolean addPowerSaveWhitelistExceptIdleInternal(String name) {
1897 synchronized (this) {
1898 try {
1899 final ApplicationInfo ai = getContext().getPackageManager().getApplicationInfo(name,
1900 PackageManager.MATCH_ANY_USER);
1901 if (mPowerSaveWhitelistAppsExceptIdle.put(name, UserHandle.getAppId(ai.uid))
1902 == null) {
1903 mPowerSaveWhitelistUserAppsExceptIdle.add(name);
1904 reportPowerSaveWhitelistChangedLocked();
1905 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(
1906 mPowerSaveWhitelistAppsExceptIdle, mPowerSaveWhitelistUserApps,
1907 mPowerSaveWhitelistExceptIdleAppIds);
Makoto Onuki71755c92018-01-16 14:15:44 -08001908
Suprabh Shukla5bf49812018-05-24 18:38:50 -07001909 passWhiteListsToForceAppStandbyTrackerLocked();
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07001910 }
1911 return true;
1912 } catch (PackageManager.NameNotFoundException e) {
1913 return false;
1914 }
1915 }
1916 }
1917
1918 public void resetPowerSaveWhitelistExceptIdleInternal() {
1919 synchronized (this) {
1920 if (mPowerSaveWhitelistAppsExceptIdle.removeAll(
1921 mPowerSaveWhitelistUserAppsExceptIdle)) {
1922 reportPowerSaveWhitelistChangedLocked();
1923 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(
1924 mPowerSaveWhitelistAppsExceptIdle, mPowerSaveWhitelistUserApps,
1925 mPowerSaveWhitelistExceptIdleAppIds);
1926 mPowerSaveWhitelistUserAppsExceptIdle.clear();
Makoto Onuki71755c92018-01-16 14:15:44 -08001927
Suprabh Shukla5bf49812018-05-24 18:38:50 -07001928 passWhiteListsToForceAppStandbyTrackerLocked();
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07001929 }
1930 }
1931 }
1932
1933 public boolean getPowerSaveWhitelistExceptIdleInternal(String name) {
1934 synchronized (this) {
1935 return mPowerSaveWhitelistAppsExceptIdle.containsKey(name);
1936 }
1937 }
1938
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001939 public String[] getSystemPowerWhitelistExceptIdleInternal() {
1940 synchronized (this) {
1941 int size = mPowerSaveWhitelistAppsExceptIdle.size();
1942 String[] apps = new String[size];
1943 for (int i = 0; i < size; i++) {
1944 apps[i] = mPowerSaveWhitelistAppsExceptIdle.keyAt(i);
1945 }
1946 return apps;
1947 }
1948 }
1949
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001950 public String[] getSystemPowerWhitelistInternal() {
1951 synchronized (this) {
1952 int size = mPowerSaveWhitelistApps.size();
1953 String[] apps = new String[size];
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001954 for (int i = 0; i < size; i++) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001955 apps[i] = mPowerSaveWhitelistApps.keyAt(i);
1956 }
1957 return apps;
1958 }
1959 }
1960
Suprabh Shukla08105642017-09-26 14:45:30 -07001961 public String[] getRemovedSystemPowerWhitelistAppsInternal() {
1962 synchronized (this) {
1963 int size = mRemovedFromSystemWhitelistApps.size();
1964 final String[] apps = new String[size];
1965 for (int i = 0; i < size; i++) {
1966 apps[i] = mRemovedFromSystemWhitelistApps.keyAt(i);
1967 }
1968 return apps;
1969 }
1970 }
1971
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001972 public String[] getUserPowerWhitelistInternal() {
1973 synchronized (this) {
1974 int size = mPowerSaveWhitelistUserApps.size();
1975 String[] apps = new String[size];
1976 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1977 apps[i] = mPowerSaveWhitelistUserApps.keyAt(i);
1978 }
1979 return apps;
1980 }
1981 }
1982
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001983 public String[] getFullPowerWhitelistExceptIdleInternal() {
1984 synchronized (this) {
1985 int size = mPowerSaveWhitelistAppsExceptIdle.size() + mPowerSaveWhitelistUserApps.size();
1986 String[] apps = new String[size];
1987 int cur = 0;
1988 for (int i = 0; i < mPowerSaveWhitelistAppsExceptIdle.size(); i++) {
1989 apps[cur] = mPowerSaveWhitelistAppsExceptIdle.keyAt(i);
1990 cur++;
1991 }
1992 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1993 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
1994 cur++;
1995 }
1996 return apps;
1997 }
1998 }
1999
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002000 public String[] getFullPowerWhitelistInternal() {
2001 synchronized (this) {
2002 int size = mPowerSaveWhitelistApps.size() + mPowerSaveWhitelistUserApps.size();
2003 String[] apps = new String[size];
2004 int cur = 0;
2005 for (int i = 0; i < mPowerSaveWhitelistApps.size(); i++) {
2006 apps[cur] = mPowerSaveWhitelistApps.keyAt(i);
2007 cur++;
2008 }
2009 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
2010 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
2011 cur++;
2012 }
2013 return apps;
2014 }
2015 }
2016
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002017 public boolean isPowerSaveWhitelistExceptIdleAppInternal(String packageName) {
2018 synchronized (this) {
2019 return mPowerSaveWhitelistAppsExceptIdle.containsKey(packageName)
2020 || mPowerSaveWhitelistUserApps.containsKey(packageName);
2021 }
2022 }
2023
Amith Yamasani06bf8242015-05-08 16:36:21 -07002024 public boolean isPowerSaveWhitelistAppInternal(String packageName) {
2025 synchronized (this) {
2026 return mPowerSaveWhitelistApps.containsKey(packageName)
2027 || mPowerSaveWhitelistUserApps.containsKey(packageName);
2028 }
2029 }
2030
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002031 public int[] getAppIdWhitelistExceptIdleInternal() {
2032 synchronized (this) {
2033 return mPowerSaveWhitelistExceptIdleAppIdArray;
2034 }
2035 }
2036
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002037 public int[] getAppIdWhitelistInternal() {
2038 synchronized (this) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002039 return mPowerSaveWhitelistAllAppIdArray;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002040 }
2041 }
2042
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002043 public int[] getAppIdUserWhitelistInternal() {
2044 synchronized (this) {
2045 return mPowerSaveWhitelistUserAppIdArray;
2046 }
2047 }
2048
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002049 public int[] getAppIdTempWhitelistInternal() {
2050 synchronized (this) {
2051 return mTempWhitelistAppIdArray;
2052 }
2053 }
2054
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002055 void addPowerSaveTempWhitelistAppChecked(String packageName, long duration,
2056 int userId, String reason) throws RemoteException {
2057 getContext().enforceCallingPermission(
2058 Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
2059 "No permission to change device idle whitelist");
2060 final int callingUid = Binder.getCallingUid();
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002061 userId = ActivityManager.getService().handleIncomingUser(
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002062 Binder.getCallingPid(),
2063 callingUid,
2064 userId,
2065 /*allowAll=*/ false,
2066 /*requireFull=*/ false,
2067 "addPowerSaveTempWhitelistApp", null);
2068 final long token = Binder.clearCallingIdentity();
2069 try {
2070 addPowerSaveTempWhitelistAppInternal(callingUid,
2071 packageName, duration, userId, true, reason);
2072 } finally {
2073 Binder.restoreCallingIdentity(token);
2074 }
2075 }
2076
Sudheer Shanka326b3112017-11-27 14:40:57 -08002077 void removePowerSaveTempWhitelistAppChecked(String packageName, int userId)
2078 throws RemoteException {
2079 getContext().enforceCallingPermission(
2080 Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
2081 "No permission to change device idle whitelist");
2082 final int callingUid = Binder.getCallingUid();
2083 userId = ActivityManager.getService().handleIncomingUser(
2084 Binder.getCallingPid(),
2085 callingUid,
2086 userId,
2087 /*allowAll=*/ false,
2088 /*requireFull=*/ false,
2089 "removePowerSaveTempWhitelistApp", null);
2090 final long token = Binder.clearCallingIdentity();
2091 try {
2092 removePowerSaveTempWhitelistAppInternal(packageName, userId);
2093 } finally {
2094 Binder.restoreCallingIdentity(token);
2095 }
2096 }
2097
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002098 /**
2099 * Adds an app to the temporary whitelist and resets the endTime for granting the
2100 * app an exemption to access network and acquire wakelocks.
2101 */
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002102 void addPowerSaveTempWhitelistAppInternal(int callingUid, String packageName,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002103 long duration, int userId, boolean sync, String reason) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002104 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07002105 int uid = getContext().getPackageManager().getPackageUidAsUser(packageName, userId);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002106 int appId = UserHandle.getAppId(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002107 addPowerSaveTempWhitelistAppDirectInternal(callingUid, appId, duration, sync, reason);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002108 } catch (NameNotFoundException e) {
2109 }
2110 }
2111
Dianne Hackborna750a632015-06-16 17:18:23 -07002112 /**
2113 * Adds an app to the temporary whitelist and resets the endTime for granting the
2114 * app an exemption to access network and acquire wakelocks.
2115 */
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002116 void addPowerSaveTempWhitelistAppDirectInternal(int callingUid, int appId,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002117 long duration, boolean sync, String reason) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002118 final long timeNow = SystemClock.elapsedRealtime();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07002119 boolean informWhitelistChanged = false;
Dianne Hackborna750a632015-06-16 17:18:23 -07002120 synchronized (this) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002121 int callingAppId = UserHandle.getAppId(callingUid);
2122 if (callingAppId >= Process.FIRST_APPLICATION_UID) {
2123 if (!mPowerSaveWhitelistSystemAppIds.get(callingAppId)) {
2124 throw new SecurityException("Calling app " + UserHandle.formatUid(callingUid)
2125 + " is not on whitelist");
2126 }
2127 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002128 duration = Math.min(duration, mConstants.MAX_TEMP_APP_WHITELIST_DURATION);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002129 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.get(appId);
2130 final boolean newEntry = entry == null;
Dianne Hackborna750a632015-06-16 17:18:23 -07002131 // Set the new end time
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002132 if (newEntry) {
2133 entry = new Pair<>(new MutableLong(0), reason);
2134 mTempWhitelistAppIdEndTimes.put(appId, entry);
2135 }
2136 entry.first.value = timeNow + duration;
Dianne Hackborna750a632015-06-16 17:18:23 -07002137 if (DEBUG) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002138 Slog.d(TAG, "Adding AppId " + appId + " to temp whitelist. New entry: " + newEntry);
Dianne Hackborna750a632015-06-16 17:18:23 -07002139 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002140 if (newEntry) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002141 // No pending timeout for the app id, post a delayed message
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002142 try {
2143 mBatteryStats.noteEvent(BatteryStats.HistoryItem.EVENT_TEMP_WHITELIST_START,
2144 reason, appId);
2145 } catch (RemoteException e) {
2146 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002147 postTempActiveTimeoutMessage(appId, duration);
Dianne Hackborn85e35642017-01-12 15:10:57 -08002148 updateTempWhitelistAppIdsLocked(appId, true);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07002149 if (sync) {
2150 informWhitelistChanged = true;
2151 } else {
2152 mHandler.obtainMessage(MSG_REPORT_TEMP_APP_WHITELIST_CHANGED, appId, 1)
2153 .sendToTarget();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002154 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002155 reportTempWhitelistChangedLocked();
2156 }
2157 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07002158 if (informWhitelistChanged) {
2159 mNetworkPolicyManagerInternal.onTempPowerSaveWhitelistChange(appId, true);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002160 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002161 }
2162
Sudheer Shanka326b3112017-11-27 14:40:57 -08002163 /**
2164 * Removes an app from the temporary whitelist and notifies the observers.
2165 */
2166 private void removePowerSaveTempWhitelistAppInternal(String packageName, int userId) {
2167 try {
2168 final int uid = getContext().getPackageManager().getPackageUidAsUser(
2169 packageName, userId);
2170 final int appId = UserHandle.getAppId(uid);
2171 removePowerSaveTempWhitelistAppDirectInternal(appId);
2172 } catch (NameNotFoundException e) {
2173 }
2174 }
2175
2176 private void removePowerSaveTempWhitelistAppDirectInternal(int appId) {
2177 synchronized (this) {
2178 final int idx = mTempWhitelistAppIdEndTimes.indexOfKey(appId);
2179 if (idx < 0) {
2180 // Nothing else to do
2181 return;
2182 }
2183 final String reason = mTempWhitelistAppIdEndTimes.valueAt(idx).second;
2184 mTempWhitelistAppIdEndTimes.removeAt(idx);
2185 onAppRemovedFromTempWhitelistLocked(appId, reason);
2186 }
2187 }
2188
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002189 private void postTempActiveTimeoutMessage(int uid, long delay) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002190 if (DEBUG) {
2191 Slog.d(TAG, "postTempActiveTimeoutMessage: uid=" + uid + ", delay=" + delay);
2192 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002193 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_TEMP_APP_WHITELIST_TIMEOUT, uid, 0),
2194 delay);
2195 }
2196
2197 void checkTempAppWhitelistTimeout(int uid) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002198 final long timeNow = SystemClock.elapsedRealtime();
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002199 if (DEBUG) {
2200 Slog.d(TAG, "checkTempAppWhitelistTimeout: uid=" + uid + ", timeNow=" + timeNow);
2201 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002202 synchronized (this) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002203 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.get(uid);
2204 if (entry == null) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002205 // Nothing to do
2206 return;
2207 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002208 if (timeNow >= entry.first.value) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002209 mTempWhitelistAppIdEndTimes.delete(uid);
Sudheer Shanka326b3112017-11-27 14:40:57 -08002210 onAppRemovedFromTempWhitelistLocked(uid, entry.second);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002211 } else {
2212 // Need more time
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002213 if (DEBUG) {
2214 Slog.d(TAG, "Time to remove UID " + uid + ": " + entry.first.value);
2215 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002216 postTempActiveTimeoutMessage(uid, entry.first.value - timeNow);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002217 }
2218 }
2219 }
2220
Sudheer Shanka326b3112017-11-27 14:40:57 -08002221 @GuardedBy("this")
2222 private void onAppRemovedFromTempWhitelistLocked(int appId, String reason) {
2223 if (DEBUG) {
2224 Slog.d(TAG, "Removing appId " + appId + " from temp whitelist");
2225 }
2226 updateTempWhitelistAppIdsLocked(appId, false);
2227 mHandler.obtainMessage(MSG_REPORT_TEMP_APP_WHITELIST_CHANGED, appId, 0)
2228 .sendToTarget();
2229 reportTempWhitelistChangedLocked();
2230 try {
2231 mBatteryStats.noteEvent(BatteryStats.HistoryItem.EVENT_TEMP_WHITELIST_FINISH,
2232 reason, appId);
2233 } catch (RemoteException e) {
2234 }
2235 }
2236
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002237 public void exitIdleInternal(String reason) {
2238 synchronized (this) {
2239 becomeActiveLocked(reason, Binder.getCallingUid());
2240 }
2241 }
2242
Kweku Adams799858b2018-10-08 17:19:08 -07002243 @VisibleForTesting
2244 boolean isNetworkConnected() {
2245 synchronized (this) {
2246 return mNetworkConnected;
2247 }
2248 }
2249
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -07002250 void updateConnectivityState(Intent connIntent) {
2251 ConnectivityService cm;
2252 synchronized (this) {
Kweku Adams799858b2018-10-08 17:19:08 -07002253 cm = mInjector.getConnectivityService();
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -07002254 }
2255 if (cm == null) {
2256 return;
2257 }
2258 // Note: can't call out to ConnectivityService with our lock held.
2259 NetworkInfo ni = cm.getActiveNetworkInfo();
2260 synchronized (this) {
Dianne Hackborn88c41352016-04-07 15:18:58 -07002261 boolean conn;
2262 if (ni == null) {
2263 conn = false;
2264 } else {
2265 if (connIntent == null) {
2266 conn = ni.isConnected();
2267 } else {
2268 final int networkType =
2269 connIntent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
2270 ConnectivityManager.TYPE_NONE);
2271 if (ni.getType() != networkType) {
2272 return;
2273 }
2274 conn = !connIntent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,
2275 false);
2276 }
2277 }
2278 if (conn != mNetworkConnected) {
2279 mNetworkConnected = conn;
2280 if (conn && mLightState == LIGHT_STATE_WAITING_FOR_NETWORK) {
2281 stepLightIdleStateLocked("network");
2282 }
2283 }
2284 }
2285 }
2286
Kweku Adams00e3a372018-09-28 16:57:09 -07002287 @VisibleForTesting
2288 boolean isScreenOn() {
Kweku Adamsb396ccf2018-09-17 16:37:15 -07002289 synchronized (this) {
2290 return mScreenOn;
2291 }
Kweku Adams00e3a372018-09-28 16:57:09 -07002292 }
2293
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -07002294 void updateInteractivityLocked() {
2295 // The interactivity state from the power manager tells us whether the display is
2296 // in a state that we need to keep things running so they will update at a normal
2297 // frequency.
2298 boolean screenOn = mPowerManager.isInteractive();
2299 if (DEBUG) Slog.d(TAG, "updateInteractivityLocked: screenOn=" + screenOn);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002300 if (!screenOn && mScreenOn) {
2301 mScreenOn = false;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002302 if (!mForceIdle) {
2303 becomeInactiveIfAppropriateLocked();
2304 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002305 } else if (screenOn) {
2306 mScreenOn = true;
Amith Yamasani396a10c2018-01-19 10:58:07 -08002307 if (!mForceIdle && (!mScreenLocked || !mConstants.WAIT_FOR_UNLOCK)) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002308 becomeActiveLocked("screen", Process.myUid());
2309 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002310 }
2311 }
2312
Kweku Adams00e3a372018-09-28 16:57:09 -07002313 @VisibleForTesting
2314 boolean isCharging() {
Kweku Adamsb396ccf2018-09-17 16:37:15 -07002315 synchronized (this) {
2316 return mCharging;
2317 }
Kweku Adams00e3a372018-09-28 16:57:09 -07002318 }
2319
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002320 void updateChargingLocked(boolean charging) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002321 if (DEBUG) Slog.i(TAG, "updateChargingLocked: charging=" + charging);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002322 if (!charging && mCharging) {
2323 mCharging = false;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002324 if (!mForceIdle) {
2325 becomeInactiveIfAppropriateLocked();
2326 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002327 } else if (charging) {
2328 mCharging = charging;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002329 if (!mForceIdle) {
2330 becomeActiveLocked("charging", Process.myUid());
2331 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002332 }
2333 }
2334
Kweku Adamsb396ccf2018-09-17 16:37:15 -07002335 @VisibleForTesting
2336 boolean isQuickDozeEnabled() {
2337 synchronized (this) {
2338 return mQuickDozeActivated;
2339 }
2340 }
2341
2342 /** Updates the quick doze flag and enters deep doze if appropriate. */
2343 @VisibleForTesting
2344 void updateQuickDozeFlagLocked(boolean enabled) {
2345 if (DEBUG) Slog.i(TAG, "updateQuickDozeFlagLocked: enabled=" + enabled);
2346 mQuickDozeActivated = enabled;
2347 if (enabled) {
2348 // If Quick Doze is enabled, see if we should go straight into it.
2349 becomeInactiveIfAppropriateLocked();
2350 }
2351 // Going from Deep Doze to Light Idle (if quick doze becomes disabled) is tricky and
2352 // probably not worth the overhead, so leave in deep doze if that's the case until the
2353 // next natural time to come out of it.
2354 }
2355
Amith Yamasani396a10c2018-01-19 10:58:07 -08002356 void keyguardShowingLocked(boolean showing) {
2357 if (DEBUG) Slog.i(TAG, "keyguardShowing=" + showing);
2358 if (mScreenLocked != showing) {
2359 mScreenLocked = showing;
2360 if (mScreenOn && !mForceIdle && !mScreenLocked) {
2361 becomeActiveLocked("unlocked", Process.myUid());
2362 }
2363 }
2364 }
2365
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002366 void scheduleReportActiveLocked(String activeReason, int activeUid) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002367 Message msg = mHandler.obtainMessage(MSG_REPORT_ACTIVE, activeUid, 0, activeReason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002368 mHandler.sendMessage(msg);
2369 }
2370
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002371 void becomeActiveLocked(String activeReason, int activeUid) {
2372 if (DEBUG) Slog.i(TAG, "becomeActiveLocked, reason = " + activeReason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002373 if (mState != STATE_ACTIVE || mLightState != STATE_ACTIVE) {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002374 EventLogTags.writeDeviceIdle(STATE_ACTIVE, activeReason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002375 EventLogTags.writeDeviceIdleLight(LIGHT_STATE_ACTIVE, activeReason);
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002376 scheduleReportActiveLocked(activeReason, activeUid);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002377 mState = STATE_ACTIVE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002378 mLightState = LIGHT_STATE_ACTIVE;
Adam Lesinski31c05d12015-06-09 17:34:04 -07002379 mInactiveTimeout = mConstants.INACTIVE_TIMEOUT;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002380 mCurIdleBudget = 0;
2381 mMaintenanceStartTime = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002382 resetIdleManagementLocked();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002383 resetLightIdleManagementLocked();
Amith Yamasaniac6517a2018-04-23 12:19:34 -07002384 addEvent(EVENT_NORMAL, activeReason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002385 }
2386 }
2387
Kweku Adams00e3a372018-09-28 16:57:09 -07002388 /** Must only be used in tests. */
2389 @VisibleForTesting
2390 void setDeepEnabledForTest(boolean enabled) {
Kweku Adams799858b2018-10-08 17:19:08 -07002391 synchronized (this) {
2392 mDeepEnabled = enabled;
2393 }
Kweku Adams00e3a372018-09-28 16:57:09 -07002394 }
2395
2396 /** Must only be used in tests. */
2397 @VisibleForTesting
2398 void setLightEnabledForTest(boolean enabled) {
Kweku Adams799858b2018-10-08 17:19:08 -07002399 synchronized (this) {
2400 mLightEnabled = enabled;
2401 }
Kweku Adams00e3a372018-09-28 16:57:09 -07002402 }
2403
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002404 void becomeInactiveIfAppropriateLocked() {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002405 if (DEBUG) Slog.d(TAG, "becomeInactiveIfAppropriateLocked()");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002406 if ((!mScreenOn && !mCharging) || mForceIdle) {
Kweku Adamsb396ccf2018-09-17 16:37:15 -07002407 // Become inactive and determine if we will ultimately go idle.
2408 if (mDeepEnabled) {
2409 if (mQuickDozeActivated) {
2410 if (mState == STATE_QUICK_DOZE_DELAY || mState == STATE_IDLE
2411 || mState == STATE_IDLE_MAINTENANCE) {
2412 // Already "idling". Don't want to restart the process.
2413 // mLightState can't be LIGHT_STATE_ACTIVE if mState is any of these 3
2414 // values, so returning here is safe.
2415 return;
2416 }
2417 if (DEBUG) {
2418 Slog.d(TAG, "Moved from "
2419 + stateToString(mState) + " to STATE_QUICK_DOZE_DELAY");
2420 }
2421 mState = STATE_QUICK_DOZE_DELAY;
2422 // Make sure any motion sensing or locating is stopped.
2423 resetIdleManagementLocked();
2424 // Wait a small amount of time in case something (eg: background service from
2425 // recently closed app) needs to finish running.
2426 scheduleAlarmLocked(mConstants.QUICK_DOZE_DELAY_TIMEOUT, false);
2427 EventLogTags.writeDeviceIdle(mState, "no activity");
2428 } else if (mState == STATE_ACTIVE) {
2429 mState = STATE_INACTIVE;
2430 if (DEBUG) Slog.d(TAG, "Moved from STATE_ACTIVE to STATE_INACTIVE");
2431 resetIdleManagementLocked();
2432 scheduleAlarmLocked(mInactiveTimeout, false);
2433 EventLogTags.writeDeviceIdle(mState, "no activity");
2434 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002435 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08002436 if (mLightState == LIGHT_STATE_ACTIVE && mLightEnabled) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002437 mLightState = LIGHT_STATE_INACTIVE;
2438 if (DEBUG) Slog.d(TAG, "Moved from LIGHT_STATE_ACTIVE to LIGHT_STATE_INACTIVE");
2439 resetLightIdleManagementLocked();
Dianne Hackborn953fc942016-03-29 15:36:24 -07002440 scheduleLightAlarmLocked(mConstants.LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002441 EventLogTags.writeDeviceIdleLight(mLightState, "no activity");
2442 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002443 }
2444 }
2445
Kweku Adams00e3a372018-09-28 16:57:09 -07002446 private void resetIdleManagementLocked() {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002447 mNextIdlePendingDelay = 0;
2448 mNextIdleDelay = 0;
Dianne Hackborn953fc942016-03-29 15:36:24 -07002449 mNextLightIdleDelay = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002450 cancelAlarmLocked();
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002451 cancelSensingTimeoutAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002452 cancelLocatingLocked();
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002453 stopMonitoringMotionLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002454 mAnyMotionDetector.stop();
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002455 }
2456
Kweku Adams00e3a372018-09-28 16:57:09 -07002457 private void resetLightIdleManagementLocked() {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002458 cancelLightAlarmLocked();
2459 }
2460
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002461 void exitForceIdleLocked() {
2462 if (mForceIdle) {
2463 mForceIdle = false;
2464 if (mScreenOn || mCharging) {
Dianne Hackborn88c41352016-04-07 15:18:58 -07002465 becomeActiveLocked("exit-force", Process.myUid());
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002466 }
2467 }
2468 }
2469
Kweku Adamsa457f4e2018-10-03 15:56:06 -07002470 /**
2471 * Must only be used in tests.
2472 *
2473 * This sets the state value directly and thus doesn't trigger any behavioral changes.
2474 */
2475 @VisibleForTesting
2476 void setLightStateForTest(int lightState) {
Kweku Adams799858b2018-10-08 17:19:08 -07002477 synchronized (this) {
2478 mLightState = lightState;
2479 }
Kweku Adamsa457f4e2018-10-03 15:56:06 -07002480 }
2481
Kweku Adams00e3a372018-09-28 16:57:09 -07002482 @VisibleForTesting
2483 int getLightState() {
2484 return mLightState;
2485 }
2486
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002487 void stepLightIdleStateLocked(String reason) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002488 if (mLightState == LIGHT_STATE_OVERRIDE) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002489 // If we are already in deep device idle mode, then
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002490 // there is nothing left to do for light mode.
2491 return;
2492 }
2493
2494 if (DEBUG) Slog.d(TAG, "stepLightIdleStateLocked: mLightState=" + mLightState);
2495 EventLogTags.writeDeviceIdleLightStep();
2496
2497 switch (mLightState) {
2498 case LIGHT_STATE_INACTIVE:
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002499 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
Dianne Hackborn953fc942016-03-29 15:36:24 -07002500 // Reset the upcoming idle delays.
2501 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002502 mMaintenanceStartTime = 0;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002503 if (!isOpsInactiveLocked()) {
2504 // We have some active ops going on... give them a chance to finish
2505 // before going in to our first idle.
2506 mLightState = LIGHT_STATE_PRE_IDLE;
2507 EventLogTags.writeDeviceIdleLight(mLightState, reason);
2508 scheduleLightAlarmLocked(mConstants.LIGHT_PRE_IDLE_TIMEOUT);
2509 break;
2510 }
2511 // Nothing active, fall through to immediately idle.
2512 case LIGHT_STATE_PRE_IDLE:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002513 case LIGHT_STATE_IDLE_MAINTENANCE:
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002514 if (mMaintenanceStartTime != 0) {
2515 long duration = SystemClock.elapsedRealtime() - mMaintenanceStartTime;
2516 if (duration < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
2517 // We didn't use up all of our minimum budget; add this to the reserve.
2518 mCurIdleBudget += (mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET-duration);
2519 } else {
2520 // We used more than our minimum budget; this comes out of the reserve.
2521 mCurIdleBudget -= (duration-mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET);
2522 }
2523 }
2524 mMaintenanceStartTime = 0;
Dianne Hackborn953fc942016-03-29 15:36:24 -07002525 scheduleLightAlarmLocked(mNextLightIdleDelay);
2526 mNextLightIdleDelay = Math.min(mConstants.LIGHT_MAX_IDLE_TIMEOUT,
2527 (long)(mNextLightIdleDelay * mConstants.LIGHT_IDLE_FACTOR));
2528 if (mNextLightIdleDelay < mConstants.LIGHT_IDLE_TIMEOUT) {
2529 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
2530 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002531 if (DEBUG) Slog.d(TAG, "Moved to LIGHT_STATE_IDLE.");
2532 mLightState = LIGHT_STATE_IDLE;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002533 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Amith Yamasaniac6517a2018-04-23 12:19:34 -07002534 addEvent(EVENT_LIGHT_IDLE, null);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08002535 mGoingIdleWakeLock.acquire();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002536 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON_LIGHT);
2537 break;
2538 case LIGHT_STATE_IDLE:
Dianne Hackborn88c41352016-04-07 15:18:58 -07002539 case LIGHT_STATE_WAITING_FOR_NETWORK:
2540 if (mNetworkConnected || mLightState == LIGHT_STATE_WAITING_FOR_NETWORK) {
2541 // We have been idling long enough, now it is time to do some work.
2542 mActiveIdleOpCount = 1;
2543 mActiveIdleWakeLock.acquire();
2544 mMaintenanceStartTime = SystemClock.elapsedRealtime();
2545 if (mCurIdleBudget < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
2546 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
2547 } else if (mCurIdleBudget > mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET) {
2548 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET;
2549 }
2550 scheduleLightAlarmLocked(mCurIdleBudget);
2551 if (DEBUG) Slog.d(TAG,
2552 "Moved from LIGHT_STATE_IDLE to LIGHT_STATE_IDLE_MAINTENANCE.");
2553 mLightState = LIGHT_STATE_IDLE_MAINTENANCE;
2554 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Amith Yamasaniac6517a2018-04-23 12:19:34 -07002555 addEvent(EVENT_LIGHT_MAINTENANCE, null);
Dianne Hackborn88c41352016-04-07 15:18:58 -07002556 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
2557 } else {
2558 // We'd like to do maintenance, but currently don't have network
2559 // connectivity... let's try to wait until the network comes back.
2560 // We'll only wait for another full idle period, however, and then give up.
2561 scheduleLightAlarmLocked(mNextLightIdleDelay);
2562 if (DEBUG) Slog.d(TAG, "Moved to LIGHT_WAITING_FOR_NETWORK.");
2563 mLightState = LIGHT_STATE_WAITING_FOR_NETWORK;
2564 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002565 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002566 break;
2567 }
2568 }
2569
Kweku Adams00e3a372018-09-28 16:57:09 -07002570 @VisibleForTesting
2571 int getState() {
2572 return mState;
2573 }
2574
2575 @VisibleForTesting
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002576 void stepIdleStateLocked(String reason) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002577 if (DEBUG) Slog.d(TAG, "stepIdleStateLocked: mState=" + mState);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002578 EventLogTags.writeDeviceIdleStep();
2579
2580 final long now = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07002581 if ((now+mConstants.MIN_TIME_TO_ALARM) > mAlarmManager.getNextWakeFromIdleTime()) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002582 // Whoops, there is an upcoming alarm. We don't actually want to go idle.
2583 if (mState != STATE_ACTIVE) {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002584 becomeActiveLocked("alarm", Process.myUid());
Koji Fukui27b33302015-12-16 19:43:01 +09002585 becomeInactiveIfAppropriateLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002586 }
2587 return;
2588 }
2589
2590 switch (mState) {
2591 case STATE_INACTIVE:
2592 // We have now been inactive long enough, it is time to start looking
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002593 // for motion and sleep some more while doing so.
2594 startMonitoringMotionLocked();
Adam Lesinski31c05d12015-06-09 17:34:04 -07002595 scheduleAlarmLocked(mConstants.IDLE_AFTER_INACTIVE_TIMEOUT, false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002596 mState = STATE_IDLE_PENDING;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002597 if (DEBUG) Slog.d(TAG, "Moved from STATE_INACTIVE to STATE_IDLE_PENDING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002598 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002599 break;
2600 case STATE_IDLE_PENDING:
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002601 mState = STATE_SENSING;
2602 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE_PENDING to STATE_SENSING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002603 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002604 cancelLocatingLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002605 mLocated = false;
2606 mLastGenericLocation = null;
2607 mLastGpsLocation = null;
Robin Leec4d424c2018-12-07 15:09:13 +01002608
2609 // If we have an accelerometer, wait to find out whether we are moving.
2610 if (mUseMotionSensor && mAnyMotionDetector.hasSensor()) {
2611 scheduleSensingTimeoutAlarmLocked(mConstants.SENSING_TIMEOUT);
2612 mNotMoving = false;
2613 mAnyMotionDetector.checkForAnyMotion();
2614 break;
2615 }
2616
2617 mNotMoving = true;
2618 // Otherwise, fall through and check this off the list of requirements.
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002619 case STATE_SENSING:
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002620 cancelSensingTimeoutAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002621 mState = STATE_LOCATING;
2622 if (DEBUG) Slog.d(TAG, "Moved from STATE_SENSING to STATE_LOCATING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002623 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002624 scheduleAlarmLocked(mConstants.LOCATING_TIMEOUT, false);
Kweku Adams799858b2018-10-08 17:19:08 -07002625 LocationManager locationManager = mInjector.getLocationManager();
2626 if (locationManager != null
2627 && locationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
2628 locationManager.requestLocationUpdates(mLocationRequest,
Joe LaPenna23d681b2015-08-27 15:12:11 -07002629 mGenericLocationListener, mHandler.getLooper());
2630 mLocating = true;
2631 } else {
2632 mHasNetworkLocation = false;
2633 }
Kweku Adams799858b2018-10-08 17:19:08 -07002634 if (locationManager != null
2635 && locationManager.getProvider(LocationManager.GPS_PROVIDER) != null) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07002636 mHasGps = true;
Kweku Adams799858b2018-10-08 17:19:08 -07002637 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 5,
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002638 mGpsLocationListener, mHandler.getLooper());
Joe LaPenna23d681b2015-08-27 15:12:11 -07002639 mLocating = true;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002640 } else {
Joe LaPenna23d681b2015-08-27 15:12:11 -07002641 mHasGps = false;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002642 }
Joe LaPenna23d681b2015-08-27 15:12:11 -07002643 // If we have a location provider, we're all set, the listeners will move state
2644 // forward.
2645 if (mLocating) {
2646 break;
2647 }
2648
2649 // Otherwise, we have to move from locating into idle maintenance.
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002650 case STATE_LOCATING:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002651 cancelAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002652 cancelLocatingLocked();
2653 mAnyMotionDetector.stop();
Dianne Hackborn953fc942016-03-29 15:36:24 -07002654
Kweku Adamsb396ccf2018-09-17 16:37:15 -07002655 // Intentional fallthrough -- time to go into IDLE state.
2656 case STATE_QUICK_DOZE_DELAY:
2657 // Reset the upcoming idle delays.
2658 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
2659 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
2660
2661 // Everything is in place to go into IDLE state.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002662 case STATE_IDLE_MAINTENANCE:
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002663 scheduleAlarmLocked(mNextIdleDelay, true);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002664 if (DEBUG) Slog.d(TAG, "Moved to STATE_IDLE. Next alarm in " + mNextIdleDelay +
2665 " ms.");
Adam Lesinski31c05d12015-06-09 17:34:04 -07002666 mNextIdleDelay = (long)(mNextIdleDelay * mConstants.IDLE_FACTOR);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002667 if (DEBUG) Slog.d(TAG, "Setting mNextIdleDelay = " + mNextIdleDelay);
Adam Lesinski31c05d12015-06-09 17:34:04 -07002668 mNextIdleDelay = Math.min(mNextIdleDelay, mConstants.MAX_IDLE_TIMEOUT);
Dianne Hackborn953fc942016-03-29 15:36:24 -07002669 if (mNextIdleDelay < mConstants.IDLE_TIMEOUT) {
2670 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
2671 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002672 mState = STATE_IDLE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002673 if (mLightState != LIGHT_STATE_OVERRIDE) {
2674 mLightState = LIGHT_STATE_OVERRIDE;
2675 cancelLightAlarmLocked();
2676 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002677 EventLogTags.writeDeviceIdle(mState, reason);
Amith Yamasaniac6517a2018-04-23 12:19:34 -07002678 addEvent(EVENT_DEEP_IDLE, null);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08002679 mGoingIdleWakeLock.acquire();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002680 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON);
2681 break;
2682 case STATE_IDLE:
2683 // We have been idling long enough, now it is time to do some work.
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002684 mActiveIdleOpCount = 1;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002685 mActiveIdleWakeLock.acquire();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002686 scheduleAlarmLocked(mNextIdlePendingDelay, false);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002687 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE to STATE_IDLE_MAINTENANCE. " +
2688 "Next alarm in " + mNextIdlePendingDelay + " ms.");
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002689 mMaintenanceStartTime = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07002690 mNextIdlePendingDelay = Math.min(mConstants.MAX_IDLE_PENDING_TIMEOUT,
2691 (long)(mNextIdlePendingDelay * mConstants.IDLE_PENDING_FACTOR));
Dianne Hackborn953fc942016-03-29 15:36:24 -07002692 if (mNextIdlePendingDelay < mConstants.IDLE_PENDING_TIMEOUT) {
2693 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
2694 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002695 mState = STATE_IDLE_MAINTENANCE;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002696 EventLogTags.writeDeviceIdle(mState, reason);
Amith Yamasaniac6517a2018-04-23 12:19:34 -07002697 addEvent(EVENT_DEEP_MAINTENANCE, null);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002698 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
2699 break;
2700 }
2701 }
2702
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002703 void incActiveIdleOps() {
2704 synchronized (this) {
2705 mActiveIdleOpCount++;
2706 }
2707 }
2708
2709 void decActiveIdleOps() {
2710 synchronized (this) {
2711 mActiveIdleOpCount--;
2712 if (mActiveIdleOpCount <= 0) {
2713 exitMaintenanceEarlyIfNeededLocked();
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002714 mActiveIdleWakeLock.release();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002715 }
2716 }
2717 }
2718
Kweku Adamsa457f4e2018-10-03 15:56:06 -07002719 /** Must only be used in tests. */
2720 @VisibleForTesting
2721 void setActiveIdleOpsForTest(int count) {
Kweku Adams799858b2018-10-08 17:19:08 -07002722 synchronized (this) {
2723 mActiveIdleOpCount = count;
2724 }
Kweku Adamsa457f4e2018-10-03 15:56:06 -07002725 }
2726
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002727 void setJobsActive(boolean active) {
2728 synchronized (this) {
2729 mJobsActive = active;
Yao Chenca5edbb2016-01-13 14:44:36 -08002730 reportMaintenanceActivityIfNeededLocked();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002731 if (!active) {
2732 exitMaintenanceEarlyIfNeededLocked();
2733 }
2734 }
2735 }
2736
2737 void setAlarmsActive(boolean active) {
2738 synchronized (this) {
2739 mAlarmsActive = active;
2740 if (!active) {
2741 exitMaintenanceEarlyIfNeededLocked();
2742 }
2743 }
2744 }
2745
Yao Chenca5edbb2016-01-13 14:44:36 -08002746 boolean registerMaintenanceActivityListener(IMaintenanceActivityListener listener) {
2747 synchronized (this) {
2748 mMaintenanceActivityListeners.register(listener);
2749 return mReportedMaintenanceActivity;
2750 }
2751 }
2752
2753 void unregisterMaintenanceActivityListener(IMaintenanceActivityListener listener) {
2754 synchronized (this) {
2755 mMaintenanceActivityListeners.unregister(listener);
2756 }
2757 }
2758
2759 void reportMaintenanceActivityIfNeededLocked() {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07002760 boolean active = mJobsActive;
Yao Chenca5edbb2016-01-13 14:44:36 -08002761 if (active == mReportedMaintenanceActivity) {
2762 return;
2763 }
2764 mReportedMaintenanceActivity = active;
2765 Message msg = mHandler.obtainMessage(MSG_REPORT_MAINTENANCE_ACTIVITY,
2766 mReportedMaintenanceActivity ? 1 : 0, 0);
2767 mHandler.sendMessage(msg);
2768 }
2769
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002770 boolean isOpsInactiveLocked() {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07002771 return mActiveIdleOpCount <= 0 && !mJobsActive && !mAlarmsActive;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002772 }
2773
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002774 void exitMaintenanceEarlyIfNeededLocked() {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002775 if (mState == STATE_IDLE_MAINTENANCE || mLightState == LIGHT_STATE_IDLE_MAINTENANCE
2776 || mLightState == LIGHT_STATE_PRE_IDLE) {
2777 if (isOpsInactiveLocked()) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002778 final long now = SystemClock.elapsedRealtime();
2779 if (DEBUG) {
2780 StringBuilder sb = new StringBuilder();
2781 sb.append("Exit: start=");
2782 TimeUtils.formatDuration(mMaintenanceStartTime, sb);
2783 sb.append(" now=");
2784 TimeUtils.formatDuration(now, sb);
2785 Slog.d(TAG, sb.toString());
2786 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002787 if (mState == STATE_IDLE_MAINTENANCE) {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002788 stepIdleStateLocked("s:early");
2789 } else if (mLightState == LIGHT_STATE_PRE_IDLE) {
2790 stepLightIdleStateLocked("s:predone");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002791 } else {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002792 stepLightIdleStateLocked("s:early");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002793 }
2794 }
2795 }
2796 }
2797
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002798 void motionLocked() {
2799 if (DEBUG) Slog.d(TAG, "motionLocked()");
2800 // The motion sensor will have been disabled at this point
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002801 handleMotionDetectedLocked(mConstants.MOTION_INACTIVE_TIMEOUT, "motion");
2802 }
2803
2804 void handleMotionDetectedLocked(long timeout, String type) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002805 // The device is not yet active, so we want to go back to the pending idle
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002806 // state to wait again for no motion. Note that we only monitor for motion
2807 // after moving out of the inactive state, so no need to worry about that.
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002808 boolean becomeInactive = false;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002809 if (mState != STATE_ACTIVE) {
Amith Yamasani4cb42572018-04-27 10:02:57 -07002810 // Motion shouldn't affect light state, if it's already in doze-light or maintenance
2811 boolean lightIdle = mLightState == LIGHT_STATE_IDLE
2812 || mLightState == LIGHT_STATE_WAITING_FOR_NETWORK
2813 || mLightState == LIGHT_STATE_IDLE_MAINTENANCE;
2814 if (!lightIdle) {
2815 // Only switch to active state if we're not in either idle state
2816 scheduleReportActiveLocked(type, Process.myUid());
2817 addEvent(EVENT_NORMAL, type);
2818 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002819 mState = STATE_ACTIVE;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002820 mInactiveTimeout = timeout;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002821 mCurIdleBudget = 0;
2822 mMaintenanceStartTime = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002823 EventLogTags.writeDeviceIdle(mState, type);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002824 becomeInactive = true;
2825 }
2826 if (mLightState == LIGHT_STATE_OVERRIDE) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002827 // We went out of light idle mode because we had started deep idle mode... let's
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002828 // now go back and reset things so we resume light idling if appropriate.
Amith Yamasani4cb42572018-04-27 10:02:57 -07002829 mLightState = LIGHT_STATE_ACTIVE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002830 EventLogTags.writeDeviceIdleLight(mLightState, type);
2831 becomeInactive = true;
2832 }
2833 if (becomeInactive) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002834 becomeInactiveIfAppropriateLocked();
2835 }
2836 }
2837
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002838 void receivedGenericLocationLocked(Location location) {
2839 if (mState != STATE_LOCATING) {
2840 cancelLocatingLocked();
2841 return;
2842 }
2843 if (DEBUG) Slog.d(TAG, "Generic location: " + location);
2844 mLastGenericLocation = new Location(location);
Joe LaPenna23d681b2015-08-27 15:12:11 -07002845 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY && mHasGps) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002846 return;
2847 }
2848 mLocated = true;
2849 if (mNotMoving) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002850 stepIdleStateLocked("s:location");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002851 }
2852 }
2853
2854 void receivedGpsLocationLocked(Location location) {
2855 if (mState != STATE_LOCATING) {
2856 cancelLocatingLocked();
2857 return;
2858 }
2859 if (DEBUG) Slog.d(TAG, "GPS location: " + location);
2860 mLastGpsLocation = new Location(location);
2861 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY) {
2862 return;
2863 }
2864 mLocated = true;
2865 if (mNotMoving) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002866 stepIdleStateLocked("s:gps");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002867 }
2868 }
2869
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002870 void startMonitoringMotionLocked() {
2871 if (DEBUG) Slog.d(TAG, "startMonitoringMotionLocked()");
2872 if (mMotionSensor != null && !mMotionListener.active) {
2873 mMotionListener.registerLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002874 }
2875 }
2876
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002877 void stopMonitoringMotionLocked() {
2878 if (DEBUG) Slog.d(TAG, "stopMonitoringMotionLocked()");
2879 if (mMotionSensor != null && mMotionListener.active) {
2880 mMotionListener.unregisterLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002881 }
2882 }
2883
2884 void cancelAlarmLocked() {
2885 if (mNextAlarmTime != 0) {
2886 mNextAlarmTime = 0;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002887 mAlarmManager.cancel(mDeepAlarmListener);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002888 }
2889 }
2890
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002891 void cancelLightAlarmLocked() {
2892 if (mNextLightAlarmTime != 0) {
2893 mNextLightAlarmTime = 0;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002894 mAlarmManager.cancel(mLightAlarmListener);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002895 }
2896 }
2897
2898 void cancelLocatingLocked() {
2899 if (mLocating) {
Kweku Adams799858b2018-10-08 17:19:08 -07002900 LocationManager locationManager = mInjector.getLocationManager();
2901 locationManager.removeUpdates(mGenericLocationListener);
2902 locationManager.removeUpdates(mGpsLocationListener);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002903 mLocating = false;
2904 }
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002905 }
2906
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002907 void cancelSensingTimeoutAlarmLocked() {
2908 if (mNextSensingTimeoutAlarmTime != 0) {
2909 mNextSensingTimeoutAlarmTime = 0;
2910 mAlarmManager.cancel(mSensingTimeoutAlarmListener);
2911 }
2912 }
2913
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002914 void scheduleAlarmLocked(long delay, boolean idleUntil) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002915 if (DEBUG) Slog.d(TAG, "scheduleAlarmLocked(" + delay + ", " + idleUntil + ")");
Robin Leec4d424c2018-12-07 15:09:13 +01002916
2917 if (mUseMotionSensor && mMotionSensor == null
2918 && mState != STATE_QUICK_DOZE_DELAY
2919 && mState != STATE_IDLE
2920 && mState != STATE_IDLE_MAINTENANCE) {
2921 // 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 -07002922 // alarms, because we can't determine if the device is not moving. This effectively
Joe LaPenna23d681b2015-08-27 15:12:11 -07002923 // turns off normal execution of device idling, although it is still possible to
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002924 // manually poke it by pretending like the alarm is going off.
Kweku Adamsb396ccf2018-09-17 16:37:15 -07002925 // STATE_QUICK_DOZE_DELAY skips the motion sensing so if the state is past the motion
2926 // sensing stage (ie, is QUICK_DOZE_DELAY, IDLE, or IDLE_MAINTENANCE), then idling
2927 // can continue until the user interacts with the device.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002928 return;
2929 }
2930 mNextAlarmTime = SystemClock.elapsedRealtime() + delay;
2931 if (idleUntil) {
2932 mAlarmManager.setIdleUntil(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002933 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002934 } else {
2935 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002936 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002937 }
2938 }
2939
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002940 void scheduleLightAlarmLocked(long delay) {
2941 if (DEBUG) Slog.d(TAG, "scheduleLightAlarmLocked(" + delay + ")");
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002942 mNextLightAlarmTime = SystemClock.elapsedRealtime() + delay;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002943 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002944 mNextLightAlarmTime, "DeviceIdleController.light", mLightAlarmListener, mHandler);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002945 }
2946
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002947 void scheduleSensingTimeoutAlarmLocked(long delay) {
2948 if (DEBUG) Slog.d(TAG, "scheduleSensingAlarmLocked(" + delay + ")");
2949 mNextSensingTimeoutAlarmTime = SystemClock.elapsedRealtime() + delay;
2950 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, mNextSensingTimeoutAlarmTime,
2951 "DeviceIdleController.sensing", mSensingTimeoutAlarmListener, mHandler);
2952 }
2953
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002954 private static int[] buildAppIdArray(ArrayMap<String, Integer> systemApps,
2955 ArrayMap<String, Integer> userApps, SparseBooleanArray outAppIds) {
2956 outAppIds.clear();
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002957 if (systemApps != null) {
2958 for (int i = 0; i < systemApps.size(); i++) {
2959 outAppIds.put(systemApps.valueAt(i), true);
2960 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002961 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002962 if (userApps != null) {
2963 for (int i = 0; i < userApps.size(); i++) {
2964 outAppIds.put(userApps.valueAt(i), true);
2965 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002966 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002967 int size = outAppIds.size();
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002968 int[] appids = new int[size];
2969 for (int i = 0; i < size; i++) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002970 appids[i] = outAppIds.keyAt(i);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002971 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002972 return appids;
2973 }
2974
2975 private void updateWhitelistAppIdsLocked() {
2976 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(mPowerSaveWhitelistAppsExceptIdle,
2977 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistExceptIdleAppIds);
2978 mPowerSaveWhitelistAllAppIdArray = buildAppIdArray(mPowerSaveWhitelistApps,
2979 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistAllAppIds);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002980 mPowerSaveWhitelistUserAppIdArray = buildAppIdArray(null,
2981 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistUserAppIds);
Dianne Hackborn85e35642017-01-12 15:10:57 -08002982 if (mLocalActivityManager != null) {
Makoto Onukiaf8ff4f2018-06-04 14:44:19 -07002983 mLocalActivityManager.setDeviceIdleWhitelist(
2984 mPowerSaveWhitelistAllAppIdArray, mPowerSaveWhitelistExceptIdleAppIdArray);
Dianne Hackborn85e35642017-01-12 15:10:57 -08002985 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002986 if (mLocalPowerManager != null) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002987 if (DEBUG) {
2988 Slog.d(TAG, "Setting wakelock whitelist to "
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002989 + Arrays.toString(mPowerSaveWhitelistAllAppIdArray));
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002990 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002991 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002992 }
Suprabh Shukla5bf49812018-05-24 18:38:50 -07002993 passWhiteListsToForceAppStandbyTrackerLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002994 }
2995
Dianne Hackborn85e35642017-01-12 15:10:57 -08002996 private void updateTempWhitelistAppIdsLocked(int appId, boolean adding) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002997 final int size = mTempWhitelistAppIdEndTimes.size();
2998 if (mTempWhitelistAppIdArray.length != size) {
2999 mTempWhitelistAppIdArray = new int[size];
3000 }
3001 for (int i = 0; i < size; i++) {
3002 mTempWhitelistAppIdArray[i] = mTempWhitelistAppIdEndTimes.keyAt(i);
3003 }
Dianne Hackborn85e35642017-01-12 15:10:57 -08003004 if (mLocalActivityManager != null) {
3005 if (DEBUG) {
3006 Slog.d(TAG, "Setting activity manager temp whitelist to "
3007 + Arrays.toString(mTempWhitelistAppIdArray));
3008 }
3009 mLocalActivityManager.updateDeviceIdleTempWhitelist(mTempWhitelistAppIdArray, appId,
3010 adding);
3011 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003012 if (mLocalPowerManager != null) {
3013 if (DEBUG) {
3014 Slog.d(TAG, "Setting wakelock temp whitelist to "
3015 + Arrays.toString(mTempWhitelistAppIdArray));
3016 }
3017 mLocalPowerManager.setDeviceIdleTempWhitelist(mTempWhitelistAppIdArray);
3018 }
Suprabh Shukla5bf49812018-05-24 18:38:50 -07003019 passWhiteListsToForceAppStandbyTrackerLocked();
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003020 }
3021
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003022 private void reportPowerSaveWhitelistChangedLocked() {
3023 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
3024 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Xiaohui Chene4de5a02015-09-22 15:33:31 -07003025 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003026 }
3027
3028 private void reportTempWhitelistChangedLocked() {
3029 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_TEMP_WHITELIST_CHANGED);
3030 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Xiaohui Chene4de5a02015-09-22 15:33:31 -07003031 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003032 }
3033
Suprabh Shukla5bf49812018-05-24 18:38:50 -07003034 private void passWhiteListsToForceAppStandbyTrackerLocked() {
Makoto Onukie4918212018-02-06 11:30:15 -08003035 mAppStateTracker.setPowerSaveWhitelistAppIds(
Makoto Onuki71755c92018-01-16 14:15:44 -08003036 mPowerSaveWhitelistExceptIdleAppIdArray,
Suprabh Shukla5bf49812018-05-24 18:38:50 -07003037 mPowerSaveWhitelistUserAppIdArray,
Makoto Onuki2206af32017-11-21 16:25:35 -08003038 mTempWhitelistAppIdArray);
3039 }
3040
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003041 void readConfigFileLocked() {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003042 if (DEBUG) Slog.d(TAG, "Reading config from " + mConfigFile.getBaseFile());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003043 mPowerSaveWhitelistUserApps.clear();
3044 FileInputStream stream;
3045 try {
3046 stream = mConfigFile.openRead();
3047 } catch (FileNotFoundException e) {
3048 return;
3049 }
3050 try {
3051 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003052 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003053 readConfigFileLocked(parser);
3054 } catch (XmlPullParserException e) {
3055 } finally {
3056 try {
3057 stream.close();
3058 } catch (IOException e) {
3059 }
3060 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003061 }
3062
3063 private void readConfigFileLocked(XmlPullParser parser) {
3064 final PackageManager pm = getContext().getPackageManager();
3065
3066 try {
3067 int type;
3068 while ((type = parser.next()) != XmlPullParser.START_TAG
3069 && type != XmlPullParser.END_DOCUMENT) {
3070 ;
3071 }
3072
3073 if (type != XmlPullParser.START_TAG) {
3074 throw new IllegalStateException("no start tag found");
3075 }
3076
3077 int outerDepth = parser.getDepth();
3078 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
3079 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3080 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3081 continue;
3082 }
3083
3084 String tagName = parser.getName();
Suprabh Shukla08105642017-09-26 14:45:30 -07003085 switch (tagName) {
3086 case "wl":
3087 String name = parser.getAttributeValue(null, "n");
3088 if (name != null) {
3089 try {
3090 ApplicationInfo ai = pm.getApplicationInfo(name,
3091 PackageManager.MATCH_ANY_USER);
3092 mPowerSaveWhitelistUserApps.put(ai.packageName,
3093 UserHandle.getAppId(ai.uid));
3094 } catch (PackageManager.NameNotFoundException e) {
3095 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003096 }
Suprabh Shukla08105642017-09-26 14:45:30 -07003097 break;
3098 case "un-wl":
3099 final String packageName = parser.getAttributeValue(null, "n");
3100 if (mPowerSaveWhitelistApps.containsKey(packageName)) {
3101 mRemovedFromSystemWhitelistApps.put(packageName,
3102 mPowerSaveWhitelistApps.remove(packageName));
3103 }
3104 break;
3105 default:
3106 Slog.w(TAG, "Unknown element under <config>: "
3107 + parser.getName());
3108 XmlUtils.skipCurrentTag(parser);
3109 break;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003110 }
3111 }
3112
3113 } catch (IllegalStateException e) {
3114 Slog.w(TAG, "Failed parsing config " + e);
3115 } catch (NullPointerException e) {
3116 Slog.w(TAG, "Failed parsing config " + e);
3117 } catch (NumberFormatException e) {
3118 Slog.w(TAG, "Failed parsing config " + e);
3119 } catch (XmlPullParserException e) {
3120 Slog.w(TAG, "Failed parsing config " + e);
3121 } catch (IOException e) {
3122 Slog.w(TAG, "Failed parsing config " + e);
3123 } catch (IndexOutOfBoundsException e) {
3124 Slog.w(TAG, "Failed parsing config " + e);
3125 }
3126 }
3127
3128 void writeConfigFileLocked() {
3129 mHandler.removeMessages(MSG_WRITE_CONFIG);
3130 mHandler.sendEmptyMessageDelayed(MSG_WRITE_CONFIG, 5000);
3131 }
3132
3133 void handleWriteConfigFile() {
3134 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
3135
3136 try {
3137 synchronized (this) {
3138 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01003139 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003140 writeConfigFileLocked(out);
3141 }
3142 } catch (IOException e) {
3143 }
3144
3145 synchronized (mConfigFile) {
3146 FileOutputStream stream = null;
3147 try {
3148 stream = mConfigFile.startWrite();
3149 memStream.writeTo(stream);
3150 stream.flush();
3151 FileUtils.sync(stream);
3152 stream.close();
3153 mConfigFile.finishWrite(stream);
3154 } catch (IOException e) {
3155 Slog.w(TAG, "Error writing config file", e);
3156 mConfigFile.failWrite(stream);
3157 }
3158 }
3159 }
3160
3161 void writeConfigFileLocked(XmlSerializer out) throws IOException {
3162 out.startDocument(null, true);
3163 out.startTag(null, "config");
3164 for (int i=0; i<mPowerSaveWhitelistUserApps.size(); i++) {
3165 String name = mPowerSaveWhitelistUserApps.keyAt(i);
3166 out.startTag(null, "wl");
3167 out.attribute(null, "n", name);
3168 out.endTag(null, "wl");
3169 }
Suprabh Shukla08105642017-09-26 14:45:30 -07003170 for (int i = 0; i < mRemovedFromSystemWhitelistApps.size(); i++) {
3171 out.startTag(null, "un-wl");
3172 out.attribute(null, "n", mRemovedFromSystemWhitelistApps.keyAt(i));
3173 out.endTag(null, "un-wl");
3174 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003175 out.endTag(null, "config");
3176 out.endDocument();
3177 }
3178
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003179 static void dumpHelp(PrintWriter pw) {
3180 pw.println("Device idle controller (deviceidle) commands:");
3181 pw.println(" help");
3182 pw.println(" Print this help text.");
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003183 pw.println(" step [light|deep]");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003184 pw.println(" Immediately step to next state, without waiting for alarm.");
Dianne Hackborn88c41352016-04-07 15:18:58 -07003185 pw.println(" force-idle [light|deep]");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003186 pw.println(" Force directly into idle mode, regardless of other device state.");
Dianne Hackborn88c41352016-04-07 15:18:58 -07003187 pw.println(" force-inactive");
3188 pw.println(" Force to be inactive, ready to freely step idle states.");
3189 pw.println(" unforce");
3190 pw.println(" Resume normal functioning after force-idle or force-inactive.");
3191 pw.println(" get [light|deep|force|screen|charging|network]");
3192 pw.println(" Retrieve the current given state.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08003193 pw.println(" disable [light|deep|all]");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003194 pw.println(" Completely disable device idle mode.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08003195 pw.println(" enable [light|deep|all]");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003196 pw.println(" Re-enable device idle mode after it had previously been disabled.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08003197 pw.println(" enabled [light|deep|all]");
Dianne Hackborn92617032015-06-19 15:32:19 -07003198 pw.println(" Print 1 if device idle mode is currently enabled, else 0.");
Dianne Hackborn1b139682015-07-06 15:13:37 -07003199 pw.println(" whitelist");
3200 pw.println(" Print currently whitelisted apps.");
Dianne Hackborn92617032015-06-19 15:32:19 -07003201 pw.println(" whitelist [package ...]");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003202 pw.println(" Add (prefix with +) or remove (prefix with -) packages.");
Suprabh Shukla08105642017-09-26 14:45:30 -07003203 pw.println(" sys-whitelist [package ...|reset]");
3204 pw.println(" Prefix the package with '-' to remove it from the system whitelist or '+'"
3205 + " to put it back in the system whitelist.");
3206 pw.println(" Note that only packages that were"
3207 + " earlier removed from the system whitelist can be added back.");
3208 pw.println(" reset will reset the whitelist to the original state");
3209 pw.println(" Prints the system whitelist if no arguments are specified");
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07003210 pw.println(" except-idle-whitelist [package ...|reset]");
3211 pw.println(" Prefix the package with '+' to add it to whitelist or "
3212 + "'=' to check if it is already whitelisted");
3213 pw.println(" [reset] will reset the whitelist to it's original state");
3214 pw.println(" Note that unlike <whitelist> cmd, "
3215 + "changes made using this won't be persisted across boots");
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003216 pw.println(" tempwhitelist");
3217 pw.println(" Print packages that are temporarily whitelisted.");
Sudheer Shanka326b3112017-11-27 14:40:57 -08003218 pw.println(" tempwhitelist [-u USER] [-d DURATION] [-r] [package]");
3219 pw.println(" Temporarily place package in whitelist for DURATION milliseconds.");
Dianne Hackborn85e35642017-01-12 15:10:57 -08003220 pw.println(" If no DURATION is specified, 10 seconds is used");
Sudheer Shanka326b3112017-11-27 14:40:57 -08003221 pw.println(" If [-r] option is used, then the package is removed from temp whitelist "
3222 + "and any [-d] is ignored");
Amith Yamasani4cb42572018-04-27 10:02:57 -07003223 pw.println(" motion");
3224 pw.println(" Simulate a motion event to bring the device out of deep doze");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003225 }
3226
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003227 class Shell extends ShellCommand {
3228 int userId = UserHandle.USER_SYSTEM;
3229
3230 @Override
3231 public int onCommand(String cmd) {
3232 return onShellCommand(this, cmd);
3233 }
3234
3235 @Override
3236 public void onHelp() {
3237 PrintWriter pw = getOutPrintWriter();
3238 dumpHelp(pw);
3239 }
3240 }
3241
3242 int onShellCommand(Shell shell, String cmd) {
3243 PrintWriter pw = shell.getOutPrintWriter();
3244 if ("step".equals(cmd)) {
3245 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3246 null);
3247 synchronized (this) {
3248 long token = Binder.clearCallingIdentity();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003249 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003250 try {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003251 if (arg == null || "deep".equals(arg)) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003252 stepIdleStateLocked("s:shell");
3253 pw.print("Stepped to deep: ");
3254 pw.println(stateToString(mState));
3255 } else if ("light".equals(arg)) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003256 stepLightIdleStateLocked("s:shell");
3257 pw.print("Stepped to light: "); pw.println(lightStateToString(mLightState));
3258 } else {
3259 pw.println("Unknown idle mode: " + arg);
3260 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003261 } finally {
3262 Binder.restoreCallingIdentity(token);
3263 }
3264 }
3265 } else if ("force-idle".equals(cmd)) {
3266 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3267 null);
3268 synchronized (this) {
3269 long token = Binder.clearCallingIdentity();
Dianne Hackborn88c41352016-04-07 15:18:58 -07003270 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003271 try {
Dianne Hackborn88c41352016-04-07 15:18:58 -07003272 if (arg == null || "deep".equals(arg)) {
3273 if (!mDeepEnabled) {
3274 pw.println("Unable to go deep idle; not enabled");
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003275 return -1;
3276 }
Dianne Hackborn88c41352016-04-07 15:18:58 -07003277 mForceIdle = true;
3278 becomeInactiveIfAppropriateLocked();
3279 int curState = mState;
3280 while (curState != STATE_IDLE) {
3281 stepIdleStateLocked("s:shell");
3282 if (curState == mState) {
3283 pw.print("Unable to go deep idle; stopped at ");
3284 pw.println(stateToString(mState));
3285 exitForceIdleLocked();
3286 return -1;
3287 }
3288 curState = mState;
3289 }
3290 pw.println("Now forced in to deep idle mode");
3291 } else if ("light".equals(arg)) {
3292 mForceIdle = true;
3293 becomeInactiveIfAppropriateLocked();
3294 int curLightState = mLightState;
3295 while (curLightState != LIGHT_STATE_IDLE) {
Tej Singh93cf3e32017-12-07 13:05:38 -08003296 stepLightIdleStateLocked("s:shell");
Dianne Hackborn88c41352016-04-07 15:18:58 -07003297 if (curLightState == mLightState) {
3298 pw.print("Unable to go light idle; stopped at ");
3299 pw.println(lightStateToString(mLightState));
3300 exitForceIdleLocked();
3301 return -1;
3302 }
3303 curLightState = mLightState;
3304 }
3305 pw.println("Now forced in to light idle mode");
3306 } else {
3307 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003308 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003309 } finally {
3310 Binder.restoreCallingIdentity(token);
3311 }
3312 }
Dianne Hackborn88c41352016-04-07 15:18:58 -07003313 } else if ("force-inactive".equals(cmd)) {
3314 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3315 null);
3316 synchronized (this) {
3317 long token = Binder.clearCallingIdentity();
3318 try {
3319 mForceIdle = true;
3320 becomeInactiveIfAppropriateLocked();
3321 pw.print("Light state: ");
3322 pw.print(lightStateToString(mLightState));
3323 pw.print(", deep state: ");
3324 pw.println(stateToString(mState));
3325 } finally {
3326 Binder.restoreCallingIdentity(token);
3327 }
3328 }
3329 } else if ("unforce".equals(cmd)) {
3330 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3331 null);
3332 synchronized (this) {
3333 long token = Binder.clearCallingIdentity();
3334 try {
3335 exitForceIdleLocked();
3336 pw.print("Light state: ");
3337 pw.print(lightStateToString(mLightState));
3338 pw.print(", deep state: ");
3339 pw.println(stateToString(mState));
3340 } finally {
3341 Binder.restoreCallingIdentity(token);
3342 }
3343 }
3344 } else if ("get".equals(cmd)) {
3345 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3346 null);
3347 synchronized (this) {
3348 String arg = shell.getNextArg();
3349 if (arg != null) {
3350 long token = Binder.clearCallingIdentity();
3351 try {
3352 switch (arg) {
3353 case "light": pw.println(lightStateToString(mLightState)); break;
3354 case "deep": pw.println(stateToString(mState)); break;
3355 case "force": pw.println(mForceIdle); break;
Kweku Adamsb396ccf2018-09-17 16:37:15 -07003356 case "quick": pw.println(mQuickDozeActivated); break;
Dianne Hackborn88c41352016-04-07 15:18:58 -07003357 case "screen": pw.println(mScreenOn); break;
3358 case "charging": pw.println(mCharging); break;
3359 case "network": pw.println(mNetworkConnected); break;
3360 default: pw.println("Unknown get option: " + arg); break;
3361 }
3362 } finally {
3363 Binder.restoreCallingIdentity(token);
3364 }
3365 } else {
3366 pw.println("Argument required");
3367 }
3368 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003369 } else if ("disable".equals(cmd)) {
3370 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3371 null);
3372 synchronized (this) {
3373 long token = Binder.clearCallingIdentity();
Dianne Hackbornb6843652016-02-22 12:20:13 -08003374 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003375 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08003376 boolean becomeActive = false;
3377 boolean valid = false;
3378 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
3379 valid = true;
3380 if (mDeepEnabled) {
3381 mDeepEnabled = false;
3382 becomeActive = true;
3383 pw.println("Deep idle mode disabled");
3384 }
3385 }
3386 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
3387 valid = true;
3388 if (mLightEnabled) {
3389 mLightEnabled = false;
3390 becomeActive = true;
3391 pw.println("Light idle mode disabled");
3392 }
3393 }
3394 if (becomeActive) {
3395 becomeActiveLocked((arg == null ? "all" : arg) + "-disabled",
3396 Process.myUid());
3397 }
3398 if (!valid) {
3399 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003400 }
3401 } finally {
3402 Binder.restoreCallingIdentity(token);
3403 }
3404 }
3405 } else if ("enable".equals(cmd)) {
3406 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3407 null);
3408 synchronized (this) {
3409 long token = Binder.clearCallingIdentity();
Dianne Hackbornb6843652016-02-22 12:20:13 -08003410 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003411 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08003412 boolean becomeInactive = false;
3413 boolean valid = false;
3414 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
3415 valid = true;
3416 if (!mDeepEnabled) {
3417 mDeepEnabled = true;
3418 becomeInactive = true;
3419 pw.println("Deep idle mode enabled");
3420 }
3421 }
3422 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
3423 valid = true;
3424 if (!mLightEnabled) {
3425 mLightEnabled = true;
3426 becomeInactive = true;
3427 pw.println("Light idle mode enable");
3428 }
3429 }
3430 if (becomeInactive) {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003431 becomeInactiveIfAppropriateLocked();
Dianne Hackbornb6843652016-02-22 12:20:13 -08003432 }
3433 if (!valid) {
3434 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003435 }
3436 } finally {
3437 Binder.restoreCallingIdentity(token);
3438 }
3439 }
3440 } else if ("enabled".equals(cmd)) {
3441 synchronized (this) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08003442 String arg = shell.getNextArg();
3443 if (arg == null || "all".equals(arg)) {
3444 pw.println(mDeepEnabled && mLightEnabled ? "1" : 0);
3445 } else if ("deep".equals(arg)) {
3446 pw.println(mDeepEnabled ? "1" : 0);
3447 } else if ("light".equals(arg)) {
3448 pw.println(mLightEnabled ? "1" : 0);
3449 } else {
3450 pw.println("Unknown idle mode: " + arg);
3451 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003452 }
3453 } else if ("whitelist".equals(cmd)) {
Dianne Hackborneb909e32016-09-29 14:35:15 -07003454 String arg = shell.getNextArg();
3455 if (arg != null) {
3456 getContext().enforceCallingOrSelfPermission(
3457 android.Manifest.permission.DEVICE_POWER, null);
3458 long token = Binder.clearCallingIdentity();
3459 try {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003460 do {
3461 if (arg.length() < 1 || (arg.charAt(0) != '-'
Felipe Lemef8a46232016-02-10 13:51:54 -08003462 && arg.charAt(0) != '+' && arg.charAt(0) != '=')) {
3463 pw.println("Package must be prefixed with +, -, or =: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003464 return -1;
3465 }
3466 char op = arg.charAt(0);
3467 String pkg = arg.substring(1);
3468 if (op == '+') {
3469 if (addPowerSaveWhitelistAppInternal(pkg)) {
3470 pw.println("Added: " + pkg);
3471 } else {
3472 pw.println("Unknown package: " + pkg);
3473 }
Felipe Lemef8a46232016-02-10 13:51:54 -08003474 } else if (op == '-') {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003475 if (removePowerSaveWhitelistAppInternal(pkg)) {
3476 pw.println("Removed: " + pkg);
3477 }
Felipe Lemef8a46232016-02-10 13:51:54 -08003478 } else {
3479 pw.println(getPowerSaveWhitelistAppInternal(pkg));
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003480 }
3481 } while ((arg=shell.getNextArg()) != null);
Dianne Hackborneb909e32016-09-29 14:35:15 -07003482 } finally {
3483 Binder.restoreCallingIdentity(token);
3484 }
3485 } else {
3486 synchronized (this) {
3487 for (int j=0; j<mPowerSaveWhitelistAppsExceptIdle.size(); j++) {
3488 pw.print("system-excidle,");
3489 pw.print(mPowerSaveWhitelistAppsExceptIdle.keyAt(j));
3490 pw.print(",");
3491 pw.println(mPowerSaveWhitelistAppsExceptIdle.valueAt(j));
3492 }
3493 for (int j=0; j<mPowerSaveWhitelistApps.size(); j++) {
3494 pw.print("system,");
3495 pw.print(mPowerSaveWhitelistApps.keyAt(j));
3496 pw.print(",");
3497 pw.println(mPowerSaveWhitelistApps.valueAt(j));
3498 }
3499 for (int j=0; j<mPowerSaveWhitelistUserApps.size(); j++) {
3500 pw.print("user,");
3501 pw.print(mPowerSaveWhitelistUserApps.keyAt(j));
3502 pw.print(",");
3503 pw.println(mPowerSaveWhitelistUserApps.valueAt(j));
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003504 }
3505 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003506 }
3507 } else if ("tempwhitelist".equals(cmd)) {
Dianne Hackborn85e35642017-01-12 15:10:57 -08003508 long duration = 10000;
Sudheer Shanka326b3112017-11-27 14:40:57 -08003509 boolean removePkg = false;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003510 String opt;
3511 while ((opt=shell.getNextOption()) != null) {
3512 if ("-u".equals(opt)) {
3513 opt = shell.getNextArg();
3514 if (opt == null) {
3515 pw.println("-u requires a user number");
3516 return -1;
3517 }
3518 shell.userId = Integer.parseInt(opt);
Dianne Hackborn85e35642017-01-12 15:10:57 -08003519 } else if ("-d".equals(opt)) {
3520 opt = shell.getNextArg();
3521 if (opt == null) {
3522 pw.println("-d requires a duration");
3523 return -1;
3524 }
3525 duration = Long.parseLong(opt);
Sudheer Shanka326b3112017-11-27 14:40:57 -08003526 } else if ("-r".equals(opt)) {
3527 removePkg = true;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003528 }
3529 }
3530 String arg = shell.getNextArg();
3531 if (arg != null) {
3532 try {
Sudheer Shanka326b3112017-11-27 14:40:57 -08003533 if (removePkg) {
3534 removePowerSaveTempWhitelistAppChecked(arg, shell.userId);
3535 } else {
3536 addPowerSaveTempWhitelistAppChecked(arg, duration, shell.userId, "shell");
3537 }
Christopher Tateec3a9f32017-03-21 17:43:47 -07003538 } catch (Exception e) {
3539 pw.println("Failed: " + e);
3540 return -1;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003541 }
Sudheer Shanka326b3112017-11-27 14:40:57 -08003542 } else if (removePkg) {
3543 pw.println("[-r] requires a package name");
3544 return -1;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003545 } else {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003546 dumpTempWhitelistSchedule(pw, false);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003547 }
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07003548 } else if ("except-idle-whitelist".equals(cmd)) {
3549 getContext().enforceCallingOrSelfPermission(
3550 android.Manifest.permission.DEVICE_POWER, null);
3551 final long token = Binder.clearCallingIdentity();
3552 try {
3553 String arg = shell.getNextArg();
3554 if (arg == null) {
3555 pw.println("No arguments given");
3556 return -1;
3557 } else if ("reset".equals(arg)) {
3558 resetPowerSaveWhitelistExceptIdleInternal();
3559 } else {
3560 do {
3561 if (arg.length() < 1 || (arg.charAt(0) != '-'
3562 && arg.charAt(0) != '+' && arg.charAt(0) != '=')) {
3563 pw.println("Package must be prefixed with +, -, or =: " + arg);
3564 return -1;
3565 }
3566 char op = arg.charAt(0);
3567 String pkg = arg.substring(1);
3568 if (op == '+') {
3569 if (addPowerSaveWhitelistExceptIdleInternal(pkg)) {
3570 pw.println("Added: " + pkg);
3571 } else {
3572 pw.println("Unknown package: " + pkg);
3573 }
3574 } else if (op == '=') {
3575 pw.println(getPowerSaveWhitelistExceptIdleInternal(pkg));
3576 } else {
3577 pw.println("Unknown argument: " + arg);
3578 return -1;
3579 }
3580 } while ((arg = shell.getNextArg()) != null);
3581 }
3582 } finally {
3583 Binder.restoreCallingIdentity(token);
3584 }
Suprabh Shukla08105642017-09-26 14:45:30 -07003585 } else if ("sys-whitelist".equals(cmd)) {
3586 String arg = shell.getNextArg();
3587 if (arg != null) {
3588 getContext().enforceCallingOrSelfPermission(
3589 android.Manifest.permission.DEVICE_POWER, null);
3590 final long token = Binder.clearCallingIdentity();
3591 try {
3592 if ("reset".equals(arg)) {
3593 resetSystemPowerWhitelistInternal();
3594 } else {
3595 do {
3596 if (arg.length() < 1
3597 || (arg.charAt(0) != '-' && arg.charAt(0) != '+')) {
3598 pw.println("Package must be prefixed with + or - " + arg);
3599 return -1;
3600 }
3601 final char op = arg.charAt(0);
3602 final String pkg = arg.substring(1);
3603 switch (op) {
3604 case '+':
3605 if (restoreSystemPowerWhitelistAppInternal(pkg)) {
3606 pw.println("Restored " + pkg);
3607 }
3608 break;
3609 case '-':
3610 if (removeSystemPowerWhitelistAppInternal(pkg)) {
3611 pw.println("Removed " + pkg);
3612 }
3613 break;
3614 }
3615 } while ((arg = shell.getNextArg()) != null);
3616 }
3617 } finally {
3618 Binder.restoreCallingIdentity(token);
3619 }
3620 } else {
3621 synchronized (this) {
Amith Yamasani4cb42572018-04-27 10:02:57 -07003622 for (int j = 0; j < mPowerSaveWhitelistApps.size(); j++) {
Suprabh Shukla08105642017-09-26 14:45:30 -07003623 pw.print(mPowerSaveWhitelistApps.keyAt(j));
3624 pw.print(",");
3625 pw.println(mPowerSaveWhitelistApps.valueAt(j));
3626 }
3627 }
3628 }
Amith Yamasani4cb42572018-04-27 10:02:57 -07003629 } else if ("motion".equals(cmd)) {
3630 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
3631 null);
3632 synchronized (this) {
3633 long token = Binder.clearCallingIdentity();
3634 try {
3635 motionLocked();
3636 pw.print("Light state: ");
3637 pw.print(lightStateToString(mLightState));
3638 pw.print(", deep state: ");
3639 pw.println(stateToString(mState));
3640 } finally {
3641 Binder.restoreCallingIdentity(token);
3642 }
3643 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003644 } else {
3645 return shell.handleDefaultCommands(cmd);
3646 }
3647 return 0;
3648 }
3649
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003650 void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003651 if (!DumpUtils.checkDumpPermission(getContext(), TAG, pw)) return;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003652
3653 if (args != null) {
Xiaohui Chen7c696362015-09-16 09:56:14 -07003654 int userId = UserHandle.USER_SYSTEM;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003655 for (int i=0; i<args.length; i++) {
3656 String arg = args[i];
3657 if ("-h".equals(arg)) {
3658 dumpHelp(pw);
3659 return;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003660 } else if ("-u".equals(arg)) {
3661 i++;
3662 if (i < args.length) {
3663 arg = args[i];
3664 userId = Integer.parseInt(arg);
3665 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003666 } else if ("-a".equals(arg)) {
3667 // Ignore, we always dump all.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003668 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
3669 pw.println("Unknown option: " + arg);
3670 return;
3671 } else {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003672 Shell shell = new Shell();
3673 shell.userId = userId;
3674 String[] newArgs = new String[args.length-i];
3675 System.arraycopy(args, i, newArgs, 0, args.length-i);
Dianne Hackborn354736e2016-08-22 17:00:05 -07003676 shell.exec(mBinderService, null, fd, null, newArgs, null,
3677 new ResultReceiver(null));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003678 return;
3679 }
3680 }
3681 }
3682
3683 synchronized (this) {
Dianne Hackborna750a632015-06-16 17:18:23 -07003684 mConstants.dump(pw);
3685
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08003686 if (mEventCmds[0] != EVENT_NULL) {
3687 pw.println(" Idling history:");
3688 long now = SystemClock.elapsedRealtime();
3689 for (int i=EVENT_BUFFER_SIZE-1; i>=0; i--) {
3690 int cmd = mEventCmds[i];
3691 if (cmd == EVENT_NULL) {
3692 continue;
3693 }
3694 String label;
3695 switch (mEventCmds[i]) {
3696 case EVENT_NORMAL: label = " normal"; break;
3697 case EVENT_LIGHT_IDLE: label = " light-idle"; break;
3698 case EVENT_LIGHT_MAINTENANCE: label = "light-maint"; break;
Dianne Hackbornb6843652016-02-22 12:20:13 -08003699 case EVENT_DEEP_IDLE: label = " deep-idle"; break;
3700 case EVENT_DEEP_MAINTENANCE: label = " deep-maint"; break;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08003701 default: label = " ??"; break;
3702 }
3703 pw.print(" ");
3704 pw.print(label);
3705 pw.print(": ");
Amith Yamasaniac6517a2018-04-23 12:19:34 -07003706 TimeUtils.formatDuration(mEventTimes[i], now, pw);
3707 if (mEventReasons[i] != null) {
3708 pw.print(" (");
3709 pw.print(mEventReasons[i]);
3710 pw.print(")");
3711 }
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08003712 pw.println();
Amith Yamasaniac6517a2018-04-23 12:19:34 -07003713
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08003714 }
3715 }
3716
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003717 int size = mPowerSaveWhitelistAppsExceptIdle.size();
3718 if (size > 0) {
3719 pw.println(" Whitelist (except idle) system apps:");
3720 for (int i = 0; i < size; i++) {
3721 pw.print(" ");
3722 pw.println(mPowerSaveWhitelistAppsExceptIdle.keyAt(i));
3723 }
3724 }
3725 size = mPowerSaveWhitelistApps.size();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003726 if (size > 0) {
3727 pw.println(" Whitelist system apps:");
3728 for (int i = 0; i < size; i++) {
3729 pw.print(" ");
3730 pw.println(mPowerSaveWhitelistApps.keyAt(i));
3731 }
3732 }
Suprabh Shukla08105642017-09-26 14:45:30 -07003733 size = mRemovedFromSystemWhitelistApps.size();
3734 if (size > 0) {
3735 pw.println(" Removed from whitelist system apps:");
3736 for (int i = 0; i < size; i++) {
3737 pw.print(" ");
3738 pw.println(mRemovedFromSystemWhitelistApps.keyAt(i));
3739 }
3740 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003741 size = mPowerSaveWhitelistUserApps.size();
3742 if (size > 0) {
3743 pw.println(" Whitelist user apps:");
3744 for (int i = 0; i < size; i++) {
3745 pw.print(" ");
3746 pw.println(mPowerSaveWhitelistUserApps.keyAt(i));
3747 }
3748 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003749 size = mPowerSaveWhitelistExceptIdleAppIds.size();
3750 if (size > 0) {
3751 pw.println(" Whitelist (except idle) all app ids:");
3752 for (int i = 0; i < size; i++) {
3753 pw.print(" ");
3754 pw.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
3755 pw.println();
3756 }
3757 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08003758 size = mPowerSaveWhitelistUserAppIds.size();
3759 if (size > 0) {
3760 pw.println(" Whitelist user app ids:");
3761 for (int i = 0; i < size; i++) {
3762 pw.print(" ");
3763 pw.print(mPowerSaveWhitelistUserAppIds.keyAt(i));
3764 pw.println();
3765 }
3766 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07003767 size = mPowerSaveWhitelistAllAppIds.size();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003768 if (size > 0) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07003769 pw.println(" Whitelist all app ids:");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003770 for (int i = 0; i < size; i++) {
Dianne Hackborna750a632015-06-16 17:18:23 -07003771 pw.print(" ");
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07003772 pw.print(mPowerSaveWhitelistAllAppIds.keyAt(i));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003773 pw.println();
3774 }
3775 }
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003776 dumpTempWhitelistSchedule(pw, true);
3777
Dianne Hackborna750a632015-06-16 17:18:23 -07003778 size = mTempWhitelistAppIdArray != null ? mTempWhitelistAppIdArray.length : 0;
3779 if (size > 0) {
3780 pw.println(" Temp whitelist app ids:");
3781 for (int i = 0; i < size; i++) {
3782 pw.print(" ");
3783 pw.print(mTempWhitelistAppIdArray[i]);
3784 pw.println();
3785 }
3786 }
Adam Lesinski31c05d12015-06-09 17:34:04 -07003787
Dianne Hackbornb6843652016-02-22 12:20:13 -08003788 pw.print(" mLightEnabled="); pw.print(mLightEnabled);
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003789 pw.print(" mDeepEnabled="); pw.println(mDeepEnabled);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003790 pw.print(" mForceIdle="); pw.println(mForceIdle);
Robin Leec4d424c2018-12-07 15:09:13 +01003791 pw.print(" mUseMotionSensor="); pw.print(mUseMotionSensor);
3792 if (mUseMotionSensor) {
3793 pw.print(" mMotionSensor="); pw.println(mMotionSensor);
3794 } else {
3795 pw.println();
3796 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003797 pw.print(" mScreenOn="); pw.println(mScreenOn);
Amith Yamasani396a10c2018-01-19 10:58:07 -08003798 pw.print(" mScreenLocked="); pw.println(mScreenLocked);
Dianne Hackborn88c41352016-04-07 15:18:58 -07003799 pw.print(" mNetworkConnected="); pw.println(mNetworkConnected);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003800 pw.print(" mCharging="); pw.println(mCharging);
Nick Vaccaro20feaea2015-09-17 17:22:44 -07003801 pw.print(" mMotionActive="); pw.println(mMotionListener.active);
Robin Leec4d424c2018-12-07 15:09:13 +01003802 if (mUseMotionSensor) {
3803 pw.print(" mNotMoving="); pw.println(mNotMoving);
3804 }
Joe LaPenna23d681b2015-08-27 15:12:11 -07003805 pw.print(" mLocating="); pw.print(mLocating); pw.print(" mHasGps=");
3806 pw.print(mHasGps); pw.print(" mHasNetwork=");
3807 pw.print(mHasNetworkLocation); pw.print(" mLocated="); pw.println(mLocated);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07003808 if (mLastGenericLocation != null) {
3809 pw.print(" mLastGenericLocation="); pw.println(mLastGenericLocation);
3810 }
3811 if (mLastGpsLocation != null) {
3812 pw.print(" mLastGpsLocation="); pw.println(mLastGpsLocation);
3813 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003814 pw.print(" mState="); pw.print(stateToString(mState));
3815 pw.print(" mLightState=");
3816 pw.println(lightStateToString(mLightState));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003817 pw.print(" mInactiveTimeout="); TimeUtils.formatDuration(mInactiveTimeout, pw);
3818 pw.println();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003819 if (mActiveIdleOpCount != 0) {
3820 pw.print(" mActiveIdleOpCount="); pw.println(mActiveIdleOpCount);
3821 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003822 if (mNextAlarmTime != 0) {
3823 pw.print(" mNextAlarmTime=");
3824 TimeUtils.formatDuration(mNextAlarmTime, SystemClock.elapsedRealtime(), pw);
3825 pw.println();
3826 }
3827 if (mNextIdlePendingDelay != 0) {
3828 pw.print(" mNextIdlePendingDelay=");
3829 TimeUtils.formatDuration(mNextIdlePendingDelay, pw);
3830 pw.println();
3831 }
3832 if (mNextIdleDelay != 0) {
3833 pw.print(" mNextIdleDelay=");
3834 TimeUtils.formatDuration(mNextIdleDelay, pw);
3835 pw.println();
3836 }
Dianne Hackborn953fc942016-03-29 15:36:24 -07003837 if (mNextLightIdleDelay != 0) {
3838 pw.print(" mNextIdleDelay=");
3839 TimeUtils.formatDuration(mNextLightIdleDelay, pw);
3840 pw.println();
3841 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003842 if (mNextLightAlarmTime != 0) {
3843 pw.print(" mNextLightAlarmTime=");
3844 TimeUtils.formatDuration(mNextLightAlarmTime, SystemClock.elapsedRealtime(), pw);
3845 pw.println();
3846 }
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08003847 if (mCurIdleBudget != 0) {
3848 pw.print(" mCurIdleBudget=");
3849 TimeUtils.formatDuration(mCurIdleBudget, pw);
3850 pw.println();
3851 }
3852 if (mMaintenanceStartTime != 0) {
3853 pw.print(" mMaintenanceStartTime=");
3854 TimeUtils.formatDuration(mMaintenanceStartTime, SystemClock.elapsedRealtime(), pw);
3855 pw.println();
3856 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003857 if (mJobsActive) {
3858 pw.print(" mJobsActive="); pw.println(mJobsActive);
3859 }
3860 if (mAlarmsActive) {
3861 pw.print(" mAlarmsActive="); pw.println(mAlarmsActive);
3862 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003863 }
3864 }
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003865
3866 void dumpTempWhitelistSchedule(PrintWriter pw, boolean printTitle) {
3867 final int size = mTempWhitelistAppIdEndTimes.size();
3868 if (size > 0) {
3869 String prefix = "";
3870 if (printTitle) {
3871 pw.println(" Temp whitelist schedule:");
3872 prefix = " ";
3873 }
3874 final long timeNow = SystemClock.elapsedRealtime();
3875 for (int i = 0; i < size; i++) {
3876 pw.print(prefix);
3877 pw.print("UID=");
3878 pw.print(mTempWhitelistAppIdEndTimes.keyAt(i));
3879 pw.print(": ");
3880 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.valueAt(i);
3881 TimeUtils.formatDuration(entry.first.value, timeNow, pw);
3882 pw.print(" - ");
3883 pw.println(entry.second);
3884 }
3885 }
3886 }
3887 }