blob: 44ca6a916c4791fd571e6c756216d5a2f20d60e6 [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;
33import android.hardware.SensorManager;
Nick Vaccaro20feaea2015-09-17 17:22:44 -070034import android.hardware.SensorEvent;
35import android.hardware.SensorEventListener;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070036import android.hardware.TriggerEvent;
37import android.hardware.TriggerEventListener;
38import android.hardware.display.DisplayManager;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -070039import android.location.LocationRequest;
40import android.location.Location;
41import android.location.LocationListener;
42import android.location.LocationManager;
Dianne Hackborn88c41352016-04-07 15:18:58 -070043import android.net.ConnectivityManager;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070044import android.net.INetworkPolicyManager;
Dianne Hackborn88c41352016-04-07 15:18:58 -070045import android.net.NetworkInfo;
Adam Lesinski31c05d12015-06-09 17:34:04 -070046import android.net.Uri;
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;
58import android.os.PowerManagerInternal;
Dianne Hackbornb6683c42015-06-18 17:40:33 -070059import android.os.Process;
Yao Chenca5edbb2016-01-13 14:44:36 -080060import android.os.RemoteCallbackList;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070061import android.os.RemoteException;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -070062import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070063import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070064import android.os.ShellCallback;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -070065import android.os.ShellCommand;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070066import android.os.SystemClock;
67import android.os.UserHandle;
Adam Lesinski31c05d12015-06-09 17:34:04 -070068import android.provider.Settings;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070069import android.util.ArrayMap;
70import android.util.ArraySet;
Adam Lesinski31c05d12015-06-09 17:34:04 -070071import android.util.KeyValueListParser;
Dianne Hackbornfd854ee2015-07-13 18:00:37 -070072import android.util.MutableLong;
73import android.util.Pair;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070074import android.util.Slog;
Dianne Hackbornfd854ee2015-07-13 18:00:37 -070075import android.util.SparseArray;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070076import android.util.SparseBooleanArray;
77import android.util.TimeUtils;
78import android.util.Xml;
79import android.view.Display;
Amith Yamasani520d8f22015-05-08 16:36:21 -070080
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070081import com.android.internal.app.IBatteryStats;
82import com.android.internal.os.AtomicFile;
83import com.android.internal.os.BackgroundThread;
84import com.android.internal.util.FastXmlSerializer;
85import com.android.internal.util.XmlUtils;
86import com.android.server.am.BatteryStatsService;
Amith Yamasani520d8f22015-05-08 16:36:21 -070087
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070088import org.xmlpull.v1.XmlPullParser;
89import org.xmlpull.v1.XmlPullParserException;
90import org.xmlpull.v1.XmlSerializer;
91
92import java.io.ByteArrayOutputStream;
93import java.io.File;
94import java.io.FileDescriptor;
95import java.io.FileInputStream;
96import java.io.FileNotFoundException;
97import java.io.FileOutputStream;
98import java.io.IOException;
99import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100100import java.nio.charset.StandardCharsets;
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700101import java.util.Arrays;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700102
103/**
104 * Keeps track of device idleness and drives low power mode based on that.
105 */
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700106public class DeviceIdleController extends SystemService
107 implements AnyMotionDetector.DeviceIdleCallback {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700108 private static final String TAG = "DeviceIdleController";
109
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700110 private static final boolean DEBUG = false;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700111
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700112 private static final boolean COMPRESS_TIME = false;
Amith Yamasani520d8f22015-05-08 16:36:21 -0700113
Dianne Hackborn953fc942016-03-29 15:36:24 -0700114 private static final int EVENT_BUFFER_SIZE = 100;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800115
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700116 private AlarmManager mAlarmManager;
117 private IBatteryStats mBatteryStats;
Dianne Hackborn85e35642017-01-12 15:10:57 -0800118 private ActivityManagerInternal mLocalActivityManager;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700119 private PowerManagerInternal mLocalPowerManager;
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700120 private PowerManager mPowerManager;
Dianne Hackborn88c41352016-04-07 15:18:58 -0700121 private ConnectivityService mConnectivityService;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -0800122 private AlarmManagerService.LocalService mLocalAlarmManager;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700123 private INetworkPolicyManager mNetworkPolicyManager;
124 private DisplayManager mDisplayManager;
125 private SensorManager mSensorManager;
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700126 private Sensor mMotionSensor;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700127 private LocationManager mLocationManager;
128 private LocationRequest mLocationRequest;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700129 private Intent mIdleIntent;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700130 private Intent mLightIdleIntent;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700131 private Display mCurDisplay;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700132 private AnyMotionDetector mAnyMotionDetector;
Dianne Hackbornb6843652016-02-22 12:20:13 -0800133 private boolean mLightEnabled;
134 private boolean mDeepEnabled;
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700135 private boolean mForceIdle;
Dianne Hackborn88c41352016-04-07 15:18:58 -0700136 private boolean mNetworkConnected;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700137 private boolean mScreenOn;
138 private boolean mCharging;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700139 private boolean mNotMoving;
140 private boolean mLocating;
141 private boolean mLocated;
Joe LaPenna23d681b2015-08-27 15:12:11 -0700142 private boolean mHasGps;
143 private boolean mHasNetworkLocation;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700144 private Location mLastGenericLocation;
145 private Location mLastGpsLocation;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700146
147 /** Device is currently active. */
148 private static final int STATE_ACTIVE = 0;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700149 /** Device is inactive (screen off, no motion) and we are waiting to for idle. */
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700150 private static final int STATE_INACTIVE = 1;
151 /** Device is past the initial inactive period, and waiting for the next idle period. */
152 private static final int STATE_IDLE_PENDING = 2;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700153 /** Device is currently sensing motion. */
154 private static final int STATE_SENSING = 3;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700155 /** Device is currently finding location (and may still be sensing). */
156 private static final int STATE_LOCATING = 4;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700157 /** Device is in the idle state, trying to stay asleep as much as possible. */
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700158 private static final int STATE_IDLE = 5;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700159 /** Device is in the idle state, but temporarily out of idle to do regular maintenance. */
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700160 private static final int STATE_IDLE_MAINTENANCE = 6;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700161 private static String stateToString(int state) {
162 switch (state) {
163 case STATE_ACTIVE: return "ACTIVE";
164 case STATE_INACTIVE: return "INACTIVE";
165 case STATE_IDLE_PENDING: return "IDLE_PENDING";
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700166 case STATE_SENSING: return "SENSING";
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700167 case STATE_LOCATING: return "LOCATING";
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700168 case STATE_IDLE: return "IDLE";
169 case STATE_IDLE_MAINTENANCE: return "IDLE_MAINTENANCE";
170 default: return Integer.toString(state);
171 }
172 }
173
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700174 /** Device is currently active. */
175 private static final int LIGHT_STATE_ACTIVE = 0;
176 /** Device is inactive (screen off) and we are waiting to for the first light idle. */
177 private static final int LIGHT_STATE_INACTIVE = 1;
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700178 /** Device is about to go idle for the first time, wait for current work to complete. */
179 private static final int LIGHT_STATE_PRE_IDLE = 3;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700180 /** Device is in the light idle state, trying to stay asleep as much as possible. */
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700181 private static final int LIGHT_STATE_IDLE = 4;
Dianne Hackborn88c41352016-04-07 15:18:58 -0700182 /** Device is in the light idle state, we want to go in to idle maintenance but are
183 * waiting for network connectivity before doing so. */
184 private static final int LIGHT_STATE_WAITING_FOR_NETWORK = 5;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700185 /** Device is in the light idle state, but temporarily out of idle to do regular maintenance. */
Dianne Hackborn88c41352016-04-07 15:18:58 -0700186 private static final int LIGHT_STATE_IDLE_MAINTENANCE = 6;
Dianne Hackbornb6843652016-02-22 12:20:13 -0800187 /** Device light idle state is overriden, now applying deep doze state. */
Dianne Hackborn88c41352016-04-07 15:18:58 -0700188 private static final int LIGHT_STATE_OVERRIDE = 7;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700189 private static String lightStateToString(int state) {
190 switch (state) {
191 case LIGHT_STATE_ACTIVE: return "ACTIVE";
192 case LIGHT_STATE_INACTIVE: return "INACTIVE";
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700193 case LIGHT_STATE_PRE_IDLE: return "PRE_IDLE";
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700194 case LIGHT_STATE_IDLE: return "IDLE";
Dianne Hackborn88c41352016-04-07 15:18:58 -0700195 case LIGHT_STATE_WAITING_FOR_NETWORK: return "WAITING_FOR_NETWORK";
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700196 case LIGHT_STATE_IDLE_MAINTENANCE: return "IDLE_MAINTENANCE";
197 case LIGHT_STATE_OVERRIDE: return "OVERRIDE";
198 default: return Integer.toString(state);
199 }
200 }
201
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700202 private int mState;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700203 private int mLightState;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700204
205 private long mInactiveTimeout;
206 private long mNextAlarmTime;
207 private long mNextIdlePendingDelay;
208 private long mNextIdleDelay;
Dianne Hackborn953fc942016-03-29 15:36:24 -0700209 private long mNextLightIdleDelay;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700210 private long mNextLightAlarmTime;
Kevin Gabayan92f15e62016-04-04 17:52:22 -0700211 private long mNextSensingTimeoutAlarmTime;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800212 private long mCurIdleBudget;
213 private long mMaintenanceStartTime;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700214
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800215 private int mActiveIdleOpCount;
Joe Onorato8f0e9ced2016-12-08 17:48:49 -0800216 private PowerManager.WakeLock mActiveIdleWakeLock; // held when there are operations in progress
217 private PowerManager.WakeLock mGoingIdleWakeLock; // held when we are going idle so hardware
218 // (especially NetworkPolicyManager) can shut
219 // down.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800220 private boolean mJobsActive;
221 private boolean mAlarmsActive;
Yao Chenca5edbb2016-01-13 14:44:36 -0800222 private boolean mReportedMaintenanceActivity;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800223
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700224 public final AtomicFile mConfigFile;
225
Yao Chenca5edbb2016-01-13 14:44:36 -0800226 private final RemoteCallbackList<IMaintenanceActivityListener> mMaintenanceActivityListeners =
227 new RemoteCallbackList<IMaintenanceActivityListener>();
228
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700229 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700230 * Package names the system has white-listed to opt out of power save restrictions,
231 * except for device idle mode.
232 */
233 private final ArrayMap<String, Integer> mPowerSaveWhitelistAppsExceptIdle = new ArrayMap<>();
234
235 /**
236 * Package names the system has white-listed to opt out of power save restrictions for
237 * all modes.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700238 */
239 private final ArrayMap<String, Integer> mPowerSaveWhitelistApps = new ArrayMap<>();
240
241 /**
242 * Package names the user has white-listed to opt out of power save restrictions.
243 */
244 private final ArrayMap<String, Integer> mPowerSaveWhitelistUserApps = new ArrayMap<>();
245
246 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700247 * App IDs of built-in system apps that have been white-listed except for idle modes.
248 */
249 private final SparseBooleanArray mPowerSaveWhitelistSystemAppIdsExceptIdle
250 = new SparseBooleanArray();
251
252 /**
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700253 * App IDs of built-in system apps that have been white-listed.
254 */
255 private final SparseBooleanArray mPowerSaveWhitelistSystemAppIds = new SparseBooleanArray();
256
257 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700258 * App IDs that have been white-listed to opt out of power save restrictions, except
259 * for device idle modes.
260 */
261 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
262
263 /**
264 * Current app IDs that are in the complete power save white list, but shouldn't be
265 * excluded from idle modes. This array can be shared with others because it will not be
266 * modified once set.
267 */
268 private int[] mPowerSaveWhitelistExceptIdleAppIdArray = new int[0];
269
270 /**
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700271 * App IDs that have been white-listed to opt out of power save restrictions.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700272 */
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700273 private final SparseBooleanArray mPowerSaveWhitelistAllAppIds = new SparseBooleanArray();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700274
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700275 /**
276 * Current app IDs that are in the complete power save white list. This array can
277 * be shared with others because it will not be modified once set.
278 */
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700279 private int[] mPowerSaveWhitelistAllAppIdArray = new int[0];
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700280
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700281 /**
Dianne Hackborn262ae5c2016-02-10 16:28:29 -0800282 * App IDs that have been white-listed by the user to opt out of power save restrictions.
283 */
284 private final SparseBooleanArray mPowerSaveWhitelistUserAppIds = new SparseBooleanArray();
285
286 /**
287 * Current app IDs that are in the user power save white list. This array can
288 * be shared with others because it will not be modified once set.
289 */
290 private int[] mPowerSaveWhitelistUserAppIdArray = new int[0];
291
292 /**
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700293 * List of end times for UIDs that are temporarily marked as being allowed to access
294 * the network and acquire wakelocks. Times are in milliseconds.
295 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700296 private final SparseArray<Pair<MutableLong, String>> mTempWhitelistAppIdEndTimes
297 = new SparseArray<>();
298
299 /**
300 * Callback to the NetworkPolicyManagerService to tell it that the temp whitelist has changed.
301 */
302 Runnable mNetworkPolicyTempWhitelistCallback;
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700303
304 /**
305 * Current app IDs of temporarily whitelist apps for high-priority messages.
306 */
307 private int[] mTempWhitelistAppIdArray = new int[0];
308
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800309 private static final int EVENT_NULL = 0;
310 private static final int EVENT_NORMAL = 1;
311 private static final int EVENT_LIGHT_IDLE = 2;
312 private static final int EVENT_LIGHT_MAINTENANCE = 3;
Dianne Hackbornb6843652016-02-22 12:20:13 -0800313 private static final int EVENT_DEEP_IDLE = 4;
314 private static final int EVENT_DEEP_MAINTENANCE = 5;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800315
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -0700316 private final int[] mEventCmds = new int[EVENT_BUFFER_SIZE];
317 private final long[] mEventTimes = new long[EVENT_BUFFER_SIZE];
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800318
319 private void addEvent(int cmd) {
320 if (mEventCmds[0] != cmd) {
321 System.arraycopy(mEventCmds, 0, mEventCmds, 1, EVENT_BUFFER_SIZE - 1);
322 System.arraycopy(mEventTimes, 0, mEventTimes, 1, EVENT_BUFFER_SIZE - 1);
323 mEventCmds[0] = cmd;
324 mEventTimes[0] = SystemClock.elapsedRealtime();
325 }
326 }
327
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700328 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
329 @Override public void onReceive(Context context, Intent intent) {
Dianne Hackborn88c41352016-04-07 15:18:58 -0700330 switch (intent.getAction()) {
331 case ConnectivityManager.CONNECTIVITY_ACTION: {
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -0700332 updateConnectivityState(intent);
Dianne Hackborn88c41352016-04-07 15:18:58 -0700333 } break;
334 case Intent.ACTION_BATTERY_CHANGED: {
335 synchronized (DeviceIdleController.this) {
336 int plugged = intent.getIntExtra("plugged", 0);
337 updateChargingLocked(plugged != 0);
338 }
339 } break;
340 case Intent.ACTION_PACKAGE_REMOVED: {
341 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
342 Uri data = intent.getData();
343 String ssp;
344 if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
345 removePowerSaveWhitelistAppInternal(ssp);
346 }
347 }
348 } break;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700349 }
350 }
351 };
352
353 private final AlarmManager.OnAlarmListener mLightAlarmListener
354 = new AlarmManager.OnAlarmListener() {
355 @Override
356 public void onAlarm() {
357 synchronized (DeviceIdleController.this) {
358 stepLightIdleStateLocked("s:alarm");
359 }
360 }
361 };
362
Kevin Gabayan92f15e62016-04-04 17:52:22 -0700363 private final AlarmManager.OnAlarmListener mSensingTimeoutAlarmListener
364 = new AlarmManager.OnAlarmListener() {
365 @Override
366 public void onAlarm() {
367 if (mState == STATE_SENSING) {
368 synchronized (DeviceIdleController.this) {
369 becomeInactiveIfAppropriateLocked();
370 }
371 }
372 }
373 };
374
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700375 private final AlarmManager.OnAlarmListener mDeepAlarmListener
376 = new AlarmManager.OnAlarmListener() {
377 @Override
378 public void onAlarm() {
379 synchronized (DeviceIdleController.this) {
380 stepIdleStateLocked("s:alarm");
381 }
382 }
383 };
384
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800385 private final BroadcastReceiver mIdleStartedDoneReceiver = new BroadcastReceiver() {
386 @Override public void onReceive(Context context, Intent intent) {
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700387 // When coming out of a deep idle, we will add in some delay before we allow
388 // the system to settle down and finish the maintenance window. This is
389 // to give a chance for any pending work to be scheduled.
390 if (PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED.equals(intent.getAction())) {
391 mHandler.sendEmptyMessageDelayed(MSG_FINISH_IDLE_OP,
392 mConstants.MIN_DEEP_MAINTENANCE_TIME);
393 } else {
394 mHandler.sendEmptyMessageDelayed(MSG_FINISH_IDLE_OP,
395 mConstants.MIN_LIGHT_MAINTENANCE_TIME);
396 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800397 }
398 };
399
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700400 private final DisplayManager.DisplayListener mDisplayListener
401 = new DisplayManager.DisplayListener() {
402 @Override public void onDisplayAdded(int displayId) {
403 }
404
405 @Override public void onDisplayRemoved(int displayId) {
406 }
407
408 @Override public void onDisplayChanged(int displayId) {
409 if (displayId == Display.DEFAULT_DISPLAY) {
410 synchronized (DeviceIdleController.this) {
411 updateDisplayLocked();
412 }
413 }
414 }
415 };
416
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700417 private final class MotionListener extends TriggerEventListener
418 implements SensorEventListener {
419
420 boolean active = false;
421
422 @Override
423 public void onTrigger(TriggerEvent event) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700424 synchronized (DeviceIdleController.this) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700425 active = false;
426 motionLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700427 }
428 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700429
430 @Override
431 public void onSensorChanged(SensorEvent event) {
432 synchronized (DeviceIdleController.this) {
433 mSensorManager.unregisterListener(this, mMotionSensor);
434 active = false;
435 motionLocked();
436 }
437 }
438
439 @Override
440 public void onAccuracyChanged(Sensor sensor, int accuracy) {}
441
442 public boolean registerLocked() {
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700443 boolean success;
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700444 if (mMotionSensor.getReportingMode() == Sensor.REPORTING_MODE_ONE_SHOT) {
445 success = mSensorManager.requestTriggerSensor(mMotionListener, mMotionSensor);
446 } else {
447 success = mSensorManager.registerListener(
448 mMotionListener, mMotionSensor, SensorManager.SENSOR_DELAY_NORMAL);
449 }
450 if (success) {
451 active = true;
452 } else {
453 Slog.e(TAG, "Unable to register for " + mMotionSensor);
454 }
455 return success;
456 }
457
458 public void unregisterLocked() {
459 if (mMotionSensor.getReportingMode() == Sensor.REPORTING_MODE_ONE_SHOT) {
460 mSensorManager.cancelTriggerSensor(mMotionListener, mMotionSensor);
461 } else {
462 mSensorManager.unregisterListener(mMotionListener);
463 }
464 active = false;
465 }
466 }
467 private final MotionListener mMotionListener = new MotionListener();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700468
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700469 private final LocationListener mGenericLocationListener = new LocationListener() {
470 @Override
471 public void onLocationChanged(Location location) {
472 synchronized (DeviceIdleController.this) {
473 receivedGenericLocationLocked(location);
474 }
475 }
476
477 @Override
478 public void onStatusChanged(String provider, int status, Bundle extras) {
479 }
480
481 @Override
482 public void onProviderEnabled(String provider) {
483 }
484
485 @Override
486 public void onProviderDisabled(String provider) {
487 }
488 };
489
490 private final LocationListener mGpsLocationListener = new LocationListener() {
491 @Override
492 public void onLocationChanged(Location location) {
493 synchronized (DeviceIdleController.this) {
494 receivedGpsLocationLocked(location);
495 }
496 }
497
498 @Override
499 public void onStatusChanged(String provider, int status, Bundle extras) {
500 }
501
502 @Override
503 public void onProviderEnabled(String provider) {
504 }
505
506 @Override
507 public void onProviderDisabled(String provider) {
508 }
509 };
510
Adam Lesinski31c05d12015-06-09 17:34:04 -0700511 /**
512 * All times are in milliseconds. These constants are kept synchronized with the system
513 * global Settings. Any access to this class or its fields should be done while
514 * holding the DeviceIdleController lock.
515 */
Dianne Hackborna750a632015-06-16 17:18:23 -0700516 private final class Constants extends ContentObserver {
Adam Lesinski31c05d12015-06-09 17:34:04 -0700517 // Key names stored in the settings value.
Dianne Hackborn953fc942016-03-29 15:36:24 -0700518 private static final String KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT
519 = "light_after_inactive_to";
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700520 private static final String KEY_LIGHT_PRE_IDLE_TIMEOUT = "light_pre_idle_to";
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700521 private static final String KEY_LIGHT_IDLE_TIMEOUT = "light_idle_to";
Dianne Hackborn953fc942016-03-29 15:36:24 -0700522 private static final String KEY_LIGHT_IDLE_FACTOR = "light_idle_factor";
523 private static final String KEY_LIGHT_MAX_IDLE_TIMEOUT = "light_max_idle_to";
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800524 private static final String KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET
525 = "light_idle_maintenance_min_budget";
526 private static final String KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET
527 = "light_idle_maintenance_max_budget";
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700528 private static final String KEY_MIN_LIGHT_MAINTENANCE_TIME = "min_light_maintenance_time";
529 private static final String KEY_MIN_DEEP_MAINTENANCE_TIME = "min_deep_maintenance_time";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700530 private static final String KEY_INACTIVE_TIMEOUT = "inactive_to";
531 private static final String KEY_SENSING_TIMEOUT = "sensing_to";
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700532 private static final String KEY_LOCATING_TIMEOUT = "locating_to";
533 private static final String KEY_LOCATION_ACCURACY = "location_accuracy";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700534 private static final String KEY_MOTION_INACTIVE_TIMEOUT = "motion_inactive_to";
535 private static final String KEY_IDLE_AFTER_INACTIVE_TIMEOUT = "idle_after_inactive_to";
536 private static final String KEY_IDLE_PENDING_TIMEOUT = "idle_pending_to";
537 private static final String KEY_MAX_IDLE_PENDING_TIMEOUT = "max_idle_pending_to";
538 private static final String KEY_IDLE_PENDING_FACTOR = "idle_pending_factor";
539 private static final String KEY_IDLE_TIMEOUT = "idle_to";
540 private static final String KEY_MAX_IDLE_TIMEOUT = "max_idle_to";
541 private static final String KEY_IDLE_FACTOR = "idle_factor";
542 private static final String KEY_MIN_TIME_TO_ALARM = "min_time_to_alarm";
543 private static final String KEY_MAX_TEMP_APP_WHITELIST_DURATION =
544 "max_temp_app_whitelist_duration";
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700545 private static final String KEY_MMS_TEMP_APP_WHITELIST_DURATION =
546 "mms_temp_app_whitelist_duration";
Dianne Hackborn451c3462015-07-21 17:39:46 -0700547 private static final String KEY_SMS_TEMP_APP_WHITELIST_DURATION =
548 "sms_temp_app_whitelist_duration";
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700549 private static final String KEY_NOTIFICATION_WHITELIST_DURATION =
550 "notification_whitelist_duration";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700551
552 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700553 * This is the time, after becoming inactive, that we go in to the first
554 * light-weight idle mode.
555 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
556 * @see #KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT
557 */
558 public long LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT;
559
560 /**
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700561 * This is amount of time we will wait from the point where we decide we would
562 * like to go idle until we actually do, while waiting for jobs and other current
563 * activity to finish.
564 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
565 * @see #KEY_LIGHT_PRE_IDLE_TIMEOUT
566 */
567 public long LIGHT_PRE_IDLE_TIMEOUT;
568
569 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700570 * This is the initial time that we will run in idle maintenance mode.
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700571 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
572 * @see #KEY_LIGHT_IDLE_TIMEOUT
573 */
574 public long LIGHT_IDLE_TIMEOUT;
575
576 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700577 * Scaling factor to apply to the light idle mode time each time we complete a cycle.
578 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
579 * @see #KEY_LIGHT_IDLE_FACTOR
580 */
581 public float LIGHT_IDLE_FACTOR;
582
583 /**
584 * This is the maximum time we will run in idle maintenence mode.
585 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
586 * @see #KEY_LIGHT_MAX_IDLE_TIMEOUT
587 */
588 public long LIGHT_MAX_IDLE_TIMEOUT;
589
590 /**
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800591 * This is the minimum amount of time we want to make available for maintenance mode
592 * when lightly idling. That is, we will always have at least this amount of time
593 * available maintenance before timing out and cutting off maintenance mode.
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700594 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800595 * @see #KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700596 */
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800597 public long LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
598
599 /**
600 * This is the maximum amount of time we want to make available for maintenance mode
601 * when lightly idling. That is, if the system isn't using up its minimum maintenance
602 * budget and this time is being added to the budget reserve, this is the maximum
603 * reserve size we will allow to grow and thus the maximum amount of time we will
604 * allow for the maintenance window.
605 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
606 * @see #KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET
607 */
608 public long LIGHT_IDLE_MAINTENANCE_MAX_BUDGET;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700609
610 /**
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700611 * This is the minimum amount of time that we will stay in maintenance mode after
612 * a light doze. We have this minimum to allow various things to respond to switching
613 * in to maintenance mode and scheduling their work -- otherwise we may
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700614 * see there is nothing to do (no jobs pending) and go out of maintenance
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700615 * mode immediately.
616 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
617 * @see #KEY_MIN_LIGHT_MAINTENANCE_TIME
618 */
619 public long MIN_LIGHT_MAINTENANCE_TIME;
620
621 /**
622 * This is the minimum amount of time that we will stay in maintenance mode after
623 * a full doze. We have this minimum to allow various things to respond to switching
624 * in to maintenance mode and scheduling their work -- otherwise we may
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700625 * see there is nothing to do (no jobs pending) and go out of maintenance
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700626 * mode immediately.
627 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
628 * @see #KEY_MIN_DEEP_MAINTENANCE_TIME
629 */
630 public long MIN_DEEP_MAINTENANCE_TIME;
631
632 /**
Adam Lesinski31c05d12015-06-09 17:34:04 -0700633 * This is the time, after becoming inactive, at which we start looking at the
634 * motion sensor to determine if the device is being left alone. We don't do this
635 * immediately after going inactive just because we don't want to be continually running
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700636 * the motion sensor whenever the screen is off.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700637 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
638 * @see #KEY_INACTIVE_TIMEOUT
639 */
640 public long INACTIVE_TIMEOUT;
641
642 /**
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700643 * If we don't receive a callback from AnyMotion in this amount of time +
644 * {@link #LOCATING_TIMEOUT}, we will change from
Adam Lesinski31c05d12015-06-09 17:34:04 -0700645 * STATE_SENSING to STATE_INACTIVE, and any AnyMotion callbacks while not in STATE_SENSING
646 * will be ignored.
647 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
648 * @see #KEY_SENSING_TIMEOUT
649 */
650 public long SENSING_TIMEOUT;
651
652 /**
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700653 * This is how long we will wait to try to get a good location fix before going in to
654 * idle mode.
655 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
656 * @see #KEY_LOCATING_TIMEOUT
657 */
658 public long LOCATING_TIMEOUT;
659
660 /**
661 * The desired maximum accuracy (in meters) we consider the location to be good enough to go
662 * on to idle. We will be trying to get an accuracy fix at least this good or until
663 * {@link #LOCATING_TIMEOUT} expires.
664 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
665 * @see #KEY_LOCATION_ACCURACY
666 */
667 public float LOCATION_ACCURACY;
668
669 /**
Adam Lesinski31c05d12015-06-09 17:34:04 -0700670 * This is the time, after seeing motion, that we wait after becoming inactive from
671 * that until we start looking for motion again.
672 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
673 * @see #KEY_MOTION_INACTIVE_TIMEOUT
674 */
675 public long MOTION_INACTIVE_TIMEOUT;
676
677 /**
678 * This is the time, after the inactive timeout elapses, that we will wait looking
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700679 * for motion until we truly consider the device to be idle.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700680 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
681 * @see #KEY_IDLE_AFTER_INACTIVE_TIMEOUT
682 */
683 public long IDLE_AFTER_INACTIVE_TIMEOUT;
684
685 /**
686 * This is the initial time, after being idle, that we will allow ourself to be back
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700687 * in the IDLE_MAINTENANCE state allowing the system to run normally until we return to
688 * idle.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700689 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
690 * @see #KEY_IDLE_PENDING_TIMEOUT
691 */
692 public long IDLE_PENDING_TIMEOUT;
693
694 /**
695 * Maximum pending idle timeout (time spent running) we will be allowed to use.
696 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
697 * @see #KEY_MAX_IDLE_PENDING_TIMEOUT
698 */
699 public long MAX_IDLE_PENDING_TIMEOUT;
700
701 /**
702 * Scaling factor to apply to current pending idle timeout each time we cycle through
703 * that state.
704 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
705 * @see #KEY_IDLE_PENDING_FACTOR
706 */
707 public float IDLE_PENDING_FACTOR;
708
709 /**
710 * This is the initial time that we want to sit in the idle state before waking up
711 * again to return to pending idle and allowing normal work to run.
712 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
713 * @see #KEY_IDLE_TIMEOUT
714 */
715 public long IDLE_TIMEOUT;
716
717 /**
718 * Maximum idle duration we will be allowed to use.
719 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
720 * @see #KEY_MAX_IDLE_TIMEOUT
721 */
722 public long MAX_IDLE_TIMEOUT;
723
724 /**
725 * Scaling factor to apply to current idle timeout each time we cycle through that state.
726 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
727 * @see #KEY_IDLE_FACTOR
728 */
729 public float IDLE_FACTOR;
730
731 /**
732 * This is the minimum time we will allow until the next upcoming alarm for us to
733 * actually go in to idle mode.
734 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
735 * @see #KEY_MIN_TIME_TO_ALARM
736 */
737 public long MIN_TIME_TO_ALARM;
738
739 /**
740 * Max amount of time to temporarily whitelist an app when it receives a high priority
741 * tickle.
742 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
743 * @see #KEY_MAX_TEMP_APP_WHITELIST_DURATION
744 */
745 public long MAX_TEMP_APP_WHITELIST_DURATION;
746
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700747 /**
748 * Amount of time we would like to whitelist an app that is receiving an MMS.
749 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
750 * @see #KEY_MMS_TEMP_APP_WHITELIST_DURATION
751 */
752 public long MMS_TEMP_APP_WHITELIST_DURATION;
753
Dianne Hackborn451c3462015-07-21 17:39:46 -0700754 /**
755 * Amount of time we would like to whitelist an app that is receiving an SMS.
756 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
757 * @see #KEY_SMS_TEMP_APP_WHITELIST_DURATION
758 */
759 public long SMS_TEMP_APP_WHITELIST_DURATION;
760
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700761 /**
762 * Amount of time we would like to whitelist an app that is handling a
763 * {@link android.app.PendingIntent} triggered by a {@link android.app.Notification}.
764 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
765 * @see #KEY_NOTIFICATION_WHITELIST_DURATION
766 */
767 public long NOTIFICATION_WHITELIST_DURATION;
768
Adam Lesinski31c05d12015-06-09 17:34:04 -0700769 private final ContentResolver mResolver;
Joe LaPennaf33b5bf2016-03-23 15:19:47 -0700770 private final boolean mHasWatch;
Adam Lesinski31c05d12015-06-09 17:34:04 -0700771 private final KeyValueListParser mParser = new KeyValueListParser(',');
772
773 public Constants(Handler handler, ContentResolver resolver) {
774 super(handler);
775 mResolver = resolver;
Joe LaPennaf33b5bf2016-03-23 15:19:47 -0700776 mHasWatch = getContext().getPackageManager().hasSystemFeature(
777 PackageManager.FEATURE_WATCH);
778 mResolver.registerContentObserver(Settings.Global.getUriFor(
779 mHasWatch ? Settings.Global.DEVICE_IDLE_CONSTANTS_WATCH
780 : Settings.Global.DEVICE_IDLE_CONSTANTS),
781 false, this);
Adam Lesinski31c05d12015-06-09 17:34:04 -0700782 updateConstants();
783 }
784
785 @Override
786 public void onChange(boolean selfChange, Uri uri) {
787 updateConstants();
788 }
789
790 private void updateConstants() {
791 synchronized (DeviceIdleController.this) {
792 try {
793 mParser.setString(Settings.Global.getString(mResolver,
Joe LaPennaf33b5bf2016-03-23 15:19:47 -0700794 mHasWatch ? Settings.Global.DEVICE_IDLE_CONSTANTS_WATCH
795 : Settings.Global.DEVICE_IDLE_CONSTANTS));
Adam Lesinski31c05d12015-06-09 17:34:04 -0700796 } catch (IllegalArgumentException e) {
797 // Failed to parse the settings string, log this and move on
798 // with defaults.
799 Slog.e(TAG, "Bad device idle settings", e);
800 }
801
Dianne Hackborn953fc942016-03-29 15:36:24 -0700802 LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT = mParser.getLong(
803 KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT,
804 !COMPRESS_TIME ? 5 * 60 * 1000L : 15 * 1000L);
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700805 LIGHT_PRE_IDLE_TIMEOUT = mParser.getLong(KEY_LIGHT_PRE_IDLE_TIMEOUT,
806 !COMPRESS_TIME ? 10 * 60 * 1000L : 30 * 1000L);
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700807 LIGHT_IDLE_TIMEOUT = mParser.getLong(KEY_LIGHT_IDLE_TIMEOUT,
Dianne Hackborn953fc942016-03-29 15:36:24 -0700808 !COMPRESS_TIME ? 5 * 60 * 1000L : 15 * 1000L);
809 LIGHT_IDLE_FACTOR = mParser.getFloat(KEY_LIGHT_IDLE_FACTOR,
810 2f);
811 LIGHT_MAX_IDLE_TIMEOUT = mParser.getLong(KEY_LIGHT_MAX_IDLE_TIMEOUT,
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700812 !COMPRESS_TIME ? 15 * 60 * 1000L : 60 * 1000L);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800813 LIGHT_IDLE_MAINTENANCE_MIN_BUDGET = mParser.getLong(
814 KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET,
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700815 !COMPRESS_TIME ? 1 * 60 * 1000L : 15 * 1000L);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800816 LIGHT_IDLE_MAINTENANCE_MAX_BUDGET = mParser.getLong(
817 KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET,
818 !COMPRESS_TIME ? 5 * 60 * 1000L : 30 * 1000L);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700819 MIN_LIGHT_MAINTENANCE_TIME = mParser.getLong(
820 KEY_MIN_LIGHT_MAINTENANCE_TIME,
821 !COMPRESS_TIME ? 5 * 1000L : 1 * 1000L);
822 MIN_DEEP_MAINTENANCE_TIME = mParser.getLong(
823 KEY_MIN_DEEP_MAINTENANCE_TIME,
824 !COMPRESS_TIME ? 30 * 1000L : 5 * 1000L);
Joe LaPenna0c5d3e92016-03-24 13:29:56 -0700825 long inactiveTimeoutDefault = (mHasWatch ? 15 : 30) * 60 * 1000L;
Adam Lesinski31c05d12015-06-09 17:34:04 -0700826 INACTIVE_TIMEOUT = mParser.getLong(KEY_INACTIVE_TIMEOUT,
Joe LaPenna0c5d3e92016-03-24 13:29:56 -0700827 !COMPRESS_TIME ? inactiveTimeoutDefault : (inactiveTimeoutDefault / 10));
Adam Lesinski31c05d12015-06-09 17:34:04 -0700828 SENSING_TIMEOUT = mParser.getLong(KEY_SENSING_TIMEOUT,
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700829 !DEBUG ? 4 * 60 * 1000L : 60 * 1000L);
830 LOCATING_TIMEOUT = mParser.getLong(KEY_LOCATING_TIMEOUT,
831 !DEBUG ? 30 * 1000L : 15 * 1000L);
832 LOCATION_ACCURACY = mParser.getFloat(KEY_LOCATION_ACCURACY, 20);
Adam Lesinski31c05d12015-06-09 17:34:04 -0700833 MOTION_INACTIVE_TIMEOUT = mParser.getLong(KEY_MOTION_INACTIVE_TIMEOUT,
834 !COMPRESS_TIME ? 10 * 60 * 1000L : 60 * 1000L);
Joe LaPenna0c5d3e92016-03-24 13:29:56 -0700835 long idleAfterInactiveTimeout = (mHasWatch ? 15 : 30) * 60 * 1000L;
Adam Lesinski31c05d12015-06-09 17:34:04 -0700836 IDLE_AFTER_INACTIVE_TIMEOUT = mParser.getLong(KEY_IDLE_AFTER_INACTIVE_TIMEOUT,
Joe LaPenna0c5d3e92016-03-24 13:29:56 -0700837 !COMPRESS_TIME ? idleAfterInactiveTimeout
838 : (idleAfterInactiveTimeout / 10));
Adam Lesinski31c05d12015-06-09 17:34:04 -0700839 IDLE_PENDING_TIMEOUT = mParser.getLong(KEY_IDLE_PENDING_TIMEOUT,
840 !COMPRESS_TIME ? 5 * 60 * 1000L : 30 * 1000L);
841 MAX_IDLE_PENDING_TIMEOUT = mParser.getLong(KEY_MAX_IDLE_PENDING_TIMEOUT,
842 !COMPRESS_TIME ? 10 * 60 * 1000L : 60 * 1000L);
843 IDLE_PENDING_FACTOR = mParser.getFloat(KEY_IDLE_PENDING_FACTOR,
844 2f);
845 IDLE_TIMEOUT = mParser.getLong(KEY_IDLE_TIMEOUT,
846 !COMPRESS_TIME ? 60 * 60 * 1000L : 6 * 60 * 1000L);
847 MAX_IDLE_TIMEOUT = mParser.getLong(KEY_MAX_IDLE_TIMEOUT,
848 !COMPRESS_TIME ? 6 * 60 * 60 * 1000L : 30 * 60 * 1000L);
849 IDLE_FACTOR = mParser.getFloat(KEY_IDLE_FACTOR,
850 2f);
851 MIN_TIME_TO_ALARM = mParser.getLong(KEY_MIN_TIME_TO_ALARM,
852 !COMPRESS_TIME ? 60 * 60 * 1000L : 6 * 60 * 1000L);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700853 MAX_TEMP_APP_WHITELIST_DURATION = mParser.getLong(
854 KEY_MAX_TEMP_APP_WHITELIST_DURATION, 5 * 60 * 1000L);
855 MMS_TEMP_APP_WHITELIST_DURATION = mParser.getLong(
Dianne Hackborn0b6134b2015-07-14 18:48:07 -0700856 KEY_MMS_TEMP_APP_WHITELIST_DURATION, 60 * 1000L);
Dianne Hackborn451c3462015-07-21 17:39:46 -0700857 SMS_TEMP_APP_WHITELIST_DURATION = mParser.getLong(
858 KEY_SMS_TEMP_APP_WHITELIST_DURATION, 20 * 1000L);
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700859 NOTIFICATION_WHITELIST_DURATION = mParser.getLong(
860 KEY_NOTIFICATION_WHITELIST_DURATION, 30 * 1000L);
Adam Lesinski31c05d12015-06-09 17:34:04 -0700861 }
862 }
863
864 void dump(PrintWriter pw) {
865 pw.println(" Settings:");
866
Dianne Hackborn953fc942016-03-29 15:36:24 -0700867 pw.print(" "); pw.print(KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT); pw.print("=");
868 TimeUtils.formatDuration(LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT, pw);
869 pw.println();
870
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700871 pw.print(" "); pw.print(KEY_LIGHT_PRE_IDLE_TIMEOUT); pw.print("=");
872 TimeUtils.formatDuration(LIGHT_PRE_IDLE_TIMEOUT, pw);
873 pw.println();
874
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700875 pw.print(" "); pw.print(KEY_LIGHT_IDLE_TIMEOUT); pw.print("=");
876 TimeUtils.formatDuration(LIGHT_IDLE_TIMEOUT, pw);
877 pw.println();
878
Dianne Hackborn953fc942016-03-29 15:36:24 -0700879 pw.print(" "); pw.print(KEY_LIGHT_IDLE_FACTOR); pw.print("=");
880 pw.print(LIGHT_IDLE_FACTOR);
881 pw.println();
882
883 pw.print(" "); pw.print(KEY_LIGHT_MAX_IDLE_TIMEOUT); pw.print("=");
884 TimeUtils.formatDuration(LIGHT_MAX_IDLE_TIMEOUT, pw);
885 pw.println();
886
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800887 pw.print(" "); pw.print(KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET); pw.print("=");
888 TimeUtils.formatDuration(LIGHT_IDLE_MAINTENANCE_MIN_BUDGET, pw);
889 pw.println();
890
891 pw.print(" "); pw.print(KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET); pw.print("=");
892 TimeUtils.formatDuration(LIGHT_IDLE_MAINTENANCE_MAX_BUDGET, pw);
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700893 pw.println();
894
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700895 pw.print(" "); pw.print(KEY_MIN_LIGHT_MAINTENANCE_TIME); pw.print("=");
896 TimeUtils.formatDuration(MIN_LIGHT_MAINTENANCE_TIME, pw);
897 pw.println();
898
899 pw.print(" "); pw.print(KEY_MIN_DEEP_MAINTENANCE_TIME); pw.print("=");
900 TimeUtils.formatDuration(MIN_DEEP_MAINTENANCE_TIME, pw);
901 pw.println();
902
Dianne Hackborna750a632015-06-16 17:18:23 -0700903 pw.print(" "); pw.print(KEY_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700904 TimeUtils.formatDuration(INACTIVE_TIMEOUT, pw);
905 pw.println();
906
Dianne Hackborna750a632015-06-16 17:18:23 -0700907 pw.print(" "); pw.print(KEY_SENSING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700908 TimeUtils.formatDuration(SENSING_TIMEOUT, pw);
909 pw.println();
910
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700911 pw.print(" "); pw.print(KEY_LOCATING_TIMEOUT); pw.print("=");
912 TimeUtils.formatDuration(LOCATING_TIMEOUT, pw);
913 pw.println();
914
915 pw.print(" "); pw.print(KEY_LOCATION_ACCURACY); pw.print("=");
916 pw.print(LOCATION_ACCURACY); pw.print("m");
917 pw.println();
918
Dianne Hackborna750a632015-06-16 17:18:23 -0700919 pw.print(" "); pw.print(KEY_MOTION_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700920 TimeUtils.formatDuration(MOTION_INACTIVE_TIMEOUT, pw);
921 pw.println();
922
Dianne Hackborna750a632015-06-16 17:18:23 -0700923 pw.print(" "); pw.print(KEY_IDLE_AFTER_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700924 TimeUtils.formatDuration(IDLE_AFTER_INACTIVE_TIMEOUT, pw);
925 pw.println();
926
Dianne Hackborna750a632015-06-16 17:18:23 -0700927 pw.print(" "); pw.print(KEY_IDLE_PENDING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700928 TimeUtils.formatDuration(IDLE_PENDING_TIMEOUT, pw);
929 pw.println();
930
Dianne Hackborna750a632015-06-16 17:18:23 -0700931 pw.print(" "); pw.print(KEY_MAX_IDLE_PENDING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700932 TimeUtils.formatDuration(MAX_IDLE_PENDING_TIMEOUT, pw);
933 pw.println();
934
Dianne Hackborna750a632015-06-16 17:18:23 -0700935 pw.print(" "); pw.print(KEY_IDLE_PENDING_FACTOR); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700936 pw.println(IDLE_PENDING_FACTOR);
937
Dianne Hackborna750a632015-06-16 17:18:23 -0700938 pw.print(" "); pw.print(KEY_IDLE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700939 TimeUtils.formatDuration(IDLE_TIMEOUT, pw);
940 pw.println();
941
Dianne Hackborna750a632015-06-16 17:18:23 -0700942 pw.print(" "); pw.print(KEY_MAX_IDLE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700943 TimeUtils.formatDuration(MAX_IDLE_TIMEOUT, pw);
944 pw.println();
945
Dianne Hackborna750a632015-06-16 17:18:23 -0700946 pw.print(" "); pw.print(KEY_IDLE_FACTOR); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700947 pw.println(IDLE_FACTOR);
948
Dianne Hackborna750a632015-06-16 17:18:23 -0700949 pw.print(" "); pw.print(KEY_MIN_TIME_TO_ALARM); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700950 TimeUtils.formatDuration(MIN_TIME_TO_ALARM, pw);
951 pw.println();
952
Dianne Hackborna750a632015-06-16 17:18:23 -0700953 pw.print(" "); pw.print(KEY_MAX_TEMP_APP_WHITELIST_DURATION); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700954 TimeUtils.formatDuration(MAX_TEMP_APP_WHITELIST_DURATION, pw);
955 pw.println();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700956
957 pw.print(" "); pw.print(KEY_MMS_TEMP_APP_WHITELIST_DURATION); pw.print("=");
958 TimeUtils.formatDuration(MMS_TEMP_APP_WHITELIST_DURATION, pw);
959 pw.println();
Dianne Hackborn451c3462015-07-21 17:39:46 -0700960
961 pw.print(" "); pw.print(KEY_SMS_TEMP_APP_WHITELIST_DURATION); pw.print("=");
962 TimeUtils.formatDuration(SMS_TEMP_APP_WHITELIST_DURATION, pw);
963 pw.println();
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700964
965 pw.print(" "); pw.print(KEY_NOTIFICATION_WHITELIST_DURATION); pw.print("=");
966 TimeUtils.formatDuration(NOTIFICATION_WHITELIST_DURATION, pw);
967 pw.println();
Adam Lesinski31c05d12015-06-09 17:34:04 -0700968 }
969 }
970
971 private Constants mConstants;
972
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700973 @Override
974 public void onAnyMotionResult(int result) {
975 if (DEBUG) Slog.d(TAG, "onAnyMotionResult(" + result + ")");
Kevin Gabayan92f15e62016-04-04 17:52:22 -0700976 if (result != AnyMotionDetector.RESULT_UNKNOWN) {
977 synchronized (this) {
978 cancelSensingTimeoutAlarmLocked();
979 }
980 }
Kevin Gabayandcf47012016-07-08 10:41:24 -0700981 if ((result == AnyMotionDetector.RESULT_MOVED) ||
982 (result == AnyMotionDetector.RESULT_UNKNOWN)) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700983 synchronized (this) {
Kevin Gabayandcf47012016-07-08 10:41:24 -0700984 handleMotionDetectedLocked(mConstants.INACTIVE_TIMEOUT, "non_stationary");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700985 }
986 } else if (result == AnyMotionDetector.RESULT_STATIONARY) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700987 if (mState == STATE_SENSING) {
988 // If we are currently sensing, it is time to move to locating.
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700989 synchronized (this) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700990 mNotMoving = true;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800991 stepIdleStateLocked("s:stationary");
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700992 }
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700993 } else if (mState == STATE_LOCATING) {
994 // If we are currently locating, note that we are not moving and step
995 // if we have located the position.
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700996 synchronized (this) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700997 mNotMoving = true;
998 if (mLocated) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800999 stepIdleStateLocked("s:stationary");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001000 }
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001001 }
1002 }
1003 }
1004 }
1005
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001006 private static final int MSG_WRITE_CONFIG = 1;
1007 private static final int MSG_REPORT_IDLE_ON = 2;
1008 private static final int MSG_REPORT_IDLE_ON_LIGHT = 3;
1009 private static final int MSG_REPORT_IDLE_OFF = 4;
1010 private static final int MSG_REPORT_ACTIVE = 5;
1011 private static final int MSG_TEMP_APP_WHITELIST_TIMEOUT = 6;
1012 private static final int MSG_REPORT_MAINTENANCE_ACTIVITY = 7;
1013 private static final int MSG_FINISH_IDLE_OP = 8;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001014
1015 final class MyHandler extends Handler {
1016 MyHandler(Looper looper) {
1017 super(looper);
1018 }
1019
1020 @Override public void handleMessage(Message msg) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001021 if (DEBUG) Slog.d(TAG, "handleMessage(" + msg.what + ")");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001022 switch (msg.what) {
1023 case MSG_WRITE_CONFIG: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001024 // Does not hold a wakelock. Just let this happen whenever.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001025 handleWriteConfigFile();
1026 } break;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001027 case MSG_REPORT_IDLE_ON:
1028 case MSG_REPORT_IDLE_ON_LIGHT: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001029 // mGoingIdleWakeLock is held at this point
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001030 EventLogTags.writeDeviceIdleOnStart();
Dianne Hackbornb6843652016-02-22 12:20:13 -08001031 final boolean deepChanged;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001032 final boolean lightChanged;
1033 if (msg.what == MSG_REPORT_IDLE_ON) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001034 deepChanged = mLocalPowerManager.setDeviceIdleMode(true);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001035 lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
1036 } else {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001037 deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001038 lightChanged = mLocalPowerManager.setLightDeviceIdleMode(true);
1039 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001040 try {
1041 mNetworkPolicyManager.setDeviceIdleMode(true);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001042 mBatteryStats.noteDeviceIdleMode(msg.what == MSG_REPORT_IDLE_ON
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07001043 ? BatteryStats.DEVICE_IDLE_MODE_DEEP
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001044 : BatteryStats.DEVICE_IDLE_MODE_LIGHT, null, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001045 } catch (RemoteException e) {
1046 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001047 if (deepChanged) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001048 getContext().sendBroadcastAsUser(mIdleIntent, UserHandle.ALL);
1049 }
1050 if (lightChanged) {
1051 getContext().sendBroadcastAsUser(mLightIdleIntent, UserHandle.ALL);
1052 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001053 EventLogTags.writeDeviceIdleOnComplete();
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001054 mGoingIdleWakeLock.release();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001055 } break;
1056 case MSG_REPORT_IDLE_OFF: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001057 // mActiveIdleWakeLock is held at this point
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001058 EventLogTags.writeDeviceIdleOffStart("unknown");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001059 final boolean deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001060 final boolean lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001061 try {
1062 mNetworkPolicyManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001063 mBatteryStats.noteDeviceIdleMode(BatteryStats.DEVICE_IDLE_MODE_OFF,
1064 null, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001065 } catch (RemoteException e) {
1066 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001067 if (deepChanged) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001068 incActiveIdleOps();
1069 getContext().sendOrderedBroadcastAsUser(mIdleIntent, UserHandle.ALL,
1070 null, mIdleStartedDoneReceiver, null, 0, null, null);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001071 }
1072 if (lightChanged) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001073 incActiveIdleOps();
1074 getContext().sendOrderedBroadcastAsUser(mLightIdleIntent, UserHandle.ALL,
1075 null, mIdleStartedDoneReceiver, null, 0, null, null);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001076 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001077 // Always start with one active op for the message being sent here.
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001078 // Now we are done!
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001079 decActiveIdleOps();
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001080 EventLogTags.writeDeviceIdleOffComplete();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001081 } break;
1082 case MSG_REPORT_ACTIVE: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001083 // The device is awake at this point, so no wakelock necessary.
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001084 String activeReason = (String)msg.obj;
1085 int activeUid = msg.arg1;
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001086 EventLogTags.writeDeviceIdleOffStart(
1087 activeReason != null ? activeReason : "unknown");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001088 final boolean deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001089 final boolean lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001090 try {
1091 mNetworkPolicyManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001092 mBatteryStats.noteDeviceIdleMode(BatteryStats.DEVICE_IDLE_MODE_OFF,
1093 activeReason, activeUid);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001094 } catch (RemoteException e) {
1095 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001096 if (deepChanged) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001097 getContext().sendBroadcastAsUser(mIdleIntent, UserHandle.ALL);
1098 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001099 if (lightChanged) {
1100 getContext().sendBroadcastAsUser(mLightIdleIntent, UserHandle.ALL);
1101 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001102 EventLogTags.writeDeviceIdleOffComplete();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001103 } break;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001104 case MSG_TEMP_APP_WHITELIST_TIMEOUT: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001105 // TODO: What is keeping the device awake at this point? Does it need to be?
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001106 int uid = msg.arg1;
1107 checkTempAppWhitelistTimeout(uid);
1108 } break;
Yao Chenca5edbb2016-01-13 14:44:36 -08001109 case MSG_REPORT_MAINTENANCE_ACTIVITY: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001110 // TODO: What is keeping the device awake at this point? Does it need to be?
Yao Chenca5edbb2016-01-13 14:44:36 -08001111 boolean active = (msg.arg1 == 1);
1112 final int size = mMaintenanceActivityListeners.beginBroadcast();
1113 try {
1114 for (int i = 0; i < size; i++) {
1115 try {
1116 mMaintenanceActivityListeners.getBroadcastItem(i)
1117 .onMaintenanceActivityChanged(active);
1118 } catch (RemoteException ignored) {
1119 }
1120 }
1121 } finally {
1122 mMaintenanceActivityListeners.finishBroadcast();
1123 }
1124 } break;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001125 case MSG_FINISH_IDLE_OP: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001126 // mActiveIdleWakeLock is held at this point
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001127 decActiveIdleOps();
1128 } break;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001129 }
1130 }
1131 }
1132
1133 final MyHandler mHandler;
1134
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001135 BinderService mBinderService;
1136
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001137 private final class BinderService extends IDeviceIdleController.Stub {
1138 @Override public void addPowerSaveWhitelistApp(String name) {
1139 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1140 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001141 long ident = Binder.clearCallingIdentity();
1142 try {
1143 addPowerSaveWhitelistAppInternal(name);
1144 } finally {
1145 Binder.restoreCallingIdentity(ident);
1146 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001147 }
1148
1149 @Override public void removePowerSaveWhitelistApp(String name) {
1150 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1151 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001152 long ident = Binder.clearCallingIdentity();
1153 try {
1154 removePowerSaveWhitelistAppInternal(name);
1155 } finally {
1156 Binder.restoreCallingIdentity(ident);
1157 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001158 }
1159
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001160 @Override public String[] getSystemPowerWhitelistExceptIdle() {
1161 return getSystemPowerWhitelistExceptIdleInternal();
1162 }
1163
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001164 @Override public String[] getSystemPowerWhitelist() {
1165 return getSystemPowerWhitelistInternal();
1166 }
1167
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001168 @Override public String[] getUserPowerWhitelist() {
1169 return getUserPowerWhitelistInternal();
1170 }
1171
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001172 @Override public String[] getFullPowerWhitelistExceptIdle() {
1173 return getFullPowerWhitelistExceptIdleInternal();
1174 }
1175
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001176 @Override public String[] getFullPowerWhitelist() {
1177 return getFullPowerWhitelistInternal();
1178 }
1179
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001180 @Override public int[] getAppIdWhitelistExceptIdle() {
1181 return getAppIdWhitelistExceptIdleInternal();
1182 }
1183
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001184 @Override public int[] getAppIdWhitelist() {
1185 return getAppIdWhitelistInternal();
1186 }
1187
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001188 @Override public int[] getAppIdUserWhitelist() {
1189 return getAppIdUserWhitelistInternal();
1190 }
1191
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001192 @Override public int[] getAppIdTempWhitelist() {
1193 return getAppIdTempWhitelistInternal();
1194 }
1195
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001196 @Override public boolean isPowerSaveWhitelistExceptIdleApp(String name) {
1197 return isPowerSaveWhitelistExceptIdleAppInternal(name);
1198 }
1199
Amith Yamasani06bf8242015-05-08 16:36:21 -07001200 @Override public boolean isPowerSaveWhitelistApp(String name) {
1201 return isPowerSaveWhitelistAppInternal(name);
1202 }
1203
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001204 @Override public void addPowerSaveTempWhitelistApp(String packageName, long duration,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001205 int userId, String reason) throws RemoteException {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001206 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001207 }
1208
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001209 @Override public long addPowerSaveTempWhitelistAppForMms(String packageName,
1210 int userId, String reason) throws RemoteException {
1211 long duration = mConstants.MMS_TEMP_APP_WHITELIST_DURATION;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001212 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001213 return duration;
1214 }
1215
Dianne Hackborn451c3462015-07-21 17:39:46 -07001216 @Override public long addPowerSaveTempWhitelistAppForSms(String packageName,
1217 int userId, String reason) throws RemoteException {
1218 long duration = mConstants.SMS_TEMP_APP_WHITELIST_DURATION;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001219 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Dianne Hackborn451c3462015-07-21 17:39:46 -07001220 return duration;
1221 }
1222
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001223 @Override public void exitIdle(String reason) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001224 getContext().enforceCallingOrSelfPermission(Manifest.permission.DEVICE_POWER,
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001225 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001226 long ident = Binder.clearCallingIdentity();
1227 try {
1228 exitIdleInternal(reason);
1229 } finally {
1230 Binder.restoreCallingIdentity(ident);
1231 }
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001232 }
1233
Yao Chenca5edbb2016-01-13 14:44:36 -08001234 @Override public boolean registerMaintenanceActivityListener(
1235 IMaintenanceActivityListener listener) {
1236 return DeviceIdleController.this.registerMaintenanceActivityListener(listener);
1237 }
1238
1239 @Override public void unregisterMaintenanceActivityListener(
1240 IMaintenanceActivityListener listener) {
1241 DeviceIdleController.this.unregisterMaintenanceActivityListener(listener);
1242 }
1243
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001244 @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1245 DeviceIdleController.this.dump(fd, pw, args);
1246 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001247
1248 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07001249 FileDescriptor err, String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
1250 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001251 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001252 }
1253
Felipe Lemeef134662016-08-10 14:46:39 -07001254 public class LocalService {
Christopher Tatee0be7e82017-02-08 17:38:20 -08001255 // duration in milliseconds
1256 public void addPowerSaveTempWhitelistApp(int callingUid, String packageName,
1257 long duration, int userId, boolean sync, String reason) {
1258 addPowerSaveTempWhitelistAppInternal(callingUid, packageName, duration,
1259 userId, sync, reason);
1260 }
1261
1262 // duration in milliseconds
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001263 public void addPowerSaveTempWhitelistAppDirect(int appId, long duration, boolean sync,
1264 String reason) {
1265 addPowerSaveTempWhitelistAppDirectInternal(0, appId, duration, sync, reason);
1266 }
1267
Christopher Tatee0be7e82017-02-08 17:38:20 -08001268 // duration in milliseconds
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001269 public long getNotificationWhitelistDuration() {
1270 return mConstants.NOTIFICATION_WHITELIST_DURATION;
1271 }
1272
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001273 public void setNetworkPolicyTempWhitelistCallback(Runnable callback) {
1274 setNetworkPolicyTempWhitelistCallbackInternal(callback);
Dianne Hackborna750a632015-06-16 17:18:23 -07001275 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001276
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001277 public void setJobsActive(boolean active) {
1278 DeviceIdleController.this.setJobsActive(active);
1279 }
1280
1281 // Up-call from alarm manager.
1282 public void setAlarmsActive(boolean active) {
1283 DeviceIdleController.this.setAlarmsActive(active);
1284 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001285
Christopher Tate42a386b2016-11-07 12:21:21 -08001286 /** Is the app on any of the power save whitelists, whether system or user? */
1287 public boolean isAppOnWhitelist(int appid) {
1288 return DeviceIdleController.this.isAppOnWhitelistInternal(appid);
1289 }
1290
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001291 /**
1292 * Returns the array of app ids whitelisted by user. Take care not to
1293 * modify this, as it is a reference to the original copy. But the reference
1294 * can change when the list changes, so it needs to be re-acquired when
1295 * {@link PowerManager#ACTION_POWER_SAVE_WHITELIST_CHANGED} is sent.
1296 */
1297 public int[] getPowerSaveWhitelistUserAppIds() {
1298 return DeviceIdleController.this.getPowerSaveWhitelistUserAppIds();
1299 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001300 }
1301
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001302 public DeviceIdleController(Context context) {
1303 super(context);
1304 mConfigFile = new AtomicFile(new File(getSystemDir(), "deviceidle.xml"));
1305 mHandler = new MyHandler(BackgroundThread.getHandler().getLooper());
1306 }
1307
Christopher Tate42a386b2016-11-07 12:21:21 -08001308 boolean isAppOnWhitelistInternal(int appid) {
1309 synchronized (this) {
1310 return Arrays.binarySearch(mPowerSaveWhitelistAllAppIdArray, appid) >= 0;
1311 }
1312 }
1313
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001314 int[] getPowerSaveWhitelistUserAppIds() {
1315 synchronized (this) {
1316 return mPowerSaveWhitelistUserAppIdArray;
1317 }
1318 }
1319
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001320 private static File getSystemDir() {
1321 return new File(Environment.getDataDirectory(), "system");
1322 }
1323
1324 @Override
1325 public void onStart() {
1326 final PackageManager pm = getContext().getPackageManager();
1327
1328 synchronized (this) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001329 mLightEnabled = mDeepEnabled = getContext().getResources().getBoolean(
Dianne Hackborn92617032015-06-19 15:32:19 -07001330 com.android.internal.R.bool.config_enableAutoPowerModes);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001331 SystemConfig sysConfig = SystemConfig.getInstance();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001332 ArraySet<String> allowPowerExceptIdle = sysConfig.getAllowInPowerSaveExceptIdle();
1333 for (int i=0; i<allowPowerExceptIdle.size(); i++) {
1334 String pkg = allowPowerExceptIdle.valueAt(i);
1335 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001336 ApplicationInfo ai = pm.getApplicationInfo(pkg,
1337 PackageManager.MATCH_SYSTEM_ONLY);
1338 int appid = UserHandle.getAppId(ai.uid);
1339 mPowerSaveWhitelistAppsExceptIdle.put(ai.packageName, appid);
1340 mPowerSaveWhitelistSystemAppIdsExceptIdle.put(appid, true);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001341 } catch (PackageManager.NameNotFoundException e) {
1342 }
1343 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001344 ArraySet<String> allowPower = sysConfig.getAllowInPowerSave();
1345 for (int i=0; i<allowPower.size(); i++) {
1346 String pkg = allowPower.valueAt(i);
1347 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001348 ApplicationInfo ai = pm.getApplicationInfo(pkg,
1349 PackageManager.MATCH_SYSTEM_ONLY);
1350 int appid = UserHandle.getAppId(ai.uid);
1351 // These apps are on both the whitelist-except-idle as well
1352 // as the full whitelist, so they apply in all cases.
1353 mPowerSaveWhitelistAppsExceptIdle.put(ai.packageName, appid);
1354 mPowerSaveWhitelistSystemAppIdsExceptIdle.put(appid, true);
1355 mPowerSaveWhitelistApps.put(ai.packageName, appid);
1356 mPowerSaveWhitelistSystemAppIds.put(appid, true);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001357 } catch (PackageManager.NameNotFoundException e) {
1358 }
1359 }
1360
Adam Lesinski31c05d12015-06-09 17:34:04 -07001361 mConstants = new Constants(mHandler, getContext().getContentResolver());
1362
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001363 readConfigFileLocked();
1364 updateWhitelistAppIdsLocked();
1365
Dianne Hackborn88c41352016-04-07 15:18:58 -07001366 mNetworkConnected = true;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001367 mScreenOn = true;
1368 // Start out assuming we are charging. If we aren't, we will at least get
1369 // a battery update the next time the level drops.
1370 mCharging = true;
1371 mState = STATE_ACTIVE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001372 mLightState = LIGHT_STATE_ACTIVE;
Adam Lesinski31c05d12015-06-09 17:34:04 -07001373 mInactiveTimeout = mConstants.INACTIVE_TIMEOUT;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001374 }
1375
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001376 mBinderService = new BinderService();
1377 publishBinderService(Context.DEVICE_IDLE_CONTROLLER, mBinderService);
Dianne Hackborna750a632015-06-16 17:18:23 -07001378 publishLocalService(LocalService.class, new LocalService());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001379 }
1380
1381 @Override
1382 public void onBootPhase(int phase) {
1383 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1384 synchronized (this) {
1385 mAlarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
1386 mBatteryStats = BatteryStatsService.getService();
Dianne Hackborn85e35642017-01-12 15:10:57 -08001387 mLocalActivityManager = getLocalService(ActivityManagerInternal.class);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001388 mLocalPowerManager = getLocalService(PowerManagerInternal.class);
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001389 mPowerManager = getContext().getSystemService(PowerManager.class);
1390 mActiveIdleWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
1391 "deviceidle_maint");
1392 mActiveIdleWakeLock.setReferenceCounted(false);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001393 mGoingIdleWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
1394 "deviceidle_going_idle");
1395 mGoingIdleWakeLock.setReferenceCounted(true);
Dianne Hackborn88c41352016-04-07 15:18:58 -07001396 mConnectivityService = (ConnectivityService)ServiceManager.getService(
1397 Context.CONNECTIVITY_SERVICE);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001398 mLocalAlarmManager = getLocalService(AlarmManagerService.LocalService.class);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001399 mNetworkPolicyManager = INetworkPolicyManager.Stub.asInterface(
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001400 ServiceManager.getService(Context.NETWORK_POLICY_SERVICE));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001401 mDisplayManager = (DisplayManager) getContext().getSystemService(
1402 Context.DISPLAY_SERVICE);
1403 mSensorManager = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001404 int sigMotionSensorId = getContext().getResources().getInteger(
1405 com.android.internal.R.integer.config_autoPowerModeAnyMotionSensor);
1406 if (sigMotionSensorId > 0) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001407 mMotionSensor = mSensorManager.getDefaultSensor(sigMotionSensorId, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001408 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001409 if (mMotionSensor == null && getContext().getResources().getBoolean(
Joe LaPenna23d681b2015-08-27 15:12:11 -07001410 com.android.internal.R.bool.config_autoPowerModePreferWristTilt)) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001411 mMotionSensor = mSensorManager.getDefaultSensor(
1412 Sensor.TYPE_WRIST_TILT_GESTURE, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001413 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001414 if (mMotionSensor == null) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07001415 // As a last ditch, fall back to SMD.
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001416 mMotionSensor = mSensorManager.getDefaultSensor(
1417 Sensor.TYPE_SIGNIFICANT_MOTION, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001418 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001419
Joe LaPenna23d681b2015-08-27 15:12:11 -07001420 if (getContext().getResources().getBoolean(
1421 com.android.internal.R.bool.config_autoPowerModePrefetchLocation)) {
1422 mLocationManager = (LocationManager) getContext().getSystemService(
1423 Context.LOCATION_SERVICE);
1424 mLocationRequest = new LocationRequest()
1425 .setQuality(LocationRequest.ACCURACY_FINE)
1426 .setInterval(0)
1427 .setFastestInterval(0)
1428 .setNumUpdates(1);
1429 }
1430
1431 float angleThreshold = getContext().getResources().getInteger(
1432 com.android.internal.R.integer.config_autoPowerModeThresholdAngle) / 100f;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001433 mAnyMotionDetector = new AnyMotionDetector(
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001434 (PowerManager) getContext().getSystemService(Context.POWER_SERVICE),
Joe LaPenna23d681b2015-08-27 15:12:11 -07001435 mHandler, mSensorManager, this, angleThreshold);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001436
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001437 mIdleIntent = new Intent(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001438 mIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1439 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001440 mLightIdleIntent = new Intent(PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED);
1441 mLightIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1442 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001443
1444 IntentFilter filter = new IntentFilter();
1445 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001446 getContext().registerReceiver(mReceiver, filter);
Amith Yamasaniac59f75e2016-05-05 12:38:17 -07001447
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001448 filter = new IntentFilter();
1449 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1450 filter.addDataScheme("package");
Amith Yamasaniac59f75e2016-05-05 12:38:17 -07001451 getContext().registerReceiver(mReceiver, filter);
1452
Dianne Hackborn88c41352016-04-07 15:18:58 -07001453 filter = new IntentFilter();
1454 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001455 getContext().registerReceiver(mReceiver, filter);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001456
Dianne Hackborn85e35642017-01-12 15:10:57 -08001457 mLocalActivityManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001458 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001459 mLocalAlarmManager.setDeviceIdleUserWhitelist(mPowerSaveWhitelistUserAppIdArray);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001460 mDisplayManager.registerDisplayListener(mDisplayListener, null);
1461 updateDisplayLocked();
1462 }
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -07001463 updateConnectivityState(null);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001464 }
1465 }
1466
1467 public boolean addPowerSaveWhitelistAppInternal(String name) {
1468 synchronized (this) {
1469 try {
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001470 ApplicationInfo ai = getContext().getPackageManager().getApplicationInfo(name,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07001471 PackageManager.MATCH_ANY_USER);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001472 if (mPowerSaveWhitelistUserApps.put(name, UserHandle.getAppId(ai.uid)) == null) {
1473 reportPowerSaveWhitelistChangedLocked();
1474 updateWhitelistAppIdsLocked();
1475 writeConfigFileLocked();
1476 }
1477 return true;
1478 } catch (PackageManager.NameNotFoundException e) {
1479 return false;
1480 }
1481 }
1482 }
1483
1484 public boolean removePowerSaveWhitelistAppInternal(String name) {
1485 synchronized (this) {
1486 if (mPowerSaveWhitelistUserApps.remove(name) != null) {
1487 reportPowerSaveWhitelistChangedLocked();
1488 updateWhitelistAppIdsLocked();
1489 writeConfigFileLocked();
1490 return true;
1491 }
1492 }
1493 return false;
1494 }
1495
Felipe Lemef8a46232016-02-10 13:51:54 -08001496 public boolean getPowerSaveWhitelistAppInternal(String name) {
1497 synchronized (this) {
1498 return mPowerSaveWhitelistUserApps.containsKey(name);
1499 }
1500 }
1501
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001502 public String[] getSystemPowerWhitelistExceptIdleInternal() {
1503 synchronized (this) {
1504 int size = mPowerSaveWhitelistAppsExceptIdle.size();
1505 String[] apps = new String[size];
1506 for (int i = 0; i < size; i++) {
1507 apps[i] = mPowerSaveWhitelistAppsExceptIdle.keyAt(i);
1508 }
1509 return apps;
1510 }
1511 }
1512
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001513 public String[] getSystemPowerWhitelistInternal() {
1514 synchronized (this) {
1515 int size = mPowerSaveWhitelistApps.size();
1516 String[] apps = new String[size];
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001517 for (int i = 0; i < size; i++) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001518 apps[i] = mPowerSaveWhitelistApps.keyAt(i);
1519 }
1520 return apps;
1521 }
1522 }
1523
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001524 public String[] getUserPowerWhitelistInternal() {
1525 synchronized (this) {
1526 int size = mPowerSaveWhitelistUserApps.size();
1527 String[] apps = new String[size];
1528 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1529 apps[i] = mPowerSaveWhitelistUserApps.keyAt(i);
1530 }
1531 return apps;
1532 }
1533 }
1534
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001535 public String[] getFullPowerWhitelistExceptIdleInternal() {
1536 synchronized (this) {
1537 int size = mPowerSaveWhitelistAppsExceptIdle.size() + mPowerSaveWhitelistUserApps.size();
1538 String[] apps = new String[size];
1539 int cur = 0;
1540 for (int i = 0; i < mPowerSaveWhitelistAppsExceptIdle.size(); i++) {
1541 apps[cur] = mPowerSaveWhitelistAppsExceptIdle.keyAt(i);
1542 cur++;
1543 }
1544 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1545 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
1546 cur++;
1547 }
1548 return apps;
1549 }
1550 }
1551
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001552 public String[] getFullPowerWhitelistInternal() {
1553 synchronized (this) {
1554 int size = mPowerSaveWhitelistApps.size() + mPowerSaveWhitelistUserApps.size();
1555 String[] apps = new String[size];
1556 int cur = 0;
1557 for (int i = 0; i < mPowerSaveWhitelistApps.size(); i++) {
1558 apps[cur] = mPowerSaveWhitelistApps.keyAt(i);
1559 cur++;
1560 }
1561 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1562 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
1563 cur++;
1564 }
1565 return apps;
1566 }
1567 }
1568
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001569 public boolean isPowerSaveWhitelistExceptIdleAppInternal(String packageName) {
1570 synchronized (this) {
1571 return mPowerSaveWhitelistAppsExceptIdle.containsKey(packageName)
1572 || mPowerSaveWhitelistUserApps.containsKey(packageName);
1573 }
1574 }
1575
Amith Yamasani06bf8242015-05-08 16:36:21 -07001576 public boolean isPowerSaveWhitelistAppInternal(String packageName) {
1577 synchronized (this) {
1578 return mPowerSaveWhitelistApps.containsKey(packageName)
1579 || mPowerSaveWhitelistUserApps.containsKey(packageName);
1580 }
1581 }
1582
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001583 public int[] getAppIdWhitelistExceptIdleInternal() {
1584 synchronized (this) {
1585 return mPowerSaveWhitelistExceptIdleAppIdArray;
1586 }
1587 }
1588
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001589 public int[] getAppIdWhitelistInternal() {
1590 synchronized (this) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001591 return mPowerSaveWhitelistAllAppIdArray;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001592 }
1593 }
1594
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001595 public int[] getAppIdUserWhitelistInternal() {
1596 synchronized (this) {
1597 return mPowerSaveWhitelistUserAppIdArray;
1598 }
1599 }
1600
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001601 public int[] getAppIdTempWhitelistInternal() {
1602 synchronized (this) {
1603 return mTempWhitelistAppIdArray;
1604 }
1605 }
1606
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001607 void addPowerSaveTempWhitelistAppChecked(String packageName, long duration,
1608 int userId, String reason) throws RemoteException {
1609 getContext().enforceCallingPermission(
1610 Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
1611 "No permission to change device idle whitelist");
1612 final int callingUid = Binder.getCallingUid();
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001613 userId = ActivityManager.getService().handleIncomingUser(
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001614 Binder.getCallingPid(),
1615 callingUid,
1616 userId,
1617 /*allowAll=*/ false,
1618 /*requireFull=*/ false,
1619 "addPowerSaveTempWhitelistApp", null);
1620 final long token = Binder.clearCallingIdentity();
1621 try {
1622 addPowerSaveTempWhitelistAppInternal(callingUid,
1623 packageName, duration, userId, true, reason);
1624 } finally {
1625 Binder.restoreCallingIdentity(token);
1626 }
1627 }
1628
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001629 /**
1630 * Adds an app to the temporary whitelist and resets the endTime for granting the
1631 * app an exemption to access network and acquire wakelocks.
1632 */
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001633 void addPowerSaveTempWhitelistAppInternal(int callingUid, String packageName,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001634 long duration, int userId, boolean sync, String reason) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001635 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001636 int uid = getContext().getPackageManager().getPackageUidAsUser(packageName, userId);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001637 int appId = UserHandle.getAppId(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001638 addPowerSaveTempWhitelistAppDirectInternal(callingUid, appId, duration, sync, reason);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001639 } catch (NameNotFoundException e) {
1640 }
1641 }
1642
Dianne Hackborna750a632015-06-16 17:18:23 -07001643 /**
1644 * Adds an app to the temporary whitelist and resets the endTime for granting the
1645 * app an exemption to access network and acquire wakelocks.
1646 */
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001647 void addPowerSaveTempWhitelistAppDirectInternal(int callingUid, int appId,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001648 long duration, boolean sync, String reason) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001649 final long timeNow = SystemClock.elapsedRealtime();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001650 Runnable networkPolicyTempWhitelistCallback = null;
Dianne Hackborna750a632015-06-16 17:18:23 -07001651 synchronized (this) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001652 int callingAppId = UserHandle.getAppId(callingUid);
1653 if (callingAppId >= Process.FIRST_APPLICATION_UID) {
1654 if (!mPowerSaveWhitelistSystemAppIds.get(callingAppId)) {
1655 throw new SecurityException("Calling app " + UserHandle.formatUid(callingUid)
1656 + " is not on whitelist");
1657 }
1658 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001659 duration = Math.min(duration, mConstants.MAX_TEMP_APP_WHITELIST_DURATION);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001660 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.get(appId);
1661 final boolean newEntry = entry == null;
Dianne Hackborna750a632015-06-16 17:18:23 -07001662 // Set the new end time
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001663 if (newEntry) {
1664 entry = new Pair<>(new MutableLong(0), reason);
1665 mTempWhitelistAppIdEndTimes.put(appId, entry);
1666 }
1667 entry.first.value = timeNow + duration;
Dianne Hackborna750a632015-06-16 17:18:23 -07001668 if (DEBUG) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001669 Slog.d(TAG, "Adding AppId " + appId + " to temp whitelist. New entry: " + newEntry);
Dianne Hackborna750a632015-06-16 17:18:23 -07001670 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001671 if (newEntry) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001672 // No pending timeout for the app id, post a delayed message
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001673 try {
1674 mBatteryStats.noteEvent(BatteryStats.HistoryItem.EVENT_TEMP_WHITELIST_START,
1675 reason, appId);
1676 } catch (RemoteException e) {
1677 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001678 postTempActiveTimeoutMessage(appId, duration);
Dianne Hackborn85e35642017-01-12 15:10:57 -08001679 updateTempWhitelistAppIdsLocked(appId, true);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001680 if (mNetworkPolicyTempWhitelistCallback != null) {
1681 if (!sync) {
1682 mHandler.post(mNetworkPolicyTempWhitelistCallback);
1683 } else {
1684 networkPolicyTempWhitelistCallback = mNetworkPolicyTempWhitelistCallback;
1685 }
1686 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001687 reportTempWhitelistChangedLocked();
1688 }
1689 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001690 if (networkPolicyTempWhitelistCallback != null) {
1691 networkPolicyTempWhitelistCallback.run();
1692 }
1693 }
1694
1695 public void setNetworkPolicyTempWhitelistCallbackInternal(Runnable callback) {
1696 synchronized (this) {
1697 mNetworkPolicyTempWhitelistCallback = callback;
1698 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001699 }
1700
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001701 private void postTempActiveTimeoutMessage(int uid, long delay) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001702 if (DEBUG) {
1703 Slog.d(TAG, "postTempActiveTimeoutMessage: uid=" + uid + ", delay=" + delay);
1704 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001705 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_TEMP_APP_WHITELIST_TIMEOUT, uid, 0),
1706 delay);
1707 }
1708
1709 void checkTempAppWhitelistTimeout(int uid) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001710 final long timeNow = SystemClock.elapsedRealtime();
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001711 if (DEBUG) {
1712 Slog.d(TAG, "checkTempAppWhitelistTimeout: uid=" + uid + ", timeNow=" + timeNow);
1713 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001714 synchronized (this) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001715 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.get(uid);
1716 if (entry == null) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001717 // Nothing to do
1718 return;
1719 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001720 if (timeNow >= entry.first.value) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001721 mTempWhitelistAppIdEndTimes.delete(uid);
1722 if (DEBUG) {
1723 Slog.d(TAG, "Removing UID " + uid + " from temp whitelist");
1724 }
Dianne Hackborn85e35642017-01-12 15:10:57 -08001725 updateTempWhitelistAppIdsLocked(uid, false);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001726 if (mNetworkPolicyTempWhitelistCallback != null) {
1727 mHandler.post(mNetworkPolicyTempWhitelistCallback);
1728 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001729 reportTempWhitelistChangedLocked();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001730 try {
1731 mBatteryStats.noteEvent(BatteryStats.HistoryItem.EVENT_TEMP_WHITELIST_FINISH,
1732 entry.second, uid);
1733 } catch (RemoteException e) {
1734 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001735 } else {
1736 // Need more time
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001737 if (DEBUG) {
1738 Slog.d(TAG, "Time to remove UID " + uid + ": " + entry.first.value);
1739 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001740 postTempActiveTimeoutMessage(uid, entry.first.value - timeNow);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001741 }
1742 }
1743 }
1744
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001745 public void exitIdleInternal(String reason) {
1746 synchronized (this) {
1747 becomeActiveLocked(reason, Binder.getCallingUid());
1748 }
1749 }
1750
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -07001751 void updateConnectivityState(Intent connIntent) {
1752 ConnectivityService cm;
1753 synchronized (this) {
1754 cm = mConnectivityService;
1755 }
1756 if (cm == null) {
1757 return;
1758 }
1759 // Note: can't call out to ConnectivityService with our lock held.
1760 NetworkInfo ni = cm.getActiveNetworkInfo();
1761 synchronized (this) {
Dianne Hackborn88c41352016-04-07 15:18:58 -07001762 boolean conn;
1763 if (ni == null) {
1764 conn = false;
1765 } else {
1766 if (connIntent == null) {
1767 conn = ni.isConnected();
1768 } else {
1769 final int networkType =
1770 connIntent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1771 ConnectivityManager.TYPE_NONE);
1772 if (ni.getType() != networkType) {
1773 return;
1774 }
1775 conn = !connIntent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,
1776 false);
1777 }
1778 }
1779 if (conn != mNetworkConnected) {
1780 mNetworkConnected = conn;
1781 if (conn && mLightState == LIGHT_STATE_WAITING_FOR_NETWORK) {
1782 stepLightIdleStateLocked("network");
1783 }
1784 }
1785 }
1786 }
1787
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001788 void updateDisplayLocked() {
1789 mCurDisplay = mDisplayManager.getDisplay(Display.DEFAULT_DISPLAY);
1790 // We consider any situation where the display is showing something to be it on,
1791 // because if there is anything shown we are going to be updating it at some
1792 // frequency so can't be allowed to go into deep sleeps.
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001793 boolean screenOn = mCurDisplay.getState() == Display.STATE_ON;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001794 if (DEBUG) Slog.d(TAG, "updateDisplayLocked: screenOn=" + screenOn);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001795 if (!screenOn && mScreenOn) {
1796 mScreenOn = false;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001797 if (!mForceIdle) {
1798 becomeInactiveIfAppropriateLocked();
1799 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001800 } else if (screenOn) {
1801 mScreenOn = true;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001802 if (!mForceIdle) {
1803 becomeActiveLocked("screen", Process.myUid());
1804 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001805 }
1806 }
1807
1808 void updateChargingLocked(boolean charging) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001809 if (DEBUG) Slog.i(TAG, "updateChargingLocked: charging=" + charging);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001810 if (!charging && mCharging) {
1811 mCharging = false;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001812 if (!mForceIdle) {
1813 becomeInactiveIfAppropriateLocked();
1814 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001815 } else if (charging) {
1816 mCharging = charging;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001817 if (!mForceIdle) {
1818 becomeActiveLocked("charging", Process.myUid());
1819 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001820 }
1821 }
1822
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001823 void scheduleReportActiveLocked(String activeReason, int activeUid) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001824 Message msg = mHandler.obtainMessage(MSG_REPORT_ACTIVE, activeUid, 0, activeReason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001825 mHandler.sendMessage(msg);
1826 }
1827
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001828 void becomeActiveLocked(String activeReason, int activeUid) {
1829 if (DEBUG) Slog.i(TAG, "becomeActiveLocked, reason = " + activeReason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001830 if (mState != STATE_ACTIVE || mLightState != STATE_ACTIVE) {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001831 EventLogTags.writeDeviceIdle(STATE_ACTIVE, activeReason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001832 EventLogTags.writeDeviceIdleLight(LIGHT_STATE_ACTIVE, activeReason);
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001833 scheduleReportActiveLocked(activeReason, activeUid);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001834 mState = STATE_ACTIVE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001835 mLightState = LIGHT_STATE_ACTIVE;
Adam Lesinski31c05d12015-06-09 17:34:04 -07001836 mInactiveTimeout = mConstants.INACTIVE_TIMEOUT;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001837 mCurIdleBudget = 0;
1838 mMaintenanceStartTime = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001839 resetIdleManagementLocked();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001840 resetLightIdleManagementLocked();
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001841 addEvent(EVENT_NORMAL);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001842 }
1843 }
1844
1845 void becomeInactiveIfAppropriateLocked() {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001846 if (DEBUG) Slog.d(TAG, "becomeInactiveIfAppropriateLocked()");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001847 if ((!mScreenOn && !mCharging) || mForceIdle) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001848 // Screen has turned off; we are now going to become inactive and start
1849 // waiting to see if we will ultimately go idle.
Dianne Hackbornb6843652016-02-22 12:20:13 -08001850 if (mState == STATE_ACTIVE && mDeepEnabled) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001851 mState = STATE_INACTIVE;
1852 if (DEBUG) Slog.d(TAG, "Moved from STATE_ACTIVE to STATE_INACTIVE");
1853 resetIdleManagementLocked();
1854 scheduleAlarmLocked(mInactiveTimeout, false);
1855 EventLogTags.writeDeviceIdle(mState, "no activity");
1856 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001857 if (mLightState == LIGHT_STATE_ACTIVE && mLightEnabled) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001858 mLightState = LIGHT_STATE_INACTIVE;
1859 if (DEBUG) Slog.d(TAG, "Moved from LIGHT_STATE_ACTIVE to LIGHT_STATE_INACTIVE");
1860 resetLightIdleManagementLocked();
Dianne Hackborn953fc942016-03-29 15:36:24 -07001861 scheduleLightAlarmLocked(mConstants.LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001862 EventLogTags.writeDeviceIdleLight(mLightState, "no activity");
1863 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001864 }
1865 }
1866
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001867 void resetIdleManagementLocked() {
1868 mNextIdlePendingDelay = 0;
1869 mNextIdleDelay = 0;
Dianne Hackborn953fc942016-03-29 15:36:24 -07001870 mNextLightIdleDelay = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001871 cancelAlarmLocked();
Kevin Gabayan92f15e62016-04-04 17:52:22 -07001872 cancelSensingTimeoutAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001873 cancelLocatingLocked();
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001874 stopMonitoringMotionLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001875 mAnyMotionDetector.stop();
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001876 }
1877
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001878 void resetLightIdleManagementLocked() {
1879 cancelLightAlarmLocked();
1880 }
1881
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001882 void exitForceIdleLocked() {
1883 if (mForceIdle) {
1884 mForceIdle = false;
1885 if (mScreenOn || mCharging) {
Dianne Hackborn88c41352016-04-07 15:18:58 -07001886 becomeActiveLocked("exit-force", Process.myUid());
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001887 }
1888 }
1889 }
1890
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001891 void stepLightIdleStateLocked(String reason) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001892 if (mLightState == LIGHT_STATE_OVERRIDE) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001893 // If we are already in deep device idle mode, then
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001894 // there is nothing left to do for light mode.
1895 return;
1896 }
1897
1898 if (DEBUG) Slog.d(TAG, "stepLightIdleStateLocked: mLightState=" + mLightState);
1899 EventLogTags.writeDeviceIdleLightStep();
1900
1901 switch (mLightState) {
1902 case LIGHT_STATE_INACTIVE:
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001903 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
Dianne Hackborn953fc942016-03-29 15:36:24 -07001904 // Reset the upcoming idle delays.
1905 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001906 mMaintenanceStartTime = 0;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001907 if (!isOpsInactiveLocked()) {
1908 // We have some active ops going on... give them a chance to finish
1909 // before going in to our first idle.
1910 mLightState = LIGHT_STATE_PRE_IDLE;
1911 EventLogTags.writeDeviceIdleLight(mLightState, reason);
1912 scheduleLightAlarmLocked(mConstants.LIGHT_PRE_IDLE_TIMEOUT);
1913 break;
1914 }
1915 // Nothing active, fall through to immediately idle.
1916 case LIGHT_STATE_PRE_IDLE:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001917 case LIGHT_STATE_IDLE_MAINTENANCE:
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001918 if (mMaintenanceStartTime != 0) {
1919 long duration = SystemClock.elapsedRealtime() - mMaintenanceStartTime;
1920 if (duration < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
1921 // We didn't use up all of our minimum budget; add this to the reserve.
1922 mCurIdleBudget += (mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET-duration);
1923 } else {
1924 // We used more than our minimum budget; this comes out of the reserve.
1925 mCurIdleBudget -= (duration-mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET);
1926 }
1927 }
1928 mMaintenanceStartTime = 0;
Dianne Hackborn953fc942016-03-29 15:36:24 -07001929 scheduleLightAlarmLocked(mNextLightIdleDelay);
1930 mNextLightIdleDelay = Math.min(mConstants.LIGHT_MAX_IDLE_TIMEOUT,
1931 (long)(mNextLightIdleDelay * mConstants.LIGHT_IDLE_FACTOR));
1932 if (mNextLightIdleDelay < mConstants.LIGHT_IDLE_TIMEOUT) {
1933 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
1934 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001935 if (DEBUG) Slog.d(TAG, "Moved to LIGHT_STATE_IDLE.");
1936 mLightState = LIGHT_STATE_IDLE;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001937 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001938 addEvent(EVENT_LIGHT_IDLE);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001939 mGoingIdleWakeLock.acquire();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001940 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON_LIGHT);
1941 break;
1942 case LIGHT_STATE_IDLE:
Dianne Hackborn88c41352016-04-07 15:18:58 -07001943 case LIGHT_STATE_WAITING_FOR_NETWORK:
1944 if (mNetworkConnected || mLightState == LIGHT_STATE_WAITING_FOR_NETWORK) {
1945 // We have been idling long enough, now it is time to do some work.
1946 mActiveIdleOpCount = 1;
1947 mActiveIdleWakeLock.acquire();
1948 mMaintenanceStartTime = SystemClock.elapsedRealtime();
1949 if (mCurIdleBudget < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
1950 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
1951 } else if (mCurIdleBudget > mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET) {
1952 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET;
1953 }
1954 scheduleLightAlarmLocked(mCurIdleBudget);
1955 if (DEBUG) Slog.d(TAG,
1956 "Moved from LIGHT_STATE_IDLE to LIGHT_STATE_IDLE_MAINTENANCE.");
1957 mLightState = LIGHT_STATE_IDLE_MAINTENANCE;
1958 EventLogTags.writeDeviceIdleLight(mLightState, reason);
1959 addEvent(EVENT_LIGHT_MAINTENANCE);
1960 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
1961 } else {
1962 // We'd like to do maintenance, but currently don't have network
1963 // connectivity... let's try to wait until the network comes back.
1964 // We'll only wait for another full idle period, however, and then give up.
1965 scheduleLightAlarmLocked(mNextLightIdleDelay);
1966 if (DEBUG) Slog.d(TAG, "Moved to LIGHT_WAITING_FOR_NETWORK.");
1967 mLightState = LIGHT_STATE_WAITING_FOR_NETWORK;
1968 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001969 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001970 break;
1971 }
1972 }
1973
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001974 void stepIdleStateLocked(String reason) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001975 if (DEBUG) Slog.d(TAG, "stepIdleStateLocked: mState=" + mState);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001976 EventLogTags.writeDeviceIdleStep();
1977
1978 final long now = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07001979 if ((now+mConstants.MIN_TIME_TO_ALARM) > mAlarmManager.getNextWakeFromIdleTime()) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001980 // Whoops, there is an upcoming alarm. We don't actually want to go idle.
1981 if (mState != STATE_ACTIVE) {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001982 becomeActiveLocked("alarm", Process.myUid());
Koji Fukui27b33302015-12-16 19:43:01 +09001983 becomeInactiveIfAppropriateLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001984 }
1985 return;
1986 }
1987
1988 switch (mState) {
1989 case STATE_INACTIVE:
1990 // We have now been inactive long enough, it is time to start looking
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001991 // for motion and sleep some more while doing so.
1992 startMonitoringMotionLocked();
Adam Lesinski31c05d12015-06-09 17:34:04 -07001993 scheduleAlarmLocked(mConstants.IDLE_AFTER_INACTIVE_TIMEOUT, false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001994 // Reset the upcoming idle delays.
Adam Lesinski31c05d12015-06-09 17:34:04 -07001995 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
1996 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001997 mState = STATE_IDLE_PENDING;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001998 if (DEBUG) Slog.d(TAG, "Moved from STATE_INACTIVE to STATE_IDLE_PENDING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001999 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002000 break;
2001 case STATE_IDLE_PENDING:
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002002 mState = STATE_SENSING;
2003 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE_PENDING to STATE_SENSING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002004 EventLogTags.writeDeviceIdle(mState, reason);
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002005 scheduleSensingTimeoutAlarmLocked(mConstants.SENSING_TIMEOUT);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002006 cancelLocatingLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002007 mNotMoving = false;
2008 mLocated = false;
2009 mLastGenericLocation = null;
2010 mLastGpsLocation = null;
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002011 mAnyMotionDetector.checkForAnyMotion();
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002012 break;
2013 case STATE_SENSING:
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002014 cancelSensingTimeoutAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002015 mState = STATE_LOCATING;
2016 if (DEBUG) Slog.d(TAG, "Moved from STATE_SENSING to STATE_LOCATING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002017 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002018 scheduleAlarmLocked(mConstants.LOCATING_TIMEOUT, false);
Joe LaPenna23d681b2015-08-27 15:12:11 -07002019 if (mLocationManager != null
2020 && mLocationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
2021 mLocationManager.requestLocationUpdates(mLocationRequest,
2022 mGenericLocationListener, mHandler.getLooper());
2023 mLocating = true;
2024 } else {
2025 mHasNetworkLocation = false;
2026 }
2027 if (mLocationManager != null
2028 && mLocationManager.getProvider(LocationManager.GPS_PROVIDER) != null) {
2029 mHasGps = true;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002030 mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 5,
2031 mGpsLocationListener, mHandler.getLooper());
Joe LaPenna23d681b2015-08-27 15:12:11 -07002032 mLocating = true;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002033 } else {
Joe LaPenna23d681b2015-08-27 15:12:11 -07002034 mHasGps = false;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002035 }
Joe LaPenna23d681b2015-08-27 15:12:11 -07002036 // If we have a location provider, we're all set, the listeners will move state
2037 // forward.
2038 if (mLocating) {
2039 break;
2040 }
2041
2042 // Otherwise, we have to move from locating into idle maintenance.
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002043 case STATE_LOCATING:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002044 cancelAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002045 cancelLocatingLocked();
2046 mAnyMotionDetector.stop();
Dianne Hackborn953fc942016-03-29 15:36:24 -07002047
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002048 case STATE_IDLE_MAINTENANCE:
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002049 scheduleAlarmLocked(mNextIdleDelay, true);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002050 if (DEBUG) Slog.d(TAG, "Moved to STATE_IDLE. Next alarm in " + mNextIdleDelay +
2051 " ms.");
Adam Lesinski31c05d12015-06-09 17:34:04 -07002052 mNextIdleDelay = (long)(mNextIdleDelay * mConstants.IDLE_FACTOR);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002053 if (DEBUG) Slog.d(TAG, "Setting mNextIdleDelay = " + mNextIdleDelay);
Adam Lesinski31c05d12015-06-09 17:34:04 -07002054 mNextIdleDelay = Math.min(mNextIdleDelay, mConstants.MAX_IDLE_TIMEOUT);
Dianne Hackborn953fc942016-03-29 15:36:24 -07002055 if (mNextIdleDelay < mConstants.IDLE_TIMEOUT) {
2056 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
2057 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002058 mState = STATE_IDLE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002059 if (mLightState != LIGHT_STATE_OVERRIDE) {
2060 mLightState = LIGHT_STATE_OVERRIDE;
2061 cancelLightAlarmLocked();
2062 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002063 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackbornb6843652016-02-22 12:20:13 -08002064 addEvent(EVENT_DEEP_IDLE);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08002065 mGoingIdleWakeLock.acquire();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002066 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON);
2067 break;
2068 case STATE_IDLE:
2069 // We have been idling long enough, now it is time to do some work.
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002070 mActiveIdleOpCount = 1;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002071 mActiveIdleWakeLock.acquire();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002072 scheduleAlarmLocked(mNextIdlePendingDelay, false);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002073 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE to STATE_IDLE_MAINTENANCE. " +
2074 "Next alarm in " + mNextIdlePendingDelay + " ms.");
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002075 mMaintenanceStartTime = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07002076 mNextIdlePendingDelay = Math.min(mConstants.MAX_IDLE_PENDING_TIMEOUT,
2077 (long)(mNextIdlePendingDelay * mConstants.IDLE_PENDING_FACTOR));
Dianne Hackborn953fc942016-03-29 15:36:24 -07002078 if (mNextIdlePendingDelay < mConstants.IDLE_PENDING_TIMEOUT) {
2079 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
2080 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002081 mState = STATE_IDLE_MAINTENANCE;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002082 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackbornb6843652016-02-22 12:20:13 -08002083 addEvent(EVENT_DEEP_MAINTENANCE);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002084 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
2085 break;
2086 }
2087 }
2088
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002089 void incActiveIdleOps() {
2090 synchronized (this) {
2091 mActiveIdleOpCount++;
2092 }
2093 }
2094
2095 void decActiveIdleOps() {
2096 synchronized (this) {
2097 mActiveIdleOpCount--;
2098 if (mActiveIdleOpCount <= 0) {
2099 exitMaintenanceEarlyIfNeededLocked();
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002100 mActiveIdleWakeLock.release();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002101 }
2102 }
2103 }
2104
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002105 void setJobsActive(boolean active) {
2106 synchronized (this) {
2107 mJobsActive = active;
Yao Chenca5edbb2016-01-13 14:44:36 -08002108 reportMaintenanceActivityIfNeededLocked();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002109 if (!active) {
2110 exitMaintenanceEarlyIfNeededLocked();
2111 }
2112 }
2113 }
2114
2115 void setAlarmsActive(boolean active) {
2116 synchronized (this) {
2117 mAlarmsActive = active;
2118 if (!active) {
2119 exitMaintenanceEarlyIfNeededLocked();
2120 }
2121 }
2122 }
2123
Yao Chenca5edbb2016-01-13 14:44:36 -08002124 boolean registerMaintenanceActivityListener(IMaintenanceActivityListener listener) {
2125 synchronized (this) {
2126 mMaintenanceActivityListeners.register(listener);
2127 return mReportedMaintenanceActivity;
2128 }
2129 }
2130
2131 void unregisterMaintenanceActivityListener(IMaintenanceActivityListener listener) {
2132 synchronized (this) {
2133 mMaintenanceActivityListeners.unregister(listener);
2134 }
2135 }
2136
2137 void reportMaintenanceActivityIfNeededLocked() {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07002138 boolean active = mJobsActive;
Yao Chenca5edbb2016-01-13 14:44:36 -08002139 if (active == mReportedMaintenanceActivity) {
2140 return;
2141 }
2142 mReportedMaintenanceActivity = active;
2143 Message msg = mHandler.obtainMessage(MSG_REPORT_MAINTENANCE_ACTIVITY,
2144 mReportedMaintenanceActivity ? 1 : 0, 0);
2145 mHandler.sendMessage(msg);
2146 }
2147
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002148 boolean isOpsInactiveLocked() {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07002149 return mActiveIdleOpCount <= 0 && !mJobsActive && !mAlarmsActive;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002150 }
2151
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002152 void exitMaintenanceEarlyIfNeededLocked() {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002153 if (mState == STATE_IDLE_MAINTENANCE || mLightState == LIGHT_STATE_IDLE_MAINTENANCE
2154 || mLightState == LIGHT_STATE_PRE_IDLE) {
2155 if (isOpsInactiveLocked()) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002156 final long now = SystemClock.elapsedRealtime();
2157 if (DEBUG) {
2158 StringBuilder sb = new StringBuilder();
2159 sb.append("Exit: start=");
2160 TimeUtils.formatDuration(mMaintenanceStartTime, sb);
2161 sb.append(" now=");
2162 TimeUtils.formatDuration(now, sb);
2163 Slog.d(TAG, sb.toString());
2164 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002165 if (mState == STATE_IDLE_MAINTENANCE) {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002166 stepIdleStateLocked("s:early");
2167 } else if (mLightState == LIGHT_STATE_PRE_IDLE) {
2168 stepLightIdleStateLocked("s:predone");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002169 } else {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002170 stepLightIdleStateLocked("s:early");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002171 }
2172 }
2173 }
2174 }
2175
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002176 void motionLocked() {
2177 if (DEBUG) Slog.d(TAG, "motionLocked()");
2178 // The motion sensor will have been disabled at this point
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002179 handleMotionDetectedLocked(mConstants.MOTION_INACTIVE_TIMEOUT, "motion");
2180 }
2181
2182 void handleMotionDetectedLocked(long timeout, String type) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002183 // The device is not yet active, so we want to go back to the pending idle
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002184 // state to wait again for no motion. Note that we only monitor for motion
2185 // after moving out of the inactive state, so no need to worry about that.
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002186 boolean becomeInactive = false;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002187 if (mState != STATE_ACTIVE) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002188 scheduleReportActiveLocked(type, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002189 mState = STATE_ACTIVE;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002190 mInactiveTimeout = timeout;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002191 mCurIdleBudget = 0;
2192 mMaintenanceStartTime = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002193 EventLogTags.writeDeviceIdle(mState, type);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002194 addEvent(EVENT_NORMAL);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002195 becomeInactive = true;
2196 }
2197 if (mLightState == LIGHT_STATE_OVERRIDE) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002198 // We went out of light idle mode because we had started deep idle mode... let's
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002199 // now go back and reset things so we resume light idling if appropriate.
2200 mLightState = STATE_ACTIVE;
2201 EventLogTags.writeDeviceIdleLight(mLightState, type);
2202 becomeInactive = true;
2203 }
2204 if (becomeInactive) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002205 becomeInactiveIfAppropriateLocked();
2206 }
2207 }
2208
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002209 void receivedGenericLocationLocked(Location location) {
2210 if (mState != STATE_LOCATING) {
2211 cancelLocatingLocked();
2212 return;
2213 }
2214 if (DEBUG) Slog.d(TAG, "Generic location: " + location);
2215 mLastGenericLocation = new Location(location);
Joe LaPenna23d681b2015-08-27 15:12:11 -07002216 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY && mHasGps) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002217 return;
2218 }
2219 mLocated = true;
2220 if (mNotMoving) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002221 stepIdleStateLocked("s:location");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002222 }
2223 }
2224
2225 void receivedGpsLocationLocked(Location location) {
2226 if (mState != STATE_LOCATING) {
2227 cancelLocatingLocked();
2228 return;
2229 }
2230 if (DEBUG) Slog.d(TAG, "GPS location: " + location);
2231 mLastGpsLocation = new Location(location);
2232 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY) {
2233 return;
2234 }
2235 mLocated = true;
2236 if (mNotMoving) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002237 stepIdleStateLocked("s:gps");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002238 }
2239 }
2240
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002241 void startMonitoringMotionLocked() {
2242 if (DEBUG) Slog.d(TAG, "startMonitoringMotionLocked()");
2243 if (mMotionSensor != null && !mMotionListener.active) {
2244 mMotionListener.registerLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002245 }
2246 }
2247
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002248 void stopMonitoringMotionLocked() {
2249 if (DEBUG) Slog.d(TAG, "stopMonitoringMotionLocked()");
2250 if (mMotionSensor != null && mMotionListener.active) {
2251 mMotionListener.unregisterLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002252 }
2253 }
2254
2255 void cancelAlarmLocked() {
2256 if (mNextAlarmTime != 0) {
2257 mNextAlarmTime = 0;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002258 mAlarmManager.cancel(mDeepAlarmListener);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002259 }
2260 }
2261
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002262 void cancelLightAlarmLocked() {
2263 if (mNextLightAlarmTime != 0) {
2264 mNextLightAlarmTime = 0;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002265 mAlarmManager.cancel(mLightAlarmListener);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002266 }
2267 }
2268
2269 void cancelLocatingLocked() {
2270 if (mLocating) {
2271 mLocationManager.removeUpdates(mGenericLocationListener);
2272 mLocationManager.removeUpdates(mGpsLocationListener);
2273 mLocating = false;
2274 }
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002275 }
2276
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002277 void cancelSensingTimeoutAlarmLocked() {
2278 if (mNextSensingTimeoutAlarmTime != 0) {
2279 mNextSensingTimeoutAlarmTime = 0;
2280 mAlarmManager.cancel(mSensingTimeoutAlarmListener);
2281 }
2282 }
2283
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002284 void scheduleAlarmLocked(long delay, boolean idleUntil) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002285 if (DEBUG) Slog.d(TAG, "scheduleAlarmLocked(" + delay + ", " + idleUntil + ")");
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002286 if (mMotionSensor == null) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07002287 // If there is no motion sensor on this device, then we won't schedule
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002288 // alarms, because we can't determine if the device is not moving. This effectively
Joe LaPenna23d681b2015-08-27 15:12:11 -07002289 // turns off normal execution of device idling, although it is still possible to
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002290 // manually poke it by pretending like the alarm is going off.
2291 return;
2292 }
2293 mNextAlarmTime = SystemClock.elapsedRealtime() + delay;
2294 if (idleUntil) {
2295 mAlarmManager.setIdleUntil(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002296 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002297 } else {
2298 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002299 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002300 }
2301 }
2302
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002303 void scheduleLightAlarmLocked(long delay) {
2304 if (DEBUG) Slog.d(TAG, "scheduleLightAlarmLocked(" + delay + ")");
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002305 mNextLightAlarmTime = SystemClock.elapsedRealtime() + delay;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002306 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002307 mNextLightAlarmTime, "DeviceIdleController.light", mLightAlarmListener, mHandler);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002308 }
2309
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002310 void scheduleSensingTimeoutAlarmLocked(long delay) {
2311 if (DEBUG) Slog.d(TAG, "scheduleSensingAlarmLocked(" + delay + ")");
2312 mNextSensingTimeoutAlarmTime = SystemClock.elapsedRealtime() + delay;
2313 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, mNextSensingTimeoutAlarmTime,
2314 "DeviceIdleController.sensing", mSensingTimeoutAlarmListener, mHandler);
2315 }
2316
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002317 private static int[] buildAppIdArray(ArrayMap<String, Integer> systemApps,
2318 ArrayMap<String, Integer> userApps, SparseBooleanArray outAppIds) {
2319 outAppIds.clear();
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002320 if (systemApps != null) {
2321 for (int i = 0; i < systemApps.size(); i++) {
2322 outAppIds.put(systemApps.valueAt(i), true);
2323 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002324 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002325 if (userApps != null) {
2326 for (int i = 0; i < userApps.size(); i++) {
2327 outAppIds.put(userApps.valueAt(i), true);
2328 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002329 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002330 int size = outAppIds.size();
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002331 int[] appids = new int[size];
2332 for (int i = 0; i < size; i++) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002333 appids[i] = outAppIds.keyAt(i);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002334 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002335 return appids;
2336 }
2337
2338 private void updateWhitelistAppIdsLocked() {
2339 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(mPowerSaveWhitelistAppsExceptIdle,
2340 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistExceptIdleAppIds);
2341 mPowerSaveWhitelistAllAppIdArray = buildAppIdArray(mPowerSaveWhitelistApps,
2342 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistAllAppIds);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002343 mPowerSaveWhitelistUserAppIdArray = buildAppIdArray(null,
2344 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistUserAppIds);
Dianne Hackborn85e35642017-01-12 15:10:57 -08002345 if (mLocalActivityManager != null) {
2346 if (DEBUG) {
2347 Slog.d(TAG, "Setting activity manager whitelist to "
2348 + Arrays.toString(mPowerSaveWhitelistAllAppIdArray));
2349 }
2350 mLocalActivityManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
2351 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002352 if (mLocalPowerManager != null) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002353 if (DEBUG) {
2354 Slog.d(TAG, "Setting wakelock whitelist to "
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002355 + Arrays.toString(mPowerSaveWhitelistAllAppIdArray));
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002356 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002357 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002358 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002359 if (mLocalAlarmManager != null) {
2360 if (DEBUG) {
2361 Slog.d(TAG, "Setting alarm whitelist to "
2362 + Arrays.toString(mPowerSaveWhitelistUserAppIdArray));
2363 }
2364 mLocalAlarmManager.setDeviceIdleUserWhitelist(mPowerSaveWhitelistUserAppIdArray);
2365 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002366 }
2367
Dianne Hackborn85e35642017-01-12 15:10:57 -08002368 private void updateTempWhitelistAppIdsLocked(int appId, boolean adding) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002369 final int size = mTempWhitelistAppIdEndTimes.size();
2370 if (mTempWhitelistAppIdArray.length != size) {
2371 mTempWhitelistAppIdArray = new int[size];
2372 }
2373 for (int i = 0; i < size; i++) {
2374 mTempWhitelistAppIdArray[i] = mTempWhitelistAppIdEndTimes.keyAt(i);
2375 }
Dianne Hackborn85e35642017-01-12 15:10:57 -08002376 if (mLocalActivityManager != null) {
2377 if (DEBUG) {
2378 Slog.d(TAG, "Setting activity manager temp whitelist to "
2379 + Arrays.toString(mTempWhitelistAppIdArray));
2380 }
2381 mLocalActivityManager.updateDeviceIdleTempWhitelist(mTempWhitelistAppIdArray, appId,
2382 adding);
2383 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002384 if (mLocalPowerManager != null) {
2385 if (DEBUG) {
2386 Slog.d(TAG, "Setting wakelock temp whitelist to "
2387 + Arrays.toString(mTempWhitelistAppIdArray));
2388 }
2389 mLocalPowerManager.setDeviceIdleTempWhitelist(mTempWhitelistAppIdArray);
2390 }
2391 }
2392
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002393 private void reportPowerSaveWhitelistChangedLocked() {
2394 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
2395 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Xiaohui Chene4de5a02015-09-22 15:33:31 -07002396 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002397 }
2398
2399 private void reportTempWhitelistChangedLocked() {
2400 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_TEMP_WHITELIST_CHANGED);
2401 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Xiaohui Chene4de5a02015-09-22 15:33:31 -07002402 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002403 }
2404
2405 void readConfigFileLocked() {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002406 if (DEBUG) Slog.d(TAG, "Reading config from " + mConfigFile.getBaseFile());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002407 mPowerSaveWhitelistUserApps.clear();
2408 FileInputStream stream;
2409 try {
2410 stream = mConfigFile.openRead();
2411 } catch (FileNotFoundException e) {
2412 return;
2413 }
2414 try {
2415 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002416 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002417 readConfigFileLocked(parser);
2418 } catch (XmlPullParserException e) {
2419 } finally {
2420 try {
2421 stream.close();
2422 } catch (IOException e) {
2423 }
2424 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002425 }
2426
2427 private void readConfigFileLocked(XmlPullParser parser) {
2428 final PackageManager pm = getContext().getPackageManager();
2429
2430 try {
2431 int type;
2432 while ((type = parser.next()) != XmlPullParser.START_TAG
2433 && type != XmlPullParser.END_DOCUMENT) {
2434 ;
2435 }
2436
2437 if (type != XmlPullParser.START_TAG) {
2438 throw new IllegalStateException("no start tag found");
2439 }
2440
2441 int outerDepth = parser.getDepth();
2442 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2443 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2444 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2445 continue;
2446 }
2447
2448 String tagName = parser.getName();
2449 if (tagName.equals("wl")) {
2450 String name = parser.getAttributeValue(null, "n");
2451 if (name != null) {
2452 try {
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07002453 ApplicationInfo ai = pm.getApplicationInfo(name,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002454 PackageManager.MATCH_ANY_USER);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002455 mPowerSaveWhitelistUserApps.put(ai.packageName,
2456 UserHandle.getAppId(ai.uid));
2457 } catch (PackageManager.NameNotFoundException e) {
2458 }
2459 }
2460 } else {
2461 Slog.w(TAG, "Unknown element under <config>: "
2462 + parser.getName());
2463 XmlUtils.skipCurrentTag(parser);
2464 }
2465 }
2466
2467 } catch (IllegalStateException e) {
2468 Slog.w(TAG, "Failed parsing config " + e);
2469 } catch (NullPointerException e) {
2470 Slog.w(TAG, "Failed parsing config " + e);
2471 } catch (NumberFormatException e) {
2472 Slog.w(TAG, "Failed parsing config " + e);
2473 } catch (XmlPullParserException e) {
2474 Slog.w(TAG, "Failed parsing config " + e);
2475 } catch (IOException e) {
2476 Slog.w(TAG, "Failed parsing config " + e);
2477 } catch (IndexOutOfBoundsException e) {
2478 Slog.w(TAG, "Failed parsing config " + e);
2479 }
2480 }
2481
2482 void writeConfigFileLocked() {
2483 mHandler.removeMessages(MSG_WRITE_CONFIG);
2484 mHandler.sendEmptyMessageDelayed(MSG_WRITE_CONFIG, 5000);
2485 }
2486
2487 void handleWriteConfigFile() {
2488 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
2489
2490 try {
2491 synchronized (this) {
2492 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002493 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002494 writeConfigFileLocked(out);
2495 }
2496 } catch (IOException e) {
2497 }
2498
2499 synchronized (mConfigFile) {
2500 FileOutputStream stream = null;
2501 try {
2502 stream = mConfigFile.startWrite();
2503 memStream.writeTo(stream);
2504 stream.flush();
2505 FileUtils.sync(stream);
2506 stream.close();
2507 mConfigFile.finishWrite(stream);
2508 } catch (IOException e) {
2509 Slog.w(TAG, "Error writing config file", e);
2510 mConfigFile.failWrite(stream);
2511 }
2512 }
2513 }
2514
2515 void writeConfigFileLocked(XmlSerializer out) throws IOException {
2516 out.startDocument(null, true);
2517 out.startTag(null, "config");
2518 for (int i=0; i<mPowerSaveWhitelistUserApps.size(); i++) {
2519 String name = mPowerSaveWhitelistUserApps.keyAt(i);
2520 out.startTag(null, "wl");
2521 out.attribute(null, "n", name);
2522 out.endTag(null, "wl");
2523 }
2524 out.endTag(null, "config");
2525 out.endDocument();
2526 }
2527
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002528 static void dumpHelp(PrintWriter pw) {
2529 pw.println("Device idle controller (deviceidle) commands:");
2530 pw.println(" help");
2531 pw.println(" Print this help text.");
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002532 pw.println(" step [light|deep]");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002533 pw.println(" Immediately step to next state, without waiting for alarm.");
Dianne Hackborn88c41352016-04-07 15:18:58 -07002534 pw.println(" force-idle [light|deep]");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002535 pw.println(" Force directly into idle mode, regardless of other device state.");
Dianne Hackborn88c41352016-04-07 15:18:58 -07002536 pw.println(" force-inactive");
2537 pw.println(" Force to be inactive, ready to freely step idle states.");
2538 pw.println(" unforce");
2539 pw.println(" Resume normal functioning after force-idle or force-inactive.");
2540 pw.println(" get [light|deep|force|screen|charging|network]");
2541 pw.println(" Retrieve the current given state.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002542 pw.println(" disable [light|deep|all]");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002543 pw.println(" Completely disable device idle mode.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002544 pw.println(" enable [light|deep|all]");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002545 pw.println(" Re-enable device idle mode after it had previously been disabled.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002546 pw.println(" enabled [light|deep|all]");
Dianne Hackborn92617032015-06-19 15:32:19 -07002547 pw.println(" Print 1 if device idle mode is currently enabled, else 0.");
Dianne Hackborn1b139682015-07-06 15:13:37 -07002548 pw.println(" whitelist");
2549 pw.println(" Print currently whitelisted apps.");
Dianne Hackborn92617032015-06-19 15:32:19 -07002550 pw.println(" whitelist [package ...]");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002551 pw.println(" Add (prefix with +) or remove (prefix with -) packages.");
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002552 pw.println(" tempwhitelist");
2553 pw.println(" Print packages that are temporarily whitelisted.");
Dianne Hackborn85e35642017-01-12 15:10:57 -08002554 pw.println(" tempwhitelist [-u USER] [-d DURATION] [package ..]");
2555 pw.println(" Temporarily place packages in whitelist for DURATION milliseconds.");
2556 pw.println(" If no DURATION is specified, 10 seconds is used");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002557 }
2558
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002559 class Shell extends ShellCommand {
2560 int userId = UserHandle.USER_SYSTEM;
2561
2562 @Override
2563 public int onCommand(String cmd) {
2564 return onShellCommand(this, cmd);
2565 }
2566
2567 @Override
2568 public void onHelp() {
2569 PrintWriter pw = getOutPrintWriter();
2570 dumpHelp(pw);
2571 }
2572 }
2573
2574 int onShellCommand(Shell shell, String cmd) {
2575 PrintWriter pw = shell.getOutPrintWriter();
2576 if ("step".equals(cmd)) {
2577 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2578 null);
2579 synchronized (this) {
2580 long token = Binder.clearCallingIdentity();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002581 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002582 try {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002583 if (arg == null || "deep".equals(arg)) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002584 stepIdleStateLocked("s:shell");
2585 pw.print("Stepped to deep: ");
2586 pw.println(stateToString(mState));
2587 } else if ("light".equals(arg)) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002588 stepLightIdleStateLocked("s:shell");
2589 pw.print("Stepped to light: "); pw.println(lightStateToString(mLightState));
2590 } else {
2591 pw.println("Unknown idle mode: " + arg);
2592 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002593 } finally {
2594 Binder.restoreCallingIdentity(token);
2595 }
2596 }
2597 } else if ("force-idle".equals(cmd)) {
2598 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2599 null);
2600 synchronized (this) {
2601 long token = Binder.clearCallingIdentity();
Dianne Hackborn88c41352016-04-07 15:18:58 -07002602 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002603 try {
Dianne Hackborn88c41352016-04-07 15:18:58 -07002604 if (arg == null || "deep".equals(arg)) {
2605 if (!mDeepEnabled) {
2606 pw.println("Unable to go deep idle; not enabled");
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002607 return -1;
2608 }
Dianne Hackborn88c41352016-04-07 15:18:58 -07002609 mForceIdle = true;
2610 becomeInactiveIfAppropriateLocked();
2611 int curState = mState;
2612 while (curState != STATE_IDLE) {
2613 stepIdleStateLocked("s:shell");
2614 if (curState == mState) {
2615 pw.print("Unable to go deep idle; stopped at ");
2616 pw.println(stateToString(mState));
2617 exitForceIdleLocked();
2618 return -1;
2619 }
2620 curState = mState;
2621 }
2622 pw.println("Now forced in to deep idle mode");
2623 } else if ("light".equals(arg)) {
2624 mForceIdle = true;
2625 becomeInactiveIfAppropriateLocked();
2626 int curLightState = mLightState;
2627 while (curLightState != LIGHT_STATE_IDLE) {
2628 stepIdleStateLocked("s:shell");
2629 if (curLightState == mLightState) {
2630 pw.print("Unable to go light idle; stopped at ");
2631 pw.println(lightStateToString(mLightState));
2632 exitForceIdleLocked();
2633 return -1;
2634 }
2635 curLightState = mLightState;
2636 }
2637 pw.println("Now forced in to light idle mode");
2638 } else {
2639 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002640 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002641 } finally {
2642 Binder.restoreCallingIdentity(token);
2643 }
2644 }
Dianne Hackborn88c41352016-04-07 15:18:58 -07002645 } else if ("force-inactive".equals(cmd)) {
2646 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2647 null);
2648 synchronized (this) {
2649 long token = Binder.clearCallingIdentity();
2650 try {
2651 mForceIdle = true;
2652 becomeInactiveIfAppropriateLocked();
2653 pw.print("Light state: ");
2654 pw.print(lightStateToString(mLightState));
2655 pw.print(", deep state: ");
2656 pw.println(stateToString(mState));
2657 } finally {
2658 Binder.restoreCallingIdentity(token);
2659 }
2660 }
2661 } else if ("unforce".equals(cmd)) {
2662 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2663 null);
2664 synchronized (this) {
2665 long token = Binder.clearCallingIdentity();
2666 try {
2667 exitForceIdleLocked();
2668 pw.print("Light state: ");
2669 pw.print(lightStateToString(mLightState));
2670 pw.print(", deep state: ");
2671 pw.println(stateToString(mState));
2672 } finally {
2673 Binder.restoreCallingIdentity(token);
2674 }
2675 }
2676 } else if ("get".equals(cmd)) {
2677 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2678 null);
2679 synchronized (this) {
2680 String arg = shell.getNextArg();
2681 if (arg != null) {
2682 long token = Binder.clearCallingIdentity();
2683 try {
2684 switch (arg) {
2685 case "light": pw.println(lightStateToString(mLightState)); break;
2686 case "deep": pw.println(stateToString(mState)); break;
2687 case "force": pw.println(mForceIdle); break;
2688 case "screen": pw.println(mScreenOn); break;
2689 case "charging": pw.println(mCharging); break;
2690 case "network": pw.println(mNetworkConnected); break;
2691 default: pw.println("Unknown get option: " + arg); break;
2692 }
2693 } finally {
2694 Binder.restoreCallingIdentity(token);
2695 }
2696 } else {
2697 pw.println("Argument required");
2698 }
2699 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002700 } else if ("disable".equals(cmd)) {
2701 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2702 null);
2703 synchronized (this) {
2704 long token = Binder.clearCallingIdentity();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002705 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002706 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002707 boolean becomeActive = false;
2708 boolean valid = false;
2709 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
2710 valid = true;
2711 if (mDeepEnabled) {
2712 mDeepEnabled = false;
2713 becomeActive = true;
2714 pw.println("Deep idle mode disabled");
2715 }
2716 }
2717 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
2718 valid = true;
2719 if (mLightEnabled) {
2720 mLightEnabled = false;
2721 becomeActive = true;
2722 pw.println("Light idle mode disabled");
2723 }
2724 }
2725 if (becomeActive) {
2726 becomeActiveLocked((arg == null ? "all" : arg) + "-disabled",
2727 Process.myUid());
2728 }
2729 if (!valid) {
2730 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002731 }
2732 } finally {
2733 Binder.restoreCallingIdentity(token);
2734 }
2735 }
2736 } else if ("enable".equals(cmd)) {
2737 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2738 null);
2739 synchronized (this) {
2740 long token = Binder.clearCallingIdentity();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002741 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002742 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002743 boolean becomeInactive = false;
2744 boolean valid = false;
2745 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
2746 valid = true;
2747 if (!mDeepEnabled) {
2748 mDeepEnabled = true;
2749 becomeInactive = true;
2750 pw.println("Deep idle mode enabled");
2751 }
2752 }
2753 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
2754 valid = true;
2755 if (!mLightEnabled) {
2756 mLightEnabled = true;
2757 becomeInactive = true;
2758 pw.println("Light idle mode enable");
2759 }
2760 }
2761 if (becomeInactive) {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002762 becomeInactiveIfAppropriateLocked();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002763 }
2764 if (!valid) {
2765 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002766 }
2767 } finally {
2768 Binder.restoreCallingIdentity(token);
2769 }
2770 }
2771 } else if ("enabled".equals(cmd)) {
2772 synchronized (this) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002773 String arg = shell.getNextArg();
2774 if (arg == null || "all".equals(arg)) {
2775 pw.println(mDeepEnabled && mLightEnabled ? "1" : 0);
2776 } else if ("deep".equals(arg)) {
2777 pw.println(mDeepEnabled ? "1" : 0);
2778 } else if ("light".equals(arg)) {
2779 pw.println(mLightEnabled ? "1" : 0);
2780 } else {
2781 pw.println("Unknown idle mode: " + arg);
2782 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002783 }
2784 } else if ("whitelist".equals(cmd)) {
Dianne Hackborneb909e32016-09-29 14:35:15 -07002785 String arg = shell.getNextArg();
2786 if (arg != null) {
2787 getContext().enforceCallingOrSelfPermission(
2788 android.Manifest.permission.DEVICE_POWER, null);
2789 long token = Binder.clearCallingIdentity();
2790 try {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002791 do {
2792 if (arg.length() < 1 || (arg.charAt(0) != '-'
Felipe Lemef8a46232016-02-10 13:51:54 -08002793 && arg.charAt(0) != '+' && arg.charAt(0) != '=')) {
2794 pw.println("Package must be prefixed with +, -, or =: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002795 return -1;
2796 }
2797 char op = arg.charAt(0);
2798 String pkg = arg.substring(1);
2799 if (op == '+') {
2800 if (addPowerSaveWhitelistAppInternal(pkg)) {
2801 pw.println("Added: " + pkg);
2802 } else {
2803 pw.println("Unknown package: " + pkg);
2804 }
Felipe Lemef8a46232016-02-10 13:51:54 -08002805 } else if (op == '-') {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002806 if (removePowerSaveWhitelistAppInternal(pkg)) {
2807 pw.println("Removed: " + pkg);
2808 }
Felipe Lemef8a46232016-02-10 13:51:54 -08002809 } else {
2810 pw.println(getPowerSaveWhitelistAppInternal(pkg));
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002811 }
2812 } while ((arg=shell.getNextArg()) != null);
Dianne Hackborneb909e32016-09-29 14:35:15 -07002813 } finally {
2814 Binder.restoreCallingIdentity(token);
2815 }
2816 } else {
2817 synchronized (this) {
2818 for (int j=0; j<mPowerSaveWhitelistAppsExceptIdle.size(); j++) {
2819 pw.print("system-excidle,");
2820 pw.print(mPowerSaveWhitelistAppsExceptIdle.keyAt(j));
2821 pw.print(",");
2822 pw.println(mPowerSaveWhitelistAppsExceptIdle.valueAt(j));
2823 }
2824 for (int j=0; j<mPowerSaveWhitelistApps.size(); j++) {
2825 pw.print("system,");
2826 pw.print(mPowerSaveWhitelistApps.keyAt(j));
2827 pw.print(",");
2828 pw.println(mPowerSaveWhitelistApps.valueAt(j));
2829 }
2830 for (int j=0; j<mPowerSaveWhitelistUserApps.size(); j++) {
2831 pw.print("user,");
2832 pw.print(mPowerSaveWhitelistUserApps.keyAt(j));
2833 pw.print(",");
2834 pw.println(mPowerSaveWhitelistUserApps.valueAt(j));
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002835 }
2836 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002837 }
2838 } else if ("tempwhitelist".equals(cmd)) {
Dianne Hackborn85e35642017-01-12 15:10:57 -08002839 long duration = 10000;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002840 String opt;
2841 while ((opt=shell.getNextOption()) != null) {
2842 if ("-u".equals(opt)) {
2843 opt = shell.getNextArg();
2844 if (opt == null) {
2845 pw.println("-u requires a user number");
2846 return -1;
2847 }
2848 shell.userId = Integer.parseInt(opt);
Dianne Hackborn85e35642017-01-12 15:10:57 -08002849 } else if ("-d".equals(opt)) {
2850 opt = shell.getNextArg();
2851 if (opt == null) {
2852 pw.println("-d requires a duration");
2853 return -1;
2854 }
2855 duration = Long.parseLong(opt);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002856 }
2857 }
2858 String arg = shell.getNextArg();
2859 if (arg != null) {
2860 try {
Dianne Hackborn85e35642017-01-12 15:10:57 -08002861 addPowerSaveTempWhitelistAppChecked(arg, duration, shell.userId, "shell");
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002862 } catch (RemoteException re) {
2863 pw.println("Failed: " + re);
2864 }
2865 } else {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002866 dumpTempWhitelistSchedule(pw, false);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002867 }
2868 } else {
2869 return shell.handleDefaultCommands(cmd);
2870 }
2871 return 0;
2872 }
2873
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002874 void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2875 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2876 != PackageManager.PERMISSION_GRANTED) {
2877 pw.println("Permission Denial: can't dump DeviceIdleController from from pid="
2878 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2879 + " without permission " + android.Manifest.permission.DUMP);
2880 return;
2881 }
2882
2883 if (args != null) {
Xiaohui Chen7c696362015-09-16 09:56:14 -07002884 int userId = UserHandle.USER_SYSTEM;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002885 for (int i=0; i<args.length; i++) {
2886 String arg = args[i];
2887 if ("-h".equals(arg)) {
2888 dumpHelp(pw);
2889 return;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002890 } else if ("-u".equals(arg)) {
2891 i++;
2892 if (i < args.length) {
2893 arg = args[i];
2894 userId = Integer.parseInt(arg);
2895 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002896 } else if ("-a".equals(arg)) {
2897 // Ignore, we always dump all.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002898 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
2899 pw.println("Unknown option: " + arg);
2900 return;
2901 } else {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002902 Shell shell = new Shell();
2903 shell.userId = userId;
2904 String[] newArgs = new String[args.length-i];
2905 System.arraycopy(args, i, newArgs, 0, args.length-i);
Dianne Hackborn354736e2016-08-22 17:00:05 -07002906 shell.exec(mBinderService, null, fd, null, newArgs, null,
2907 new ResultReceiver(null));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002908 return;
2909 }
2910 }
2911 }
2912
2913 synchronized (this) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002914 mConstants.dump(pw);
2915
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002916 if (mEventCmds[0] != EVENT_NULL) {
2917 pw.println(" Idling history:");
2918 long now = SystemClock.elapsedRealtime();
2919 for (int i=EVENT_BUFFER_SIZE-1; i>=0; i--) {
2920 int cmd = mEventCmds[i];
2921 if (cmd == EVENT_NULL) {
2922 continue;
2923 }
2924 String label;
2925 switch (mEventCmds[i]) {
2926 case EVENT_NORMAL: label = " normal"; break;
2927 case EVENT_LIGHT_IDLE: label = " light-idle"; break;
2928 case EVENT_LIGHT_MAINTENANCE: label = "light-maint"; break;
Dianne Hackbornb6843652016-02-22 12:20:13 -08002929 case EVENT_DEEP_IDLE: label = " deep-idle"; break;
2930 case EVENT_DEEP_MAINTENANCE: label = " deep-maint"; break;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002931 default: label = " ??"; break;
2932 }
2933 pw.print(" ");
2934 pw.print(label);
2935 pw.print(": ");
2936 TimeUtils.formatDuration(mEventTimes[i], now, pw);;
2937 pw.println();
2938 }
2939 }
2940
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002941 int size = mPowerSaveWhitelistAppsExceptIdle.size();
2942 if (size > 0) {
2943 pw.println(" Whitelist (except idle) system apps:");
2944 for (int i = 0; i < size; i++) {
2945 pw.print(" ");
2946 pw.println(mPowerSaveWhitelistAppsExceptIdle.keyAt(i));
2947 }
2948 }
2949 size = mPowerSaveWhitelistApps.size();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002950 if (size > 0) {
2951 pw.println(" Whitelist system apps:");
2952 for (int i = 0; i < size; i++) {
2953 pw.print(" ");
2954 pw.println(mPowerSaveWhitelistApps.keyAt(i));
2955 }
2956 }
2957 size = mPowerSaveWhitelistUserApps.size();
2958 if (size > 0) {
2959 pw.println(" Whitelist user apps:");
2960 for (int i = 0; i < size; i++) {
2961 pw.print(" ");
2962 pw.println(mPowerSaveWhitelistUserApps.keyAt(i));
2963 }
2964 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002965 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2966 if (size > 0) {
2967 pw.println(" Whitelist (except idle) all app ids:");
2968 for (int i = 0; i < size; i++) {
2969 pw.print(" ");
2970 pw.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2971 pw.println();
2972 }
2973 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002974 size = mPowerSaveWhitelistUserAppIds.size();
2975 if (size > 0) {
2976 pw.println(" Whitelist user app ids:");
2977 for (int i = 0; i < size; i++) {
2978 pw.print(" ");
2979 pw.print(mPowerSaveWhitelistUserAppIds.keyAt(i));
2980 pw.println();
2981 }
2982 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002983 size = mPowerSaveWhitelistAllAppIds.size();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002984 if (size > 0) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002985 pw.println(" Whitelist all app ids:");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002986 for (int i = 0; i < size; i++) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002987 pw.print(" ");
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002988 pw.print(mPowerSaveWhitelistAllAppIds.keyAt(i));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002989 pw.println();
2990 }
2991 }
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002992 dumpTempWhitelistSchedule(pw, true);
2993
Dianne Hackborna750a632015-06-16 17:18:23 -07002994 size = mTempWhitelistAppIdArray != null ? mTempWhitelistAppIdArray.length : 0;
2995 if (size > 0) {
2996 pw.println(" Temp whitelist app ids:");
2997 for (int i = 0; i < size; i++) {
2998 pw.print(" ");
2999 pw.print(mTempWhitelistAppIdArray[i]);
3000 pw.println();
3001 }
3002 }
Adam Lesinski31c05d12015-06-09 17:34:04 -07003003
Dianne Hackbornb6843652016-02-22 12:20:13 -08003004 pw.print(" mLightEnabled="); pw.print(mLightEnabled);
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003005 pw.print(" mDeepEnabled="); pw.println(mDeepEnabled);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003006 pw.print(" mForceIdle="); pw.println(mForceIdle);
Nick Vaccaro20feaea2015-09-17 17:22:44 -07003007 pw.print(" mMotionSensor="); pw.println(mMotionSensor);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003008 pw.print(" mCurDisplay="); pw.println(mCurDisplay);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003009 pw.print(" mScreenOn="); pw.println(mScreenOn);
Dianne Hackborn88c41352016-04-07 15:18:58 -07003010 pw.print(" mNetworkConnected="); pw.println(mNetworkConnected);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003011 pw.print(" mCharging="); pw.println(mCharging);
Nick Vaccaro20feaea2015-09-17 17:22:44 -07003012 pw.print(" mMotionActive="); pw.println(mMotionListener.active);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003013 pw.print(" mNotMoving="); pw.println(mNotMoving);
Joe LaPenna23d681b2015-08-27 15:12:11 -07003014 pw.print(" mLocating="); pw.print(mLocating); pw.print(" mHasGps=");
3015 pw.print(mHasGps); pw.print(" mHasNetwork=");
3016 pw.print(mHasNetworkLocation); pw.print(" mLocated="); pw.println(mLocated);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07003017 if (mLastGenericLocation != null) {
3018 pw.print(" mLastGenericLocation="); pw.println(mLastGenericLocation);
3019 }
3020 if (mLastGpsLocation != null) {
3021 pw.print(" mLastGpsLocation="); pw.println(mLastGpsLocation);
3022 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003023 pw.print(" mState="); pw.print(stateToString(mState));
3024 pw.print(" mLightState=");
3025 pw.println(lightStateToString(mLightState));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003026 pw.print(" mInactiveTimeout="); TimeUtils.formatDuration(mInactiveTimeout, pw);
3027 pw.println();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003028 if (mActiveIdleOpCount != 0) {
3029 pw.print(" mActiveIdleOpCount="); pw.println(mActiveIdleOpCount);
3030 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003031 if (mNextAlarmTime != 0) {
3032 pw.print(" mNextAlarmTime=");
3033 TimeUtils.formatDuration(mNextAlarmTime, SystemClock.elapsedRealtime(), pw);
3034 pw.println();
3035 }
3036 if (mNextIdlePendingDelay != 0) {
3037 pw.print(" mNextIdlePendingDelay=");
3038 TimeUtils.formatDuration(mNextIdlePendingDelay, pw);
3039 pw.println();
3040 }
3041 if (mNextIdleDelay != 0) {
3042 pw.print(" mNextIdleDelay=");
3043 TimeUtils.formatDuration(mNextIdleDelay, pw);
3044 pw.println();
3045 }
Dianne Hackborn953fc942016-03-29 15:36:24 -07003046 if (mNextLightIdleDelay != 0) {
3047 pw.print(" mNextIdleDelay=");
3048 TimeUtils.formatDuration(mNextLightIdleDelay, pw);
3049 pw.println();
3050 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003051 if (mNextLightAlarmTime != 0) {
3052 pw.print(" mNextLightAlarmTime=");
3053 TimeUtils.formatDuration(mNextLightAlarmTime, SystemClock.elapsedRealtime(), pw);
3054 pw.println();
3055 }
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08003056 if (mCurIdleBudget != 0) {
3057 pw.print(" mCurIdleBudget=");
3058 TimeUtils.formatDuration(mCurIdleBudget, pw);
3059 pw.println();
3060 }
3061 if (mMaintenanceStartTime != 0) {
3062 pw.print(" mMaintenanceStartTime=");
3063 TimeUtils.formatDuration(mMaintenanceStartTime, SystemClock.elapsedRealtime(), pw);
3064 pw.println();
3065 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003066 if (mJobsActive) {
3067 pw.print(" mJobsActive="); pw.println(mJobsActive);
3068 }
3069 if (mAlarmsActive) {
3070 pw.print(" mAlarmsActive="); pw.println(mAlarmsActive);
3071 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003072 }
3073 }
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003074
3075 void dumpTempWhitelistSchedule(PrintWriter pw, boolean printTitle) {
3076 final int size = mTempWhitelistAppIdEndTimes.size();
3077 if (size > 0) {
3078 String prefix = "";
3079 if (printTitle) {
3080 pw.println(" Temp whitelist schedule:");
3081 prefix = " ";
3082 }
3083 final long timeNow = SystemClock.elapsedRealtime();
3084 for (int i = 0; i < size; i++) {
3085 pw.print(prefix);
3086 pw.print("UID=");
3087 pw.print(mTempWhitelistAppIdEndTimes.keyAt(i));
3088 pw.print(": ");
3089 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.valueAt(i);
3090 TimeUtils.formatDuration(entry.first.value, timeNow, pw);
3091 pw.print(" - ");
3092 pw.println(entry.second);
3093 }
3094 }
3095 }
3096 }