blob: 3e2dae55988c7db17b80443a3c7c04813ca17615 [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) {
Eugene Susla6a7006a2017-03-13 12:57:58 -07001139 if (DEBUG) {
1140 Slog.i(TAG, "addPowerSaveWhitelistApp(name = " + name + ")");
1141 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001142 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1143 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001144 long ident = Binder.clearCallingIdentity();
1145 try {
1146 addPowerSaveWhitelistAppInternal(name);
1147 } finally {
1148 Binder.restoreCallingIdentity(ident);
1149 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001150 }
1151
1152 @Override public void removePowerSaveWhitelistApp(String name) {
Eugene Susla6a7006a2017-03-13 12:57:58 -07001153 if (DEBUG) {
1154 Slog.i(TAG, "removePowerSaveWhitelistApp(name = " + name + ")");
1155 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001156 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1157 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001158 long ident = Binder.clearCallingIdentity();
1159 try {
1160 removePowerSaveWhitelistAppInternal(name);
1161 } finally {
1162 Binder.restoreCallingIdentity(ident);
1163 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001164 }
1165
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001166 @Override public String[] getSystemPowerWhitelistExceptIdle() {
1167 return getSystemPowerWhitelistExceptIdleInternal();
1168 }
1169
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001170 @Override public String[] getSystemPowerWhitelist() {
1171 return getSystemPowerWhitelistInternal();
1172 }
1173
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001174 @Override public String[] getUserPowerWhitelist() {
1175 return getUserPowerWhitelistInternal();
1176 }
1177
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001178 @Override public String[] getFullPowerWhitelistExceptIdle() {
1179 return getFullPowerWhitelistExceptIdleInternal();
1180 }
1181
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001182 @Override public String[] getFullPowerWhitelist() {
1183 return getFullPowerWhitelistInternal();
1184 }
1185
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001186 @Override public int[] getAppIdWhitelistExceptIdle() {
1187 return getAppIdWhitelistExceptIdleInternal();
1188 }
1189
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001190 @Override public int[] getAppIdWhitelist() {
1191 return getAppIdWhitelistInternal();
1192 }
1193
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001194 @Override public int[] getAppIdUserWhitelist() {
1195 return getAppIdUserWhitelistInternal();
1196 }
1197
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001198 @Override public int[] getAppIdTempWhitelist() {
1199 return getAppIdTempWhitelistInternal();
1200 }
1201
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001202 @Override public boolean isPowerSaveWhitelistExceptIdleApp(String name) {
1203 return isPowerSaveWhitelistExceptIdleAppInternal(name);
1204 }
1205
Amith Yamasani06bf8242015-05-08 16:36:21 -07001206 @Override public boolean isPowerSaveWhitelistApp(String name) {
1207 return isPowerSaveWhitelistAppInternal(name);
1208 }
1209
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001210 @Override public void addPowerSaveTempWhitelistApp(String packageName, long duration,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001211 int userId, String reason) throws RemoteException {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001212 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001213 }
1214
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001215 @Override public long addPowerSaveTempWhitelistAppForMms(String packageName,
1216 int userId, String reason) throws RemoteException {
1217 long duration = mConstants.MMS_TEMP_APP_WHITELIST_DURATION;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001218 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001219 return duration;
1220 }
1221
Dianne Hackborn451c3462015-07-21 17:39:46 -07001222 @Override public long addPowerSaveTempWhitelistAppForSms(String packageName,
1223 int userId, String reason) throws RemoteException {
1224 long duration = mConstants.SMS_TEMP_APP_WHITELIST_DURATION;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001225 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Dianne Hackborn451c3462015-07-21 17:39:46 -07001226 return duration;
1227 }
1228
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001229 @Override public void exitIdle(String reason) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001230 getContext().enforceCallingOrSelfPermission(Manifest.permission.DEVICE_POWER,
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001231 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001232 long ident = Binder.clearCallingIdentity();
1233 try {
1234 exitIdleInternal(reason);
1235 } finally {
1236 Binder.restoreCallingIdentity(ident);
1237 }
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001238 }
1239
Yao Chenca5edbb2016-01-13 14:44:36 -08001240 @Override public boolean registerMaintenanceActivityListener(
1241 IMaintenanceActivityListener listener) {
1242 return DeviceIdleController.this.registerMaintenanceActivityListener(listener);
1243 }
1244
1245 @Override public void unregisterMaintenanceActivityListener(
1246 IMaintenanceActivityListener listener) {
1247 DeviceIdleController.this.unregisterMaintenanceActivityListener(listener);
1248 }
1249
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001250 @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1251 DeviceIdleController.this.dump(fd, pw, args);
1252 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001253
1254 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07001255 FileDescriptor err, String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
1256 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001257 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001258 }
1259
Felipe Lemeef134662016-08-10 14:46:39 -07001260 public class LocalService {
Christopher Tatee0be7e82017-02-08 17:38:20 -08001261 // duration in milliseconds
1262 public void addPowerSaveTempWhitelistApp(int callingUid, String packageName,
1263 long duration, int userId, boolean sync, String reason) {
1264 addPowerSaveTempWhitelistAppInternal(callingUid, packageName, duration,
1265 userId, sync, reason);
1266 }
1267
1268 // duration in milliseconds
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001269 public void addPowerSaveTempWhitelistAppDirect(int appId, long duration, boolean sync,
1270 String reason) {
1271 addPowerSaveTempWhitelistAppDirectInternal(0, appId, duration, sync, reason);
1272 }
1273
Christopher Tatee0be7e82017-02-08 17:38:20 -08001274 // duration in milliseconds
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001275 public long getNotificationWhitelistDuration() {
1276 return mConstants.NOTIFICATION_WHITELIST_DURATION;
1277 }
1278
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001279 public void setNetworkPolicyTempWhitelistCallback(Runnable callback) {
1280 setNetworkPolicyTempWhitelistCallbackInternal(callback);
Dianne Hackborna750a632015-06-16 17:18:23 -07001281 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001282
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001283 public void setJobsActive(boolean active) {
1284 DeviceIdleController.this.setJobsActive(active);
1285 }
1286
1287 // Up-call from alarm manager.
1288 public void setAlarmsActive(boolean active) {
1289 DeviceIdleController.this.setAlarmsActive(active);
1290 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001291
Christopher Tate42a386b2016-11-07 12:21:21 -08001292 /** Is the app on any of the power save whitelists, whether system or user? */
1293 public boolean isAppOnWhitelist(int appid) {
1294 return DeviceIdleController.this.isAppOnWhitelistInternal(appid);
1295 }
1296
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001297 /**
1298 * Returns the array of app ids whitelisted by user. Take care not to
1299 * modify this, as it is a reference to the original copy. But the reference
1300 * can change when the list changes, so it needs to be re-acquired when
1301 * {@link PowerManager#ACTION_POWER_SAVE_WHITELIST_CHANGED} is sent.
1302 */
1303 public int[] getPowerSaveWhitelistUserAppIds() {
1304 return DeviceIdleController.this.getPowerSaveWhitelistUserAppIds();
1305 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001306 }
1307
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001308 public DeviceIdleController(Context context) {
1309 super(context);
1310 mConfigFile = new AtomicFile(new File(getSystemDir(), "deviceidle.xml"));
1311 mHandler = new MyHandler(BackgroundThread.getHandler().getLooper());
1312 }
1313
Christopher Tate42a386b2016-11-07 12:21:21 -08001314 boolean isAppOnWhitelistInternal(int appid) {
1315 synchronized (this) {
1316 return Arrays.binarySearch(mPowerSaveWhitelistAllAppIdArray, appid) >= 0;
1317 }
1318 }
1319
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001320 int[] getPowerSaveWhitelistUserAppIds() {
1321 synchronized (this) {
1322 return mPowerSaveWhitelistUserAppIdArray;
1323 }
1324 }
1325
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001326 private static File getSystemDir() {
1327 return new File(Environment.getDataDirectory(), "system");
1328 }
1329
1330 @Override
1331 public void onStart() {
1332 final PackageManager pm = getContext().getPackageManager();
1333
1334 synchronized (this) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001335 mLightEnabled = mDeepEnabled = getContext().getResources().getBoolean(
Dianne Hackborn92617032015-06-19 15:32:19 -07001336 com.android.internal.R.bool.config_enableAutoPowerModes);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001337 SystemConfig sysConfig = SystemConfig.getInstance();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001338 ArraySet<String> allowPowerExceptIdle = sysConfig.getAllowInPowerSaveExceptIdle();
1339 for (int i=0; i<allowPowerExceptIdle.size(); i++) {
1340 String pkg = allowPowerExceptIdle.valueAt(i);
1341 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001342 ApplicationInfo ai = pm.getApplicationInfo(pkg,
1343 PackageManager.MATCH_SYSTEM_ONLY);
1344 int appid = UserHandle.getAppId(ai.uid);
1345 mPowerSaveWhitelistAppsExceptIdle.put(ai.packageName, appid);
1346 mPowerSaveWhitelistSystemAppIdsExceptIdle.put(appid, true);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001347 } catch (PackageManager.NameNotFoundException e) {
1348 }
1349 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001350 ArraySet<String> allowPower = sysConfig.getAllowInPowerSave();
1351 for (int i=0; i<allowPower.size(); i++) {
1352 String pkg = allowPower.valueAt(i);
1353 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001354 ApplicationInfo ai = pm.getApplicationInfo(pkg,
1355 PackageManager.MATCH_SYSTEM_ONLY);
1356 int appid = UserHandle.getAppId(ai.uid);
1357 // These apps are on both the whitelist-except-idle as well
1358 // as the full whitelist, so they apply in all cases.
1359 mPowerSaveWhitelistAppsExceptIdle.put(ai.packageName, appid);
1360 mPowerSaveWhitelistSystemAppIdsExceptIdle.put(appid, true);
1361 mPowerSaveWhitelistApps.put(ai.packageName, appid);
1362 mPowerSaveWhitelistSystemAppIds.put(appid, true);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001363 } catch (PackageManager.NameNotFoundException e) {
1364 }
1365 }
1366
Adam Lesinski31c05d12015-06-09 17:34:04 -07001367 mConstants = new Constants(mHandler, getContext().getContentResolver());
1368
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001369 readConfigFileLocked();
1370 updateWhitelistAppIdsLocked();
1371
Dianne Hackborn88c41352016-04-07 15:18:58 -07001372 mNetworkConnected = true;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001373 mScreenOn = true;
1374 // Start out assuming we are charging. If we aren't, we will at least get
1375 // a battery update the next time the level drops.
1376 mCharging = true;
1377 mState = STATE_ACTIVE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001378 mLightState = LIGHT_STATE_ACTIVE;
Adam Lesinski31c05d12015-06-09 17:34:04 -07001379 mInactiveTimeout = mConstants.INACTIVE_TIMEOUT;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001380 }
1381
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001382 mBinderService = new BinderService();
1383 publishBinderService(Context.DEVICE_IDLE_CONTROLLER, mBinderService);
Dianne Hackborna750a632015-06-16 17:18:23 -07001384 publishLocalService(LocalService.class, new LocalService());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001385 }
1386
1387 @Override
1388 public void onBootPhase(int phase) {
1389 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1390 synchronized (this) {
1391 mAlarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
1392 mBatteryStats = BatteryStatsService.getService();
Dianne Hackborn85e35642017-01-12 15:10:57 -08001393 mLocalActivityManager = getLocalService(ActivityManagerInternal.class);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001394 mLocalPowerManager = getLocalService(PowerManagerInternal.class);
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001395 mPowerManager = getContext().getSystemService(PowerManager.class);
1396 mActiveIdleWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
1397 "deviceidle_maint");
1398 mActiveIdleWakeLock.setReferenceCounted(false);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001399 mGoingIdleWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
1400 "deviceidle_going_idle");
1401 mGoingIdleWakeLock.setReferenceCounted(true);
Dianne Hackborn88c41352016-04-07 15:18:58 -07001402 mConnectivityService = (ConnectivityService)ServiceManager.getService(
1403 Context.CONNECTIVITY_SERVICE);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001404 mLocalAlarmManager = getLocalService(AlarmManagerService.LocalService.class);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001405 mNetworkPolicyManager = INetworkPolicyManager.Stub.asInterface(
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001406 ServiceManager.getService(Context.NETWORK_POLICY_SERVICE));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001407 mDisplayManager = (DisplayManager) getContext().getSystemService(
1408 Context.DISPLAY_SERVICE);
1409 mSensorManager = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001410 int sigMotionSensorId = getContext().getResources().getInteger(
1411 com.android.internal.R.integer.config_autoPowerModeAnyMotionSensor);
1412 if (sigMotionSensorId > 0) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001413 mMotionSensor = mSensorManager.getDefaultSensor(sigMotionSensorId, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001414 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001415 if (mMotionSensor == null && getContext().getResources().getBoolean(
Joe LaPenna23d681b2015-08-27 15:12:11 -07001416 com.android.internal.R.bool.config_autoPowerModePreferWristTilt)) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001417 mMotionSensor = mSensorManager.getDefaultSensor(
1418 Sensor.TYPE_WRIST_TILT_GESTURE, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001419 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001420 if (mMotionSensor == null) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07001421 // As a last ditch, fall back to SMD.
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001422 mMotionSensor = mSensorManager.getDefaultSensor(
1423 Sensor.TYPE_SIGNIFICANT_MOTION, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001424 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001425
Joe LaPenna23d681b2015-08-27 15:12:11 -07001426 if (getContext().getResources().getBoolean(
1427 com.android.internal.R.bool.config_autoPowerModePrefetchLocation)) {
1428 mLocationManager = (LocationManager) getContext().getSystemService(
1429 Context.LOCATION_SERVICE);
1430 mLocationRequest = new LocationRequest()
1431 .setQuality(LocationRequest.ACCURACY_FINE)
1432 .setInterval(0)
1433 .setFastestInterval(0)
1434 .setNumUpdates(1);
1435 }
1436
1437 float angleThreshold = getContext().getResources().getInteger(
1438 com.android.internal.R.integer.config_autoPowerModeThresholdAngle) / 100f;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001439 mAnyMotionDetector = new AnyMotionDetector(
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001440 (PowerManager) getContext().getSystemService(Context.POWER_SERVICE),
Joe LaPenna23d681b2015-08-27 15:12:11 -07001441 mHandler, mSensorManager, this, angleThreshold);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001442
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001443 mIdleIntent = new Intent(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001444 mIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1445 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001446 mLightIdleIntent = new Intent(PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED);
1447 mLightIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1448 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001449
1450 IntentFilter filter = new IntentFilter();
1451 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001452 getContext().registerReceiver(mReceiver, filter);
Amith Yamasaniac59f75e2016-05-05 12:38:17 -07001453
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001454 filter = new IntentFilter();
1455 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1456 filter.addDataScheme("package");
Amith Yamasaniac59f75e2016-05-05 12:38:17 -07001457 getContext().registerReceiver(mReceiver, filter);
1458
Dianne Hackborn88c41352016-04-07 15:18:58 -07001459 filter = new IntentFilter();
1460 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001461 getContext().registerReceiver(mReceiver, filter);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001462
Dianne Hackborn85e35642017-01-12 15:10:57 -08001463 mLocalActivityManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001464 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001465 mLocalAlarmManager.setDeviceIdleUserWhitelist(mPowerSaveWhitelistUserAppIdArray);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001466 mDisplayManager.registerDisplayListener(mDisplayListener, null);
1467 updateDisplayLocked();
1468 }
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -07001469 updateConnectivityState(null);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001470 }
1471 }
1472
1473 public boolean addPowerSaveWhitelistAppInternal(String name) {
1474 synchronized (this) {
1475 try {
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001476 ApplicationInfo ai = getContext().getPackageManager().getApplicationInfo(name,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07001477 PackageManager.MATCH_ANY_USER);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001478 if (mPowerSaveWhitelistUserApps.put(name, UserHandle.getAppId(ai.uid)) == null) {
1479 reportPowerSaveWhitelistChangedLocked();
1480 updateWhitelistAppIdsLocked();
1481 writeConfigFileLocked();
1482 }
1483 return true;
1484 } catch (PackageManager.NameNotFoundException e) {
1485 return false;
1486 }
1487 }
1488 }
1489
1490 public boolean removePowerSaveWhitelistAppInternal(String name) {
1491 synchronized (this) {
1492 if (mPowerSaveWhitelistUserApps.remove(name) != null) {
1493 reportPowerSaveWhitelistChangedLocked();
1494 updateWhitelistAppIdsLocked();
1495 writeConfigFileLocked();
1496 return true;
1497 }
1498 }
1499 return false;
1500 }
1501
Felipe Lemef8a46232016-02-10 13:51:54 -08001502 public boolean getPowerSaveWhitelistAppInternal(String name) {
1503 synchronized (this) {
1504 return mPowerSaveWhitelistUserApps.containsKey(name);
1505 }
1506 }
1507
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001508 public String[] getSystemPowerWhitelistExceptIdleInternal() {
1509 synchronized (this) {
1510 int size = mPowerSaveWhitelistAppsExceptIdle.size();
1511 String[] apps = new String[size];
1512 for (int i = 0; i < size; i++) {
1513 apps[i] = mPowerSaveWhitelistAppsExceptIdle.keyAt(i);
1514 }
1515 return apps;
1516 }
1517 }
1518
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001519 public String[] getSystemPowerWhitelistInternal() {
1520 synchronized (this) {
1521 int size = mPowerSaveWhitelistApps.size();
1522 String[] apps = new String[size];
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001523 for (int i = 0; i < size; i++) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001524 apps[i] = mPowerSaveWhitelistApps.keyAt(i);
1525 }
1526 return apps;
1527 }
1528 }
1529
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001530 public String[] getUserPowerWhitelistInternal() {
1531 synchronized (this) {
1532 int size = mPowerSaveWhitelistUserApps.size();
1533 String[] apps = new String[size];
1534 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1535 apps[i] = mPowerSaveWhitelistUserApps.keyAt(i);
1536 }
1537 return apps;
1538 }
1539 }
1540
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001541 public String[] getFullPowerWhitelistExceptIdleInternal() {
1542 synchronized (this) {
1543 int size = mPowerSaveWhitelistAppsExceptIdle.size() + mPowerSaveWhitelistUserApps.size();
1544 String[] apps = new String[size];
1545 int cur = 0;
1546 for (int i = 0; i < mPowerSaveWhitelistAppsExceptIdle.size(); i++) {
1547 apps[cur] = mPowerSaveWhitelistAppsExceptIdle.keyAt(i);
1548 cur++;
1549 }
1550 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1551 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
1552 cur++;
1553 }
1554 return apps;
1555 }
1556 }
1557
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001558 public String[] getFullPowerWhitelistInternal() {
1559 synchronized (this) {
1560 int size = mPowerSaveWhitelistApps.size() + mPowerSaveWhitelistUserApps.size();
1561 String[] apps = new String[size];
1562 int cur = 0;
1563 for (int i = 0; i < mPowerSaveWhitelistApps.size(); i++) {
1564 apps[cur] = mPowerSaveWhitelistApps.keyAt(i);
1565 cur++;
1566 }
1567 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1568 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
1569 cur++;
1570 }
1571 return apps;
1572 }
1573 }
1574
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001575 public boolean isPowerSaveWhitelistExceptIdleAppInternal(String packageName) {
1576 synchronized (this) {
1577 return mPowerSaveWhitelistAppsExceptIdle.containsKey(packageName)
1578 || mPowerSaveWhitelistUserApps.containsKey(packageName);
1579 }
1580 }
1581
Amith Yamasani06bf8242015-05-08 16:36:21 -07001582 public boolean isPowerSaveWhitelistAppInternal(String packageName) {
1583 synchronized (this) {
1584 return mPowerSaveWhitelistApps.containsKey(packageName)
1585 || mPowerSaveWhitelistUserApps.containsKey(packageName);
1586 }
1587 }
1588
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001589 public int[] getAppIdWhitelistExceptIdleInternal() {
1590 synchronized (this) {
1591 return mPowerSaveWhitelistExceptIdleAppIdArray;
1592 }
1593 }
1594
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001595 public int[] getAppIdWhitelistInternal() {
1596 synchronized (this) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001597 return mPowerSaveWhitelistAllAppIdArray;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001598 }
1599 }
1600
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001601 public int[] getAppIdUserWhitelistInternal() {
1602 synchronized (this) {
1603 return mPowerSaveWhitelistUserAppIdArray;
1604 }
1605 }
1606
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001607 public int[] getAppIdTempWhitelistInternal() {
1608 synchronized (this) {
1609 return mTempWhitelistAppIdArray;
1610 }
1611 }
1612
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001613 void addPowerSaveTempWhitelistAppChecked(String packageName, long duration,
1614 int userId, String reason) throws RemoteException {
1615 getContext().enforceCallingPermission(
1616 Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
1617 "No permission to change device idle whitelist");
1618 final int callingUid = Binder.getCallingUid();
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001619 userId = ActivityManager.getService().handleIncomingUser(
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001620 Binder.getCallingPid(),
1621 callingUid,
1622 userId,
1623 /*allowAll=*/ false,
1624 /*requireFull=*/ false,
1625 "addPowerSaveTempWhitelistApp", null);
1626 final long token = Binder.clearCallingIdentity();
1627 try {
1628 addPowerSaveTempWhitelistAppInternal(callingUid,
1629 packageName, duration, userId, true, reason);
1630 } finally {
1631 Binder.restoreCallingIdentity(token);
1632 }
1633 }
1634
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001635 /**
1636 * Adds an app to the temporary whitelist and resets the endTime for granting the
1637 * app an exemption to access network and acquire wakelocks.
1638 */
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001639 void addPowerSaveTempWhitelistAppInternal(int callingUid, String packageName,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001640 long duration, int userId, boolean sync, String reason) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001641 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001642 int uid = getContext().getPackageManager().getPackageUidAsUser(packageName, userId);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001643 int appId = UserHandle.getAppId(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001644 addPowerSaveTempWhitelistAppDirectInternal(callingUid, appId, duration, sync, reason);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001645 } catch (NameNotFoundException e) {
1646 }
1647 }
1648
Dianne Hackborna750a632015-06-16 17:18:23 -07001649 /**
1650 * Adds an app to the temporary whitelist and resets the endTime for granting the
1651 * app an exemption to access network and acquire wakelocks.
1652 */
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001653 void addPowerSaveTempWhitelistAppDirectInternal(int callingUid, int appId,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001654 long duration, boolean sync, String reason) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001655 final long timeNow = SystemClock.elapsedRealtime();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001656 Runnable networkPolicyTempWhitelistCallback = null;
Dianne Hackborna750a632015-06-16 17:18:23 -07001657 synchronized (this) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001658 int callingAppId = UserHandle.getAppId(callingUid);
1659 if (callingAppId >= Process.FIRST_APPLICATION_UID) {
1660 if (!mPowerSaveWhitelistSystemAppIds.get(callingAppId)) {
1661 throw new SecurityException("Calling app " + UserHandle.formatUid(callingUid)
1662 + " is not on whitelist");
1663 }
1664 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001665 duration = Math.min(duration, mConstants.MAX_TEMP_APP_WHITELIST_DURATION);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001666 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.get(appId);
1667 final boolean newEntry = entry == null;
Dianne Hackborna750a632015-06-16 17:18:23 -07001668 // Set the new end time
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001669 if (newEntry) {
1670 entry = new Pair<>(new MutableLong(0), reason);
1671 mTempWhitelistAppIdEndTimes.put(appId, entry);
1672 }
1673 entry.first.value = timeNow + duration;
Dianne Hackborna750a632015-06-16 17:18:23 -07001674 if (DEBUG) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001675 Slog.d(TAG, "Adding AppId " + appId + " to temp whitelist. New entry: " + newEntry);
Dianne Hackborna750a632015-06-16 17:18:23 -07001676 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001677 if (newEntry) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001678 // No pending timeout for the app id, post a delayed message
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001679 try {
1680 mBatteryStats.noteEvent(BatteryStats.HistoryItem.EVENT_TEMP_WHITELIST_START,
1681 reason, appId);
1682 } catch (RemoteException e) {
1683 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001684 postTempActiveTimeoutMessage(appId, duration);
Dianne Hackborn85e35642017-01-12 15:10:57 -08001685 updateTempWhitelistAppIdsLocked(appId, true);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001686 if (mNetworkPolicyTempWhitelistCallback != null) {
1687 if (!sync) {
1688 mHandler.post(mNetworkPolicyTempWhitelistCallback);
1689 } else {
1690 networkPolicyTempWhitelistCallback = mNetworkPolicyTempWhitelistCallback;
1691 }
1692 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001693 reportTempWhitelistChangedLocked();
1694 }
1695 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001696 if (networkPolicyTempWhitelistCallback != null) {
1697 networkPolicyTempWhitelistCallback.run();
1698 }
1699 }
1700
1701 public void setNetworkPolicyTempWhitelistCallbackInternal(Runnable callback) {
1702 synchronized (this) {
1703 mNetworkPolicyTempWhitelistCallback = callback;
1704 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001705 }
1706
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001707 private void postTempActiveTimeoutMessage(int uid, long delay) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001708 if (DEBUG) {
1709 Slog.d(TAG, "postTempActiveTimeoutMessage: uid=" + uid + ", delay=" + delay);
1710 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001711 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_TEMP_APP_WHITELIST_TIMEOUT, uid, 0),
1712 delay);
1713 }
1714
1715 void checkTempAppWhitelistTimeout(int uid) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001716 final long timeNow = SystemClock.elapsedRealtime();
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001717 if (DEBUG) {
1718 Slog.d(TAG, "checkTempAppWhitelistTimeout: uid=" + uid + ", timeNow=" + timeNow);
1719 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001720 synchronized (this) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001721 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.get(uid);
1722 if (entry == null) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001723 // Nothing to do
1724 return;
1725 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001726 if (timeNow >= entry.first.value) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001727 mTempWhitelistAppIdEndTimes.delete(uid);
1728 if (DEBUG) {
1729 Slog.d(TAG, "Removing UID " + uid + " from temp whitelist");
1730 }
Dianne Hackborn85e35642017-01-12 15:10:57 -08001731 updateTempWhitelistAppIdsLocked(uid, false);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001732 if (mNetworkPolicyTempWhitelistCallback != null) {
1733 mHandler.post(mNetworkPolicyTempWhitelistCallback);
1734 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001735 reportTempWhitelistChangedLocked();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001736 try {
1737 mBatteryStats.noteEvent(BatteryStats.HistoryItem.EVENT_TEMP_WHITELIST_FINISH,
1738 entry.second, uid);
1739 } catch (RemoteException e) {
1740 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001741 } else {
1742 // Need more time
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001743 if (DEBUG) {
1744 Slog.d(TAG, "Time to remove UID " + uid + ": " + entry.first.value);
1745 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001746 postTempActiveTimeoutMessage(uid, entry.first.value - timeNow);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001747 }
1748 }
1749 }
1750
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001751 public void exitIdleInternal(String reason) {
1752 synchronized (this) {
1753 becomeActiveLocked(reason, Binder.getCallingUid());
1754 }
1755 }
1756
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -07001757 void updateConnectivityState(Intent connIntent) {
1758 ConnectivityService cm;
1759 synchronized (this) {
1760 cm = mConnectivityService;
1761 }
1762 if (cm == null) {
1763 return;
1764 }
1765 // Note: can't call out to ConnectivityService with our lock held.
1766 NetworkInfo ni = cm.getActiveNetworkInfo();
1767 synchronized (this) {
Dianne Hackborn88c41352016-04-07 15:18:58 -07001768 boolean conn;
1769 if (ni == null) {
1770 conn = false;
1771 } else {
1772 if (connIntent == null) {
1773 conn = ni.isConnected();
1774 } else {
1775 final int networkType =
1776 connIntent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1777 ConnectivityManager.TYPE_NONE);
1778 if (ni.getType() != networkType) {
1779 return;
1780 }
1781 conn = !connIntent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,
1782 false);
1783 }
1784 }
1785 if (conn != mNetworkConnected) {
1786 mNetworkConnected = conn;
1787 if (conn && mLightState == LIGHT_STATE_WAITING_FOR_NETWORK) {
1788 stepLightIdleStateLocked("network");
1789 }
1790 }
1791 }
1792 }
1793
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001794 void updateDisplayLocked() {
1795 mCurDisplay = mDisplayManager.getDisplay(Display.DEFAULT_DISPLAY);
1796 // We consider any situation where the display is showing something to be it on,
1797 // because if there is anything shown we are going to be updating it at some
1798 // frequency so can't be allowed to go into deep sleeps.
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001799 boolean screenOn = mCurDisplay.getState() == Display.STATE_ON;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001800 if (DEBUG) Slog.d(TAG, "updateDisplayLocked: screenOn=" + screenOn);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001801 if (!screenOn && mScreenOn) {
1802 mScreenOn = false;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001803 if (!mForceIdle) {
1804 becomeInactiveIfAppropriateLocked();
1805 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001806 } else if (screenOn) {
1807 mScreenOn = true;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001808 if (!mForceIdle) {
1809 becomeActiveLocked("screen", Process.myUid());
1810 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001811 }
1812 }
1813
1814 void updateChargingLocked(boolean charging) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001815 if (DEBUG) Slog.i(TAG, "updateChargingLocked: charging=" + charging);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001816 if (!charging && mCharging) {
1817 mCharging = false;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001818 if (!mForceIdle) {
1819 becomeInactiveIfAppropriateLocked();
1820 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001821 } else if (charging) {
1822 mCharging = charging;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001823 if (!mForceIdle) {
1824 becomeActiveLocked("charging", Process.myUid());
1825 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001826 }
1827 }
1828
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001829 void scheduleReportActiveLocked(String activeReason, int activeUid) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001830 Message msg = mHandler.obtainMessage(MSG_REPORT_ACTIVE, activeUid, 0, activeReason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001831 mHandler.sendMessage(msg);
1832 }
1833
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001834 void becomeActiveLocked(String activeReason, int activeUid) {
1835 if (DEBUG) Slog.i(TAG, "becomeActiveLocked, reason = " + activeReason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001836 if (mState != STATE_ACTIVE || mLightState != STATE_ACTIVE) {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001837 EventLogTags.writeDeviceIdle(STATE_ACTIVE, activeReason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001838 EventLogTags.writeDeviceIdleLight(LIGHT_STATE_ACTIVE, activeReason);
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001839 scheduleReportActiveLocked(activeReason, activeUid);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001840 mState = STATE_ACTIVE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001841 mLightState = LIGHT_STATE_ACTIVE;
Adam Lesinski31c05d12015-06-09 17:34:04 -07001842 mInactiveTimeout = mConstants.INACTIVE_TIMEOUT;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001843 mCurIdleBudget = 0;
1844 mMaintenanceStartTime = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001845 resetIdleManagementLocked();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001846 resetLightIdleManagementLocked();
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001847 addEvent(EVENT_NORMAL);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001848 }
1849 }
1850
1851 void becomeInactiveIfAppropriateLocked() {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001852 if (DEBUG) Slog.d(TAG, "becomeInactiveIfAppropriateLocked()");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001853 if ((!mScreenOn && !mCharging) || mForceIdle) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001854 // Screen has turned off; we are now going to become inactive and start
1855 // waiting to see if we will ultimately go idle.
Dianne Hackbornb6843652016-02-22 12:20:13 -08001856 if (mState == STATE_ACTIVE && mDeepEnabled) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001857 mState = STATE_INACTIVE;
1858 if (DEBUG) Slog.d(TAG, "Moved from STATE_ACTIVE to STATE_INACTIVE");
1859 resetIdleManagementLocked();
1860 scheduleAlarmLocked(mInactiveTimeout, false);
1861 EventLogTags.writeDeviceIdle(mState, "no activity");
1862 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001863 if (mLightState == LIGHT_STATE_ACTIVE && mLightEnabled) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001864 mLightState = LIGHT_STATE_INACTIVE;
1865 if (DEBUG) Slog.d(TAG, "Moved from LIGHT_STATE_ACTIVE to LIGHT_STATE_INACTIVE");
1866 resetLightIdleManagementLocked();
Dianne Hackborn953fc942016-03-29 15:36:24 -07001867 scheduleLightAlarmLocked(mConstants.LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001868 EventLogTags.writeDeviceIdleLight(mLightState, "no activity");
1869 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001870 }
1871 }
1872
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001873 void resetIdleManagementLocked() {
1874 mNextIdlePendingDelay = 0;
1875 mNextIdleDelay = 0;
Dianne Hackborn953fc942016-03-29 15:36:24 -07001876 mNextLightIdleDelay = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001877 cancelAlarmLocked();
Kevin Gabayan92f15e62016-04-04 17:52:22 -07001878 cancelSensingTimeoutAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001879 cancelLocatingLocked();
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001880 stopMonitoringMotionLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001881 mAnyMotionDetector.stop();
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001882 }
1883
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001884 void resetLightIdleManagementLocked() {
1885 cancelLightAlarmLocked();
1886 }
1887
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001888 void exitForceIdleLocked() {
1889 if (mForceIdle) {
1890 mForceIdle = false;
1891 if (mScreenOn || mCharging) {
Dianne Hackborn88c41352016-04-07 15:18:58 -07001892 becomeActiveLocked("exit-force", Process.myUid());
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001893 }
1894 }
1895 }
1896
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001897 void stepLightIdleStateLocked(String reason) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001898 if (mLightState == LIGHT_STATE_OVERRIDE) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001899 // If we are already in deep device idle mode, then
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001900 // there is nothing left to do for light mode.
1901 return;
1902 }
1903
1904 if (DEBUG) Slog.d(TAG, "stepLightIdleStateLocked: mLightState=" + mLightState);
1905 EventLogTags.writeDeviceIdleLightStep();
1906
1907 switch (mLightState) {
1908 case LIGHT_STATE_INACTIVE:
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001909 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
Dianne Hackborn953fc942016-03-29 15:36:24 -07001910 // Reset the upcoming idle delays.
1911 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001912 mMaintenanceStartTime = 0;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001913 if (!isOpsInactiveLocked()) {
1914 // We have some active ops going on... give them a chance to finish
1915 // before going in to our first idle.
1916 mLightState = LIGHT_STATE_PRE_IDLE;
1917 EventLogTags.writeDeviceIdleLight(mLightState, reason);
1918 scheduleLightAlarmLocked(mConstants.LIGHT_PRE_IDLE_TIMEOUT);
1919 break;
1920 }
1921 // Nothing active, fall through to immediately idle.
1922 case LIGHT_STATE_PRE_IDLE:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001923 case LIGHT_STATE_IDLE_MAINTENANCE:
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001924 if (mMaintenanceStartTime != 0) {
1925 long duration = SystemClock.elapsedRealtime() - mMaintenanceStartTime;
1926 if (duration < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
1927 // We didn't use up all of our minimum budget; add this to the reserve.
1928 mCurIdleBudget += (mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET-duration);
1929 } else {
1930 // We used more than our minimum budget; this comes out of the reserve.
1931 mCurIdleBudget -= (duration-mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET);
1932 }
1933 }
1934 mMaintenanceStartTime = 0;
Dianne Hackborn953fc942016-03-29 15:36:24 -07001935 scheduleLightAlarmLocked(mNextLightIdleDelay);
1936 mNextLightIdleDelay = Math.min(mConstants.LIGHT_MAX_IDLE_TIMEOUT,
1937 (long)(mNextLightIdleDelay * mConstants.LIGHT_IDLE_FACTOR));
1938 if (mNextLightIdleDelay < mConstants.LIGHT_IDLE_TIMEOUT) {
1939 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
1940 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001941 if (DEBUG) Slog.d(TAG, "Moved to LIGHT_STATE_IDLE.");
1942 mLightState = LIGHT_STATE_IDLE;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001943 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001944 addEvent(EVENT_LIGHT_IDLE);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001945 mGoingIdleWakeLock.acquire();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001946 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON_LIGHT);
1947 break;
1948 case LIGHT_STATE_IDLE:
Dianne Hackborn88c41352016-04-07 15:18:58 -07001949 case LIGHT_STATE_WAITING_FOR_NETWORK:
1950 if (mNetworkConnected || mLightState == LIGHT_STATE_WAITING_FOR_NETWORK) {
1951 // We have been idling long enough, now it is time to do some work.
1952 mActiveIdleOpCount = 1;
1953 mActiveIdleWakeLock.acquire();
1954 mMaintenanceStartTime = SystemClock.elapsedRealtime();
1955 if (mCurIdleBudget < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
1956 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
1957 } else if (mCurIdleBudget > mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET) {
1958 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET;
1959 }
1960 scheduleLightAlarmLocked(mCurIdleBudget);
1961 if (DEBUG) Slog.d(TAG,
1962 "Moved from LIGHT_STATE_IDLE to LIGHT_STATE_IDLE_MAINTENANCE.");
1963 mLightState = LIGHT_STATE_IDLE_MAINTENANCE;
1964 EventLogTags.writeDeviceIdleLight(mLightState, reason);
1965 addEvent(EVENT_LIGHT_MAINTENANCE);
1966 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
1967 } else {
1968 // We'd like to do maintenance, but currently don't have network
1969 // connectivity... let's try to wait until the network comes back.
1970 // We'll only wait for another full idle period, however, and then give up.
1971 scheduleLightAlarmLocked(mNextLightIdleDelay);
1972 if (DEBUG) Slog.d(TAG, "Moved to LIGHT_WAITING_FOR_NETWORK.");
1973 mLightState = LIGHT_STATE_WAITING_FOR_NETWORK;
1974 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001975 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001976 break;
1977 }
1978 }
1979
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001980 void stepIdleStateLocked(String reason) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001981 if (DEBUG) Slog.d(TAG, "stepIdleStateLocked: mState=" + mState);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001982 EventLogTags.writeDeviceIdleStep();
1983
1984 final long now = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07001985 if ((now+mConstants.MIN_TIME_TO_ALARM) > mAlarmManager.getNextWakeFromIdleTime()) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001986 // Whoops, there is an upcoming alarm. We don't actually want to go idle.
1987 if (mState != STATE_ACTIVE) {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001988 becomeActiveLocked("alarm", Process.myUid());
Koji Fukui27b33302015-12-16 19:43:01 +09001989 becomeInactiveIfAppropriateLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001990 }
1991 return;
1992 }
1993
1994 switch (mState) {
1995 case STATE_INACTIVE:
1996 // We have now been inactive long enough, it is time to start looking
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001997 // for motion and sleep some more while doing so.
1998 startMonitoringMotionLocked();
Adam Lesinski31c05d12015-06-09 17:34:04 -07001999 scheduleAlarmLocked(mConstants.IDLE_AFTER_INACTIVE_TIMEOUT, false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002000 // Reset the upcoming idle delays.
Adam Lesinski31c05d12015-06-09 17:34:04 -07002001 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
2002 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002003 mState = STATE_IDLE_PENDING;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002004 if (DEBUG) Slog.d(TAG, "Moved from STATE_INACTIVE to STATE_IDLE_PENDING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002005 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002006 break;
2007 case STATE_IDLE_PENDING:
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002008 mState = STATE_SENSING;
2009 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE_PENDING to STATE_SENSING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002010 EventLogTags.writeDeviceIdle(mState, reason);
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002011 scheduleSensingTimeoutAlarmLocked(mConstants.SENSING_TIMEOUT);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002012 cancelLocatingLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002013 mNotMoving = false;
2014 mLocated = false;
2015 mLastGenericLocation = null;
2016 mLastGpsLocation = null;
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002017 mAnyMotionDetector.checkForAnyMotion();
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002018 break;
2019 case STATE_SENSING:
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002020 cancelSensingTimeoutAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002021 mState = STATE_LOCATING;
2022 if (DEBUG) Slog.d(TAG, "Moved from STATE_SENSING to STATE_LOCATING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002023 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002024 scheduleAlarmLocked(mConstants.LOCATING_TIMEOUT, false);
Joe LaPenna23d681b2015-08-27 15:12:11 -07002025 if (mLocationManager != null
2026 && mLocationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
2027 mLocationManager.requestLocationUpdates(mLocationRequest,
2028 mGenericLocationListener, mHandler.getLooper());
2029 mLocating = true;
2030 } else {
2031 mHasNetworkLocation = false;
2032 }
2033 if (mLocationManager != null
2034 && mLocationManager.getProvider(LocationManager.GPS_PROVIDER) != null) {
2035 mHasGps = true;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002036 mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 5,
2037 mGpsLocationListener, mHandler.getLooper());
Joe LaPenna23d681b2015-08-27 15:12:11 -07002038 mLocating = true;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002039 } else {
Joe LaPenna23d681b2015-08-27 15:12:11 -07002040 mHasGps = false;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002041 }
Joe LaPenna23d681b2015-08-27 15:12:11 -07002042 // If we have a location provider, we're all set, the listeners will move state
2043 // forward.
2044 if (mLocating) {
2045 break;
2046 }
2047
2048 // Otherwise, we have to move from locating into idle maintenance.
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002049 case STATE_LOCATING:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002050 cancelAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002051 cancelLocatingLocked();
2052 mAnyMotionDetector.stop();
Dianne Hackborn953fc942016-03-29 15:36:24 -07002053
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002054 case STATE_IDLE_MAINTENANCE:
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002055 scheduleAlarmLocked(mNextIdleDelay, true);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002056 if (DEBUG) Slog.d(TAG, "Moved to STATE_IDLE. Next alarm in " + mNextIdleDelay +
2057 " ms.");
Adam Lesinski31c05d12015-06-09 17:34:04 -07002058 mNextIdleDelay = (long)(mNextIdleDelay * mConstants.IDLE_FACTOR);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002059 if (DEBUG) Slog.d(TAG, "Setting mNextIdleDelay = " + mNextIdleDelay);
Adam Lesinski31c05d12015-06-09 17:34:04 -07002060 mNextIdleDelay = Math.min(mNextIdleDelay, mConstants.MAX_IDLE_TIMEOUT);
Dianne Hackborn953fc942016-03-29 15:36:24 -07002061 if (mNextIdleDelay < mConstants.IDLE_TIMEOUT) {
2062 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
2063 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002064 mState = STATE_IDLE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002065 if (mLightState != LIGHT_STATE_OVERRIDE) {
2066 mLightState = LIGHT_STATE_OVERRIDE;
2067 cancelLightAlarmLocked();
2068 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002069 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackbornb6843652016-02-22 12:20:13 -08002070 addEvent(EVENT_DEEP_IDLE);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08002071 mGoingIdleWakeLock.acquire();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002072 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON);
2073 break;
2074 case STATE_IDLE:
2075 // We have been idling long enough, now it is time to do some work.
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002076 mActiveIdleOpCount = 1;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002077 mActiveIdleWakeLock.acquire();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002078 scheduleAlarmLocked(mNextIdlePendingDelay, false);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002079 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE to STATE_IDLE_MAINTENANCE. " +
2080 "Next alarm in " + mNextIdlePendingDelay + " ms.");
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002081 mMaintenanceStartTime = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07002082 mNextIdlePendingDelay = Math.min(mConstants.MAX_IDLE_PENDING_TIMEOUT,
2083 (long)(mNextIdlePendingDelay * mConstants.IDLE_PENDING_FACTOR));
Dianne Hackborn953fc942016-03-29 15:36:24 -07002084 if (mNextIdlePendingDelay < mConstants.IDLE_PENDING_TIMEOUT) {
2085 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
2086 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002087 mState = STATE_IDLE_MAINTENANCE;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002088 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackbornb6843652016-02-22 12:20:13 -08002089 addEvent(EVENT_DEEP_MAINTENANCE);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002090 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
2091 break;
2092 }
2093 }
2094
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002095 void incActiveIdleOps() {
2096 synchronized (this) {
2097 mActiveIdleOpCount++;
2098 }
2099 }
2100
2101 void decActiveIdleOps() {
2102 synchronized (this) {
2103 mActiveIdleOpCount--;
2104 if (mActiveIdleOpCount <= 0) {
2105 exitMaintenanceEarlyIfNeededLocked();
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002106 mActiveIdleWakeLock.release();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002107 }
2108 }
2109 }
2110
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002111 void setJobsActive(boolean active) {
2112 synchronized (this) {
2113 mJobsActive = active;
Yao Chenca5edbb2016-01-13 14:44:36 -08002114 reportMaintenanceActivityIfNeededLocked();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002115 if (!active) {
2116 exitMaintenanceEarlyIfNeededLocked();
2117 }
2118 }
2119 }
2120
2121 void setAlarmsActive(boolean active) {
2122 synchronized (this) {
2123 mAlarmsActive = active;
2124 if (!active) {
2125 exitMaintenanceEarlyIfNeededLocked();
2126 }
2127 }
2128 }
2129
Yao Chenca5edbb2016-01-13 14:44:36 -08002130 boolean registerMaintenanceActivityListener(IMaintenanceActivityListener listener) {
2131 synchronized (this) {
2132 mMaintenanceActivityListeners.register(listener);
2133 return mReportedMaintenanceActivity;
2134 }
2135 }
2136
2137 void unregisterMaintenanceActivityListener(IMaintenanceActivityListener listener) {
2138 synchronized (this) {
2139 mMaintenanceActivityListeners.unregister(listener);
2140 }
2141 }
2142
2143 void reportMaintenanceActivityIfNeededLocked() {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07002144 boolean active = mJobsActive;
Yao Chenca5edbb2016-01-13 14:44:36 -08002145 if (active == mReportedMaintenanceActivity) {
2146 return;
2147 }
2148 mReportedMaintenanceActivity = active;
2149 Message msg = mHandler.obtainMessage(MSG_REPORT_MAINTENANCE_ACTIVITY,
2150 mReportedMaintenanceActivity ? 1 : 0, 0);
2151 mHandler.sendMessage(msg);
2152 }
2153
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002154 boolean isOpsInactiveLocked() {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07002155 return mActiveIdleOpCount <= 0 && !mJobsActive && !mAlarmsActive;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002156 }
2157
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002158 void exitMaintenanceEarlyIfNeededLocked() {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002159 if (mState == STATE_IDLE_MAINTENANCE || mLightState == LIGHT_STATE_IDLE_MAINTENANCE
2160 || mLightState == LIGHT_STATE_PRE_IDLE) {
2161 if (isOpsInactiveLocked()) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002162 final long now = SystemClock.elapsedRealtime();
2163 if (DEBUG) {
2164 StringBuilder sb = new StringBuilder();
2165 sb.append("Exit: start=");
2166 TimeUtils.formatDuration(mMaintenanceStartTime, sb);
2167 sb.append(" now=");
2168 TimeUtils.formatDuration(now, sb);
2169 Slog.d(TAG, sb.toString());
2170 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002171 if (mState == STATE_IDLE_MAINTENANCE) {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002172 stepIdleStateLocked("s:early");
2173 } else if (mLightState == LIGHT_STATE_PRE_IDLE) {
2174 stepLightIdleStateLocked("s:predone");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002175 } else {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002176 stepLightIdleStateLocked("s:early");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002177 }
2178 }
2179 }
2180 }
2181
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002182 void motionLocked() {
2183 if (DEBUG) Slog.d(TAG, "motionLocked()");
2184 // The motion sensor will have been disabled at this point
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002185 handleMotionDetectedLocked(mConstants.MOTION_INACTIVE_TIMEOUT, "motion");
2186 }
2187
2188 void handleMotionDetectedLocked(long timeout, String type) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002189 // The device is not yet active, so we want to go back to the pending idle
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002190 // state to wait again for no motion. Note that we only monitor for motion
2191 // after moving out of the inactive state, so no need to worry about that.
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002192 boolean becomeInactive = false;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002193 if (mState != STATE_ACTIVE) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002194 scheduleReportActiveLocked(type, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002195 mState = STATE_ACTIVE;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002196 mInactiveTimeout = timeout;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002197 mCurIdleBudget = 0;
2198 mMaintenanceStartTime = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002199 EventLogTags.writeDeviceIdle(mState, type);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002200 addEvent(EVENT_NORMAL);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002201 becomeInactive = true;
2202 }
2203 if (mLightState == LIGHT_STATE_OVERRIDE) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002204 // We went out of light idle mode because we had started deep idle mode... let's
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002205 // now go back and reset things so we resume light idling if appropriate.
2206 mLightState = STATE_ACTIVE;
2207 EventLogTags.writeDeviceIdleLight(mLightState, type);
2208 becomeInactive = true;
2209 }
2210 if (becomeInactive) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002211 becomeInactiveIfAppropriateLocked();
2212 }
2213 }
2214
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002215 void receivedGenericLocationLocked(Location location) {
2216 if (mState != STATE_LOCATING) {
2217 cancelLocatingLocked();
2218 return;
2219 }
2220 if (DEBUG) Slog.d(TAG, "Generic location: " + location);
2221 mLastGenericLocation = new Location(location);
Joe LaPenna23d681b2015-08-27 15:12:11 -07002222 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY && mHasGps) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002223 return;
2224 }
2225 mLocated = true;
2226 if (mNotMoving) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002227 stepIdleStateLocked("s:location");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002228 }
2229 }
2230
2231 void receivedGpsLocationLocked(Location location) {
2232 if (mState != STATE_LOCATING) {
2233 cancelLocatingLocked();
2234 return;
2235 }
2236 if (DEBUG) Slog.d(TAG, "GPS location: " + location);
2237 mLastGpsLocation = new Location(location);
2238 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY) {
2239 return;
2240 }
2241 mLocated = true;
2242 if (mNotMoving) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002243 stepIdleStateLocked("s:gps");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002244 }
2245 }
2246
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002247 void startMonitoringMotionLocked() {
2248 if (DEBUG) Slog.d(TAG, "startMonitoringMotionLocked()");
2249 if (mMotionSensor != null && !mMotionListener.active) {
2250 mMotionListener.registerLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002251 }
2252 }
2253
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002254 void stopMonitoringMotionLocked() {
2255 if (DEBUG) Slog.d(TAG, "stopMonitoringMotionLocked()");
2256 if (mMotionSensor != null && mMotionListener.active) {
2257 mMotionListener.unregisterLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002258 }
2259 }
2260
2261 void cancelAlarmLocked() {
2262 if (mNextAlarmTime != 0) {
2263 mNextAlarmTime = 0;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002264 mAlarmManager.cancel(mDeepAlarmListener);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002265 }
2266 }
2267
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002268 void cancelLightAlarmLocked() {
2269 if (mNextLightAlarmTime != 0) {
2270 mNextLightAlarmTime = 0;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002271 mAlarmManager.cancel(mLightAlarmListener);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002272 }
2273 }
2274
2275 void cancelLocatingLocked() {
2276 if (mLocating) {
2277 mLocationManager.removeUpdates(mGenericLocationListener);
2278 mLocationManager.removeUpdates(mGpsLocationListener);
2279 mLocating = false;
2280 }
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002281 }
2282
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002283 void cancelSensingTimeoutAlarmLocked() {
2284 if (mNextSensingTimeoutAlarmTime != 0) {
2285 mNextSensingTimeoutAlarmTime = 0;
2286 mAlarmManager.cancel(mSensingTimeoutAlarmListener);
2287 }
2288 }
2289
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002290 void scheduleAlarmLocked(long delay, boolean idleUntil) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002291 if (DEBUG) Slog.d(TAG, "scheduleAlarmLocked(" + delay + ", " + idleUntil + ")");
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002292 if (mMotionSensor == null) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07002293 // If there is no motion sensor on this device, then we won't schedule
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002294 // alarms, because we can't determine if the device is not moving. This effectively
Joe LaPenna23d681b2015-08-27 15:12:11 -07002295 // turns off normal execution of device idling, although it is still possible to
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002296 // manually poke it by pretending like the alarm is going off.
2297 return;
2298 }
2299 mNextAlarmTime = SystemClock.elapsedRealtime() + delay;
2300 if (idleUntil) {
2301 mAlarmManager.setIdleUntil(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002302 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002303 } else {
2304 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002305 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002306 }
2307 }
2308
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002309 void scheduleLightAlarmLocked(long delay) {
2310 if (DEBUG) Slog.d(TAG, "scheduleLightAlarmLocked(" + delay + ")");
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002311 mNextLightAlarmTime = SystemClock.elapsedRealtime() + delay;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002312 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002313 mNextLightAlarmTime, "DeviceIdleController.light", mLightAlarmListener, mHandler);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002314 }
2315
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002316 void scheduleSensingTimeoutAlarmLocked(long delay) {
2317 if (DEBUG) Slog.d(TAG, "scheduleSensingAlarmLocked(" + delay + ")");
2318 mNextSensingTimeoutAlarmTime = SystemClock.elapsedRealtime() + delay;
2319 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, mNextSensingTimeoutAlarmTime,
2320 "DeviceIdleController.sensing", mSensingTimeoutAlarmListener, mHandler);
2321 }
2322
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002323 private static int[] buildAppIdArray(ArrayMap<String, Integer> systemApps,
2324 ArrayMap<String, Integer> userApps, SparseBooleanArray outAppIds) {
2325 outAppIds.clear();
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002326 if (systemApps != null) {
2327 for (int i = 0; i < systemApps.size(); i++) {
2328 outAppIds.put(systemApps.valueAt(i), true);
2329 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002330 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002331 if (userApps != null) {
2332 for (int i = 0; i < userApps.size(); i++) {
2333 outAppIds.put(userApps.valueAt(i), true);
2334 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002335 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002336 int size = outAppIds.size();
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002337 int[] appids = new int[size];
2338 for (int i = 0; i < size; i++) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002339 appids[i] = outAppIds.keyAt(i);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002340 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002341 return appids;
2342 }
2343
2344 private void updateWhitelistAppIdsLocked() {
2345 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(mPowerSaveWhitelistAppsExceptIdle,
2346 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistExceptIdleAppIds);
2347 mPowerSaveWhitelistAllAppIdArray = buildAppIdArray(mPowerSaveWhitelistApps,
2348 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistAllAppIds);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002349 mPowerSaveWhitelistUserAppIdArray = buildAppIdArray(null,
2350 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistUserAppIds);
Dianne Hackborn85e35642017-01-12 15:10:57 -08002351 if (mLocalActivityManager != null) {
2352 if (DEBUG) {
2353 Slog.d(TAG, "Setting activity manager whitelist to "
2354 + Arrays.toString(mPowerSaveWhitelistAllAppIdArray));
2355 }
2356 mLocalActivityManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
2357 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002358 if (mLocalPowerManager != null) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002359 if (DEBUG) {
2360 Slog.d(TAG, "Setting wakelock whitelist to "
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002361 + Arrays.toString(mPowerSaveWhitelistAllAppIdArray));
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002362 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002363 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002364 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002365 if (mLocalAlarmManager != null) {
2366 if (DEBUG) {
2367 Slog.d(TAG, "Setting alarm whitelist to "
2368 + Arrays.toString(mPowerSaveWhitelistUserAppIdArray));
2369 }
2370 mLocalAlarmManager.setDeviceIdleUserWhitelist(mPowerSaveWhitelistUserAppIdArray);
2371 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002372 }
2373
Dianne Hackborn85e35642017-01-12 15:10:57 -08002374 private void updateTempWhitelistAppIdsLocked(int appId, boolean adding) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002375 final int size = mTempWhitelistAppIdEndTimes.size();
2376 if (mTempWhitelistAppIdArray.length != size) {
2377 mTempWhitelistAppIdArray = new int[size];
2378 }
2379 for (int i = 0; i < size; i++) {
2380 mTempWhitelistAppIdArray[i] = mTempWhitelistAppIdEndTimes.keyAt(i);
2381 }
Dianne Hackborn85e35642017-01-12 15:10:57 -08002382 if (mLocalActivityManager != null) {
2383 if (DEBUG) {
2384 Slog.d(TAG, "Setting activity manager temp whitelist to "
2385 + Arrays.toString(mTempWhitelistAppIdArray));
2386 }
2387 mLocalActivityManager.updateDeviceIdleTempWhitelist(mTempWhitelistAppIdArray, appId,
2388 adding);
2389 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002390 if (mLocalPowerManager != null) {
2391 if (DEBUG) {
2392 Slog.d(TAG, "Setting wakelock temp whitelist to "
2393 + Arrays.toString(mTempWhitelistAppIdArray));
2394 }
2395 mLocalPowerManager.setDeviceIdleTempWhitelist(mTempWhitelistAppIdArray);
2396 }
2397 }
2398
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002399 private void reportPowerSaveWhitelistChangedLocked() {
2400 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
2401 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Xiaohui Chene4de5a02015-09-22 15:33:31 -07002402 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002403 }
2404
2405 private void reportTempWhitelistChangedLocked() {
2406 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_TEMP_WHITELIST_CHANGED);
2407 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Xiaohui Chene4de5a02015-09-22 15:33:31 -07002408 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002409 }
2410
2411 void readConfigFileLocked() {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002412 if (DEBUG) Slog.d(TAG, "Reading config from " + mConfigFile.getBaseFile());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002413 mPowerSaveWhitelistUserApps.clear();
2414 FileInputStream stream;
2415 try {
2416 stream = mConfigFile.openRead();
2417 } catch (FileNotFoundException e) {
2418 return;
2419 }
2420 try {
2421 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002422 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002423 readConfigFileLocked(parser);
2424 } catch (XmlPullParserException e) {
2425 } finally {
2426 try {
2427 stream.close();
2428 } catch (IOException e) {
2429 }
2430 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002431 }
2432
2433 private void readConfigFileLocked(XmlPullParser parser) {
2434 final PackageManager pm = getContext().getPackageManager();
2435
2436 try {
2437 int type;
2438 while ((type = parser.next()) != XmlPullParser.START_TAG
2439 && type != XmlPullParser.END_DOCUMENT) {
2440 ;
2441 }
2442
2443 if (type != XmlPullParser.START_TAG) {
2444 throw new IllegalStateException("no start tag found");
2445 }
2446
2447 int outerDepth = parser.getDepth();
2448 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2449 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2450 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2451 continue;
2452 }
2453
2454 String tagName = parser.getName();
2455 if (tagName.equals("wl")) {
2456 String name = parser.getAttributeValue(null, "n");
2457 if (name != null) {
2458 try {
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07002459 ApplicationInfo ai = pm.getApplicationInfo(name,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002460 PackageManager.MATCH_ANY_USER);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002461 mPowerSaveWhitelistUserApps.put(ai.packageName,
2462 UserHandle.getAppId(ai.uid));
2463 } catch (PackageManager.NameNotFoundException e) {
2464 }
2465 }
2466 } else {
2467 Slog.w(TAG, "Unknown element under <config>: "
2468 + parser.getName());
2469 XmlUtils.skipCurrentTag(parser);
2470 }
2471 }
2472
2473 } catch (IllegalStateException e) {
2474 Slog.w(TAG, "Failed parsing config " + e);
2475 } catch (NullPointerException e) {
2476 Slog.w(TAG, "Failed parsing config " + e);
2477 } catch (NumberFormatException e) {
2478 Slog.w(TAG, "Failed parsing config " + e);
2479 } catch (XmlPullParserException e) {
2480 Slog.w(TAG, "Failed parsing config " + e);
2481 } catch (IOException e) {
2482 Slog.w(TAG, "Failed parsing config " + e);
2483 } catch (IndexOutOfBoundsException e) {
2484 Slog.w(TAG, "Failed parsing config " + e);
2485 }
2486 }
2487
2488 void writeConfigFileLocked() {
2489 mHandler.removeMessages(MSG_WRITE_CONFIG);
2490 mHandler.sendEmptyMessageDelayed(MSG_WRITE_CONFIG, 5000);
2491 }
2492
2493 void handleWriteConfigFile() {
2494 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
2495
2496 try {
2497 synchronized (this) {
2498 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002499 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002500 writeConfigFileLocked(out);
2501 }
2502 } catch (IOException e) {
2503 }
2504
2505 synchronized (mConfigFile) {
2506 FileOutputStream stream = null;
2507 try {
2508 stream = mConfigFile.startWrite();
2509 memStream.writeTo(stream);
2510 stream.flush();
2511 FileUtils.sync(stream);
2512 stream.close();
2513 mConfigFile.finishWrite(stream);
2514 } catch (IOException e) {
2515 Slog.w(TAG, "Error writing config file", e);
2516 mConfigFile.failWrite(stream);
2517 }
2518 }
2519 }
2520
2521 void writeConfigFileLocked(XmlSerializer out) throws IOException {
2522 out.startDocument(null, true);
2523 out.startTag(null, "config");
2524 for (int i=0; i<mPowerSaveWhitelistUserApps.size(); i++) {
2525 String name = mPowerSaveWhitelistUserApps.keyAt(i);
2526 out.startTag(null, "wl");
2527 out.attribute(null, "n", name);
2528 out.endTag(null, "wl");
2529 }
2530 out.endTag(null, "config");
2531 out.endDocument();
2532 }
2533
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002534 static void dumpHelp(PrintWriter pw) {
2535 pw.println("Device idle controller (deviceidle) commands:");
2536 pw.println(" help");
2537 pw.println(" Print this help text.");
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002538 pw.println(" step [light|deep]");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002539 pw.println(" Immediately step to next state, without waiting for alarm.");
Dianne Hackborn88c41352016-04-07 15:18:58 -07002540 pw.println(" force-idle [light|deep]");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002541 pw.println(" Force directly into idle mode, regardless of other device state.");
Dianne Hackborn88c41352016-04-07 15:18:58 -07002542 pw.println(" force-inactive");
2543 pw.println(" Force to be inactive, ready to freely step idle states.");
2544 pw.println(" unforce");
2545 pw.println(" Resume normal functioning after force-idle or force-inactive.");
2546 pw.println(" get [light|deep|force|screen|charging|network]");
2547 pw.println(" Retrieve the current given state.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002548 pw.println(" disable [light|deep|all]");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002549 pw.println(" Completely disable device idle mode.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002550 pw.println(" enable [light|deep|all]");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002551 pw.println(" Re-enable device idle mode after it had previously been disabled.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002552 pw.println(" enabled [light|deep|all]");
Dianne Hackborn92617032015-06-19 15:32:19 -07002553 pw.println(" Print 1 if device idle mode is currently enabled, else 0.");
Dianne Hackborn1b139682015-07-06 15:13:37 -07002554 pw.println(" whitelist");
2555 pw.println(" Print currently whitelisted apps.");
Dianne Hackborn92617032015-06-19 15:32:19 -07002556 pw.println(" whitelist [package ...]");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002557 pw.println(" Add (prefix with +) or remove (prefix with -) packages.");
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002558 pw.println(" tempwhitelist");
2559 pw.println(" Print packages that are temporarily whitelisted.");
Dianne Hackborn85e35642017-01-12 15:10:57 -08002560 pw.println(" tempwhitelist [-u USER] [-d DURATION] [package ..]");
2561 pw.println(" Temporarily place packages in whitelist for DURATION milliseconds.");
2562 pw.println(" If no DURATION is specified, 10 seconds is used");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002563 }
2564
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002565 class Shell extends ShellCommand {
2566 int userId = UserHandle.USER_SYSTEM;
2567
2568 @Override
2569 public int onCommand(String cmd) {
2570 return onShellCommand(this, cmd);
2571 }
2572
2573 @Override
2574 public void onHelp() {
2575 PrintWriter pw = getOutPrintWriter();
2576 dumpHelp(pw);
2577 }
2578 }
2579
2580 int onShellCommand(Shell shell, String cmd) {
2581 PrintWriter pw = shell.getOutPrintWriter();
2582 if ("step".equals(cmd)) {
2583 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2584 null);
2585 synchronized (this) {
2586 long token = Binder.clearCallingIdentity();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002587 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002588 try {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002589 if (arg == null || "deep".equals(arg)) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002590 stepIdleStateLocked("s:shell");
2591 pw.print("Stepped to deep: ");
2592 pw.println(stateToString(mState));
2593 } else if ("light".equals(arg)) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002594 stepLightIdleStateLocked("s:shell");
2595 pw.print("Stepped to light: "); pw.println(lightStateToString(mLightState));
2596 } else {
2597 pw.println("Unknown idle mode: " + arg);
2598 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002599 } finally {
2600 Binder.restoreCallingIdentity(token);
2601 }
2602 }
2603 } else if ("force-idle".equals(cmd)) {
2604 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2605 null);
2606 synchronized (this) {
2607 long token = Binder.clearCallingIdentity();
Dianne Hackborn88c41352016-04-07 15:18:58 -07002608 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002609 try {
Dianne Hackborn88c41352016-04-07 15:18:58 -07002610 if (arg == null || "deep".equals(arg)) {
2611 if (!mDeepEnabled) {
2612 pw.println("Unable to go deep idle; not enabled");
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002613 return -1;
2614 }
Dianne Hackborn88c41352016-04-07 15:18:58 -07002615 mForceIdle = true;
2616 becomeInactiveIfAppropriateLocked();
2617 int curState = mState;
2618 while (curState != STATE_IDLE) {
2619 stepIdleStateLocked("s:shell");
2620 if (curState == mState) {
2621 pw.print("Unable to go deep idle; stopped at ");
2622 pw.println(stateToString(mState));
2623 exitForceIdleLocked();
2624 return -1;
2625 }
2626 curState = mState;
2627 }
2628 pw.println("Now forced in to deep idle mode");
2629 } else if ("light".equals(arg)) {
2630 mForceIdle = true;
2631 becomeInactiveIfAppropriateLocked();
2632 int curLightState = mLightState;
2633 while (curLightState != LIGHT_STATE_IDLE) {
2634 stepIdleStateLocked("s:shell");
2635 if (curLightState == mLightState) {
2636 pw.print("Unable to go light idle; stopped at ");
2637 pw.println(lightStateToString(mLightState));
2638 exitForceIdleLocked();
2639 return -1;
2640 }
2641 curLightState = mLightState;
2642 }
2643 pw.println("Now forced in to light idle mode");
2644 } else {
2645 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002646 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002647 } finally {
2648 Binder.restoreCallingIdentity(token);
2649 }
2650 }
Dianne Hackborn88c41352016-04-07 15:18:58 -07002651 } else if ("force-inactive".equals(cmd)) {
2652 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2653 null);
2654 synchronized (this) {
2655 long token = Binder.clearCallingIdentity();
2656 try {
2657 mForceIdle = true;
2658 becomeInactiveIfAppropriateLocked();
2659 pw.print("Light state: ");
2660 pw.print(lightStateToString(mLightState));
2661 pw.print(", deep state: ");
2662 pw.println(stateToString(mState));
2663 } finally {
2664 Binder.restoreCallingIdentity(token);
2665 }
2666 }
2667 } else if ("unforce".equals(cmd)) {
2668 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2669 null);
2670 synchronized (this) {
2671 long token = Binder.clearCallingIdentity();
2672 try {
2673 exitForceIdleLocked();
2674 pw.print("Light state: ");
2675 pw.print(lightStateToString(mLightState));
2676 pw.print(", deep state: ");
2677 pw.println(stateToString(mState));
2678 } finally {
2679 Binder.restoreCallingIdentity(token);
2680 }
2681 }
2682 } else if ("get".equals(cmd)) {
2683 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2684 null);
2685 synchronized (this) {
2686 String arg = shell.getNextArg();
2687 if (arg != null) {
2688 long token = Binder.clearCallingIdentity();
2689 try {
2690 switch (arg) {
2691 case "light": pw.println(lightStateToString(mLightState)); break;
2692 case "deep": pw.println(stateToString(mState)); break;
2693 case "force": pw.println(mForceIdle); break;
2694 case "screen": pw.println(mScreenOn); break;
2695 case "charging": pw.println(mCharging); break;
2696 case "network": pw.println(mNetworkConnected); break;
2697 default: pw.println("Unknown get option: " + arg); break;
2698 }
2699 } finally {
2700 Binder.restoreCallingIdentity(token);
2701 }
2702 } else {
2703 pw.println("Argument required");
2704 }
2705 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002706 } else if ("disable".equals(cmd)) {
2707 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2708 null);
2709 synchronized (this) {
2710 long token = Binder.clearCallingIdentity();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002711 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002712 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002713 boolean becomeActive = false;
2714 boolean valid = false;
2715 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
2716 valid = true;
2717 if (mDeepEnabled) {
2718 mDeepEnabled = false;
2719 becomeActive = true;
2720 pw.println("Deep idle mode disabled");
2721 }
2722 }
2723 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
2724 valid = true;
2725 if (mLightEnabled) {
2726 mLightEnabled = false;
2727 becomeActive = true;
2728 pw.println("Light idle mode disabled");
2729 }
2730 }
2731 if (becomeActive) {
2732 becomeActiveLocked((arg == null ? "all" : arg) + "-disabled",
2733 Process.myUid());
2734 }
2735 if (!valid) {
2736 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002737 }
2738 } finally {
2739 Binder.restoreCallingIdentity(token);
2740 }
2741 }
2742 } else if ("enable".equals(cmd)) {
2743 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2744 null);
2745 synchronized (this) {
2746 long token = Binder.clearCallingIdentity();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002747 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002748 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002749 boolean becomeInactive = false;
2750 boolean valid = false;
2751 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
2752 valid = true;
2753 if (!mDeepEnabled) {
2754 mDeepEnabled = true;
2755 becomeInactive = true;
2756 pw.println("Deep idle mode enabled");
2757 }
2758 }
2759 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
2760 valid = true;
2761 if (!mLightEnabled) {
2762 mLightEnabled = true;
2763 becomeInactive = true;
2764 pw.println("Light idle mode enable");
2765 }
2766 }
2767 if (becomeInactive) {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002768 becomeInactiveIfAppropriateLocked();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002769 }
2770 if (!valid) {
2771 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002772 }
2773 } finally {
2774 Binder.restoreCallingIdentity(token);
2775 }
2776 }
2777 } else if ("enabled".equals(cmd)) {
2778 synchronized (this) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002779 String arg = shell.getNextArg();
2780 if (arg == null || "all".equals(arg)) {
2781 pw.println(mDeepEnabled && mLightEnabled ? "1" : 0);
2782 } else if ("deep".equals(arg)) {
2783 pw.println(mDeepEnabled ? "1" : 0);
2784 } else if ("light".equals(arg)) {
2785 pw.println(mLightEnabled ? "1" : 0);
2786 } else {
2787 pw.println("Unknown idle mode: " + arg);
2788 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002789 }
2790 } else if ("whitelist".equals(cmd)) {
Dianne Hackborneb909e32016-09-29 14:35:15 -07002791 String arg = shell.getNextArg();
2792 if (arg != null) {
2793 getContext().enforceCallingOrSelfPermission(
2794 android.Manifest.permission.DEVICE_POWER, null);
2795 long token = Binder.clearCallingIdentity();
2796 try {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002797 do {
2798 if (arg.length() < 1 || (arg.charAt(0) != '-'
Felipe Lemef8a46232016-02-10 13:51:54 -08002799 && arg.charAt(0) != '+' && arg.charAt(0) != '=')) {
2800 pw.println("Package must be prefixed with +, -, or =: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002801 return -1;
2802 }
2803 char op = arg.charAt(0);
2804 String pkg = arg.substring(1);
2805 if (op == '+') {
2806 if (addPowerSaveWhitelistAppInternal(pkg)) {
2807 pw.println("Added: " + pkg);
2808 } else {
2809 pw.println("Unknown package: " + pkg);
2810 }
Felipe Lemef8a46232016-02-10 13:51:54 -08002811 } else if (op == '-') {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002812 if (removePowerSaveWhitelistAppInternal(pkg)) {
2813 pw.println("Removed: " + pkg);
2814 }
Felipe Lemef8a46232016-02-10 13:51:54 -08002815 } else {
2816 pw.println(getPowerSaveWhitelistAppInternal(pkg));
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002817 }
2818 } while ((arg=shell.getNextArg()) != null);
Dianne Hackborneb909e32016-09-29 14:35:15 -07002819 } finally {
2820 Binder.restoreCallingIdentity(token);
2821 }
2822 } else {
2823 synchronized (this) {
2824 for (int j=0; j<mPowerSaveWhitelistAppsExceptIdle.size(); j++) {
2825 pw.print("system-excidle,");
2826 pw.print(mPowerSaveWhitelistAppsExceptIdle.keyAt(j));
2827 pw.print(",");
2828 pw.println(mPowerSaveWhitelistAppsExceptIdle.valueAt(j));
2829 }
2830 for (int j=0; j<mPowerSaveWhitelistApps.size(); j++) {
2831 pw.print("system,");
2832 pw.print(mPowerSaveWhitelistApps.keyAt(j));
2833 pw.print(",");
2834 pw.println(mPowerSaveWhitelistApps.valueAt(j));
2835 }
2836 for (int j=0; j<mPowerSaveWhitelistUserApps.size(); j++) {
2837 pw.print("user,");
2838 pw.print(mPowerSaveWhitelistUserApps.keyAt(j));
2839 pw.print(",");
2840 pw.println(mPowerSaveWhitelistUserApps.valueAt(j));
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002841 }
2842 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002843 }
2844 } else if ("tempwhitelist".equals(cmd)) {
Dianne Hackborn85e35642017-01-12 15:10:57 -08002845 long duration = 10000;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002846 String opt;
2847 while ((opt=shell.getNextOption()) != null) {
2848 if ("-u".equals(opt)) {
2849 opt = shell.getNextArg();
2850 if (opt == null) {
2851 pw.println("-u requires a user number");
2852 return -1;
2853 }
2854 shell.userId = Integer.parseInt(opt);
Dianne Hackborn85e35642017-01-12 15:10:57 -08002855 } else if ("-d".equals(opt)) {
2856 opt = shell.getNextArg();
2857 if (opt == null) {
2858 pw.println("-d requires a duration");
2859 return -1;
2860 }
2861 duration = Long.parseLong(opt);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002862 }
2863 }
2864 String arg = shell.getNextArg();
2865 if (arg != null) {
2866 try {
Dianne Hackborn85e35642017-01-12 15:10:57 -08002867 addPowerSaveTempWhitelistAppChecked(arg, duration, shell.userId, "shell");
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002868 } catch (RemoteException re) {
2869 pw.println("Failed: " + re);
2870 }
2871 } else {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002872 dumpTempWhitelistSchedule(pw, false);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002873 }
2874 } else {
2875 return shell.handleDefaultCommands(cmd);
2876 }
2877 return 0;
2878 }
2879
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002880 void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2881 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2882 != PackageManager.PERMISSION_GRANTED) {
2883 pw.println("Permission Denial: can't dump DeviceIdleController from from pid="
2884 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2885 + " without permission " + android.Manifest.permission.DUMP);
2886 return;
2887 }
2888
2889 if (args != null) {
Xiaohui Chen7c696362015-09-16 09:56:14 -07002890 int userId = UserHandle.USER_SYSTEM;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002891 for (int i=0; i<args.length; i++) {
2892 String arg = args[i];
2893 if ("-h".equals(arg)) {
2894 dumpHelp(pw);
2895 return;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002896 } else if ("-u".equals(arg)) {
2897 i++;
2898 if (i < args.length) {
2899 arg = args[i];
2900 userId = Integer.parseInt(arg);
2901 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002902 } else if ("-a".equals(arg)) {
2903 // Ignore, we always dump all.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002904 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
2905 pw.println("Unknown option: " + arg);
2906 return;
2907 } else {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002908 Shell shell = new Shell();
2909 shell.userId = userId;
2910 String[] newArgs = new String[args.length-i];
2911 System.arraycopy(args, i, newArgs, 0, args.length-i);
Dianne Hackborn354736e2016-08-22 17:00:05 -07002912 shell.exec(mBinderService, null, fd, null, newArgs, null,
2913 new ResultReceiver(null));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002914 return;
2915 }
2916 }
2917 }
2918
2919 synchronized (this) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002920 mConstants.dump(pw);
2921
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002922 if (mEventCmds[0] != EVENT_NULL) {
2923 pw.println(" Idling history:");
2924 long now = SystemClock.elapsedRealtime();
2925 for (int i=EVENT_BUFFER_SIZE-1; i>=0; i--) {
2926 int cmd = mEventCmds[i];
2927 if (cmd == EVENT_NULL) {
2928 continue;
2929 }
2930 String label;
2931 switch (mEventCmds[i]) {
2932 case EVENT_NORMAL: label = " normal"; break;
2933 case EVENT_LIGHT_IDLE: label = " light-idle"; break;
2934 case EVENT_LIGHT_MAINTENANCE: label = "light-maint"; break;
Dianne Hackbornb6843652016-02-22 12:20:13 -08002935 case EVENT_DEEP_IDLE: label = " deep-idle"; break;
2936 case EVENT_DEEP_MAINTENANCE: label = " deep-maint"; break;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002937 default: label = " ??"; break;
2938 }
2939 pw.print(" ");
2940 pw.print(label);
2941 pw.print(": ");
2942 TimeUtils.formatDuration(mEventTimes[i], now, pw);;
2943 pw.println();
2944 }
2945 }
2946
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002947 int size = mPowerSaveWhitelistAppsExceptIdle.size();
2948 if (size > 0) {
2949 pw.println(" Whitelist (except idle) system apps:");
2950 for (int i = 0; i < size; i++) {
2951 pw.print(" ");
2952 pw.println(mPowerSaveWhitelistAppsExceptIdle.keyAt(i));
2953 }
2954 }
2955 size = mPowerSaveWhitelistApps.size();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002956 if (size > 0) {
2957 pw.println(" Whitelist system apps:");
2958 for (int i = 0; i < size; i++) {
2959 pw.print(" ");
2960 pw.println(mPowerSaveWhitelistApps.keyAt(i));
2961 }
2962 }
2963 size = mPowerSaveWhitelistUserApps.size();
2964 if (size > 0) {
2965 pw.println(" Whitelist user apps:");
2966 for (int i = 0; i < size; i++) {
2967 pw.print(" ");
2968 pw.println(mPowerSaveWhitelistUserApps.keyAt(i));
2969 }
2970 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002971 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2972 if (size > 0) {
2973 pw.println(" Whitelist (except idle) all app ids:");
2974 for (int i = 0; i < size; i++) {
2975 pw.print(" ");
2976 pw.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2977 pw.println();
2978 }
2979 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002980 size = mPowerSaveWhitelistUserAppIds.size();
2981 if (size > 0) {
2982 pw.println(" Whitelist user app ids:");
2983 for (int i = 0; i < size; i++) {
2984 pw.print(" ");
2985 pw.print(mPowerSaveWhitelistUserAppIds.keyAt(i));
2986 pw.println();
2987 }
2988 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002989 size = mPowerSaveWhitelistAllAppIds.size();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002990 if (size > 0) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002991 pw.println(" Whitelist all app ids:");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002992 for (int i = 0; i < size; i++) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002993 pw.print(" ");
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002994 pw.print(mPowerSaveWhitelistAllAppIds.keyAt(i));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002995 pw.println();
2996 }
2997 }
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002998 dumpTempWhitelistSchedule(pw, true);
2999
Dianne Hackborna750a632015-06-16 17:18:23 -07003000 size = mTempWhitelistAppIdArray != null ? mTempWhitelistAppIdArray.length : 0;
3001 if (size > 0) {
3002 pw.println(" Temp whitelist app ids:");
3003 for (int i = 0; i < size; i++) {
3004 pw.print(" ");
3005 pw.print(mTempWhitelistAppIdArray[i]);
3006 pw.println();
3007 }
3008 }
Adam Lesinski31c05d12015-06-09 17:34:04 -07003009
Dianne Hackbornb6843652016-02-22 12:20:13 -08003010 pw.print(" mLightEnabled="); pw.print(mLightEnabled);
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003011 pw.print(" mDeepEnabled="); pw.println(mDeepEnabled);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003012 pw.print(" mForceIdle="); pw.println(mForceIdle);
Nick Vaccaro20feaea2015-09-17 17:22:44 -07003013 pw.print(" mMotionSensor="); pw.println(mMotionSensor);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003014 pw.print(" mCurDisplay="); pw.println(mCurDisplay);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003015 pw.print(" mScreenOn="); pw.println(mScreenOn);
Dianne Hackborn88c41352016-04-07 15:18:58 -07003016 pw.print(" mNetworkConnected="); pw.println(mNetworkConnected);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003017 pw.print(" mCharging="); pw.println(mCharging);
Nick Vaccaro20feaea2015-09-17 17:22:44 -07003018 pw.print(" mMotionActive="); pw.println(mMotionListener.active);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003019 pw.print(" mNotMoving="); pw.println(mNotMoving);
Joe LaPenna23d681b2015-08-27 15:12:11 -07003020 pw.print(" mLocating="); pw.print(mLocating); pw.print(" mHasGps=");
3021 pw.print(mHasGps); pw.print(" mHasNetwork=");
3022 pw.print(mHasNetworkLocation); pw.print(" mLocated="); pw.println(mLocated);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07003023 if (mLastGenericLocation != null) {
3024 pw.print(" mLastGenericLocation="); pw.println(mLastGenericLocation);
3025 }
3026 if (mLastGpsLocation != null) {
3027 pw.print(" mLastGpsLocation="); pw.println(mLastGpsLocation);
3028 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003029 pw.print(" mState="); pw.print(stateToString(mState));
3030 pw.print(" mLightState=");
3031 pw.println(lightStateToString(mLightState));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003032 pw.print(" mInactiveTimeout="); TimeUtils.formatDuration(mInactiveTimeout, pw);
3033 pw.println();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003034 if (mActiveIdleOpCount != 0) {
3035 pw.print(" mActiveIdleOpCount="); pw.println(mActiveIdleOpCount);
3036 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003037 if (mNextAlarmTime != 0) {
3038 pw.print(" mNextAlarmTime=");
3039 TimeUtils.formatDuration(mNextAlarmTime, SystemClock.elapsedRealtime(), pw);
3040 pw.println();
3041 }
3042 if (mNextIdlePendingDelay != 0) {
3043 pw.print(" mNextIdlePendingDelay=");
3044 TimeUtils.formatDuration(mNextIdlePendingDelay, pw);
3045 pw.println();
3046 }
3047 if (mNextIdleDelay != 0) {
3048 pw.print(" mNextIdleDelay=");
3049 TimeUtils.formatDuration(mNextIdleDelay, pw);
3050 pw.println();
3051 }
Dianne Hackborn953fc942016-03-29 15:36:24 -07003052 if (mNextLightIdleDelay != 0) {
3053 pw.print(" mNextIdleDelay=");
3054 TimeUtils.formatDuration(mNextLightIdleDelay, pw);
3055 pw.println();
3056 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003057 if (mNextLightAlarmTime != 0) {
3058 pw.print(" mNextLightAlarmTime=");
3059 TimeUtils.formatDuration(mNextLightAlarmTime, SystemClock.elapsedRealtime(), pw);
3060 pw.println();
3061 }
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08003062 if (mCurIdleBudget != 0) {
3063 pw.print(" mCurIdleBudget=");
3064 TimeUtils.formatDuration(mCurIdleBudget, pw);
3065 pw.println();
3066 }
3067 if (mMaintenanceStartTime != 0) {
3068 pw.print(" mMaintenanceStartTime=");
3069 TimeUtils.formatDuration(mMaintenanceStartTime, SystemClock.elapsedRealtime(), pw);
3070 pw.println();
3071 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003072 if (mJobsActive) {
3073 pw.print(" mJobsActive="); pw.println(mJobsActive);
3074 }
3075 if (mAlarmsActive) {
3076 pw.print(" mAlarmsActive="); pw.println(mAlarmsActive);
3077 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003078 }
3079 }
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003080
3081 void dumpTempWhitelistSchedule(PrintWriter pw, boolean printTitle) {
3082 final int size = mTempWhitelistAppIdEndTimes.size();
3083 if (size > 0) {
3084 String prefix = "";
3085 if (printTitle) {
3086 pw.println(" Temp whitelist schedule:");
3087 prefix = " ";
3088 }
3089 final long timeNow = SystemClock.elapsedRealtime();
3090 for (int i = 0; i < size; i++) {
3091 pw.print(prefix);
3092 pw.print("UID=");
3093 pw.print(mTempWhitelistAppIdEndTimes.keyAt(i));
3094 pw.print(": ");
3095 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.valueAt(i);
3096 TimeUtils.formatDuration(entry.first.value, timeNow, pw);
3097 pw.print(" - ");
3098 pw.println(entry.second);
3099 }
3100 }
3101 }
3102 }