blob: 423f9456ee7f58e59d1664a31cf7c5f8247247d6 [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;
20import android.app.ActivityManagerNative;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070021import android.app.AlarmManager;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070022import android.content.BroadcastReceiver;
Adam Lesinski31c05d12015-06-09 17:34:04 -070023import android.content.ContentResolver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070024import android.content.Context;
25import android.content.Intent;
26import android.content.IntentFilter;
27import android.content.pm.ApplicationInfo;
28import android.content.pm.PackageManager;
Amith Yamasaniaf575b92015-05-29 15:35:26 -070029import android.content.pm.PackageManager.NameNotFoundException;
Adam Lesinski31c05d12015-06-09 17:34:04 -070030import android.database.ContentObserver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070031import android.hardware.Sensor;
32import android.hardware.SensorManager;
Nick Vaccaro20feaea2015-09-17 17:22:44 -070033import android.hardware.SensorEvent;
34import android.hardware.SensorEventListener;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070035import android.hardware.TriggerEvent;
36import android.hardware.TriggerEventListener;
37import android.hardware.display.DisplayManager;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -070038import android.location.LocationRequest;
39import android.location.Location;
40import android.location.LocationListener;
41import android.location.LocationManager;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070042import android.net.INetworkPolicyManager;
Adam Lesinski31c05d12015-06-09 17:34:04 -070043import android.net.Uri;
Dianne Hackbornfd854ee2015-07-13 18:00:37 -070044import android.os.BatteryStats;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070045import android.os.Binder;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -070046import android.os.Bundle;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070047import android.os.Environment;
48import android.os.FileUtils;
49import android.os.Handler;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080050import android.os.IBinder;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070051import android.os.IDeviceIdleController;
Yao Chenca5edbb2016-01-13 14:44:36 -080052import android.os.IMaintenanceActivityListener;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070053import android.os.Looper;
54import android.os.Message;
55import android.os.PowerManager;
56import android.os.PowerManagerInternal;
Dianne Hackbornb6683c42015-06-18 17:40:33 -070057import android.os.Process;
Yao Chenca5edbb2016-01-13 14:44:36 -080058import android.os.RemoteCallbackList;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070059import android.os.RemoteException;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -070060import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070061import android.os.ServiceManager;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -070062import android.os.ShellCommand;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070063import android.os.SystemClock;
64import android.os.UserHandle;
Adam Lesinski31c05d12015-06-09 17:34:04 -070065import android.provider.Settings;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070066import android.util.ArrayMap;
67import android.util.ArraySet;
Adam Lesinski31c05d12015-06-09 17:34:04 -070068import android.util.KeyValueListParser;
Dianne Hackbornfd854ee2015-07-13 18:00:37 -070069import android.util.MutableLong;
70import android.util.Pair;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070071import android.util.Slog;
Dianne Hackbornfd854ee2015-07-13 18:00:37 -070072import android.util.SparseArray;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070073import android.util.SparseBooleanArray;
74import android.util.TimeUtils;
75import android.util.Xml;
76import android.view.Display;
Amith Yamasani520d8f22015-05-08 16:36:21 -070077
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070078import com.android.internal.app.IBatteryStats;
79import com.android.internal.os.AtomicFile;
80import com.android.internal.os.BackgroundThread;
81import com.android.internal.util.FastXmlSerializer;
82import com.android.internal.util.XmlUtils;
83import com.android.server.am.BatteryStatsService;
Amith Yamasani520d8f22015-05-08 16:36:21 -070084
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070085import org.xmlpull.v1.XmlPullParser;
86import org.xmlpull.v1.XmlPullParserException;
87import org.xmlpull.v1.XmlSerializer;
88
89import java.io.ByteArrayOutputStream;
90import java.io.File;
91import java.io.FileDescriptor;
92import java.io.FileInputStream;
93import java.io.FileNotFoundException;
94import java.io.FileOutputStream;
95import java.io.IOException;
96import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010097import java.nio.charset.StandardCharsets;
Amith Yamasaniaf575b92015-05-29 15:35:26 -070098import java.util.Arrays;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070099
100/**
101 * Keeps track of device idleness and drives low power mode based on that.
102 */
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700103public class DeviceIdleController extends SystemService
104 implements AnyMotionDetector.DeviceIdleCallback {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700105 private static final String TAG = "DeviceIdleController";
106
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700107 private static final boolean DEBUG = false;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700108
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700109 private static final boolean COMPRESS_TIME = false;
Amith Yamasani520d8f22015-05-08 16:36:21 -0700110
Dianne Hackborn953fc942016-03-29 15:36:24 -0700111 private static final int EVENT_BUFFER_SIZE = 100;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800112
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700113 private AlarmManager mAlarmManager;
114 private IBatteryStats mBatteryStats;
115 private PowerManagerInternal mLocalPowerManager;
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700116 private PowerManager mPowerManager;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -0800117 private AlarmManagerService.LocalService mLocalAlarmManager;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700118 private INetworkPolicyManager mNetworkPolicyManager;
119 private DisplayManager mDisplayManager;
120 private SensorManager mSensorManager;
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700121 private Sensor mMotionSensor;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700122 private LocationManager mLocationManager;
123 private LocationRequest mLocationRequest;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700124 private Intent mIdleIntent;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700125 private Intent mLightIdleIntent;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700126 private Display mCurDisplay;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700127 private AnyMotionDetector mAnyMotionDetector;
Dianne Hackbornb6843652016-02-22 12:20:13 -0800128 private boolean mLightEnabled;
129 private boolean mDeepEnabled;
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700130 private boolean mForceIdle;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700131 private boolean mScreenOn;
132 private boolean mCharging;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700133 private boolean mNotMoving;
134 private boolean mLocating;
135 private boolean mLocated;
Joe LaPenna23d681b2015-08-27 15:12:11 -0700136 private boolean mHasGps;
137 private boolean mHasNetworkLocation;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700138 private Location mLastGenericLocation;
139 private Location mLastGpsLocation;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700140
141 /** Device is currently active. */
142 private static final int STATE_ACTIVE = 0;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700143 /** Device is inactive (screen off, no motion) and we are waiting to for idle. */
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700144 private static final int STATE_INACTIVE = 1;
145 /** Device is past the initial inactive period, and waiting for the next idle period. */
146 private static final int STATE_IDLE_PENDING = 2;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700147 /** Device is currently sensing motion. */
148 private static final int STATE_SENSING = 3;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700149 /** Device is currently finding location (and may still be sensing). */
150 private static final int STATE_LOCATING = 4;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700151 /** Device is in the idle state, trying to stay asleep as much as possible. */
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700152 private static final int STATE_IDLE = 5;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700153 /** Device is in the idle state, but temporarily out of idle to do regular maintenance. */
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700154 private static final int STATE_IDLE_MAINTENANCE = 6;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700155 private static String stateToString(int state) {
156 switch (state) {
157 case STATE_ACTIVE: return "ACTIVE";
158 case STATE_INACTIVE: return "INACTIVE";
159 case STATE_IDLE_PENDING: return "IDLE_PENDING";
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700160 case STATE_SENSING: return "SENSING";
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700161 case STATE_LOCATING: return "LOCATING";
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700162 case STATE_IDLE: return "IDLE";
163 case STATE_IDLE_MAINTENANCE: return "IDLE_MAINTENANCE";
164 default: return Integer.toString(state);
165 }
166 }
167
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700168 /** Device is currently active. */
169 private static final int LIGHT_STATE_ACTIVE = 0;
170 /** Device is inactive (screen off) and we are waiting to for the first light idle. */
171 private static final int LIGHT_STATE_INACTIVE = 1;
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700172 /** Device is about to go idle for the first time, wait for current work to complete. */
173 private static final int LIGHT_STATE_PRE_IDLE = 3;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700174 /** Device is in the light idle state, trying to stay asleep as much as possible. */
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700175 private static final int LIGHT_STATE_IDLE = 4;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700176 /** Device is in the light idle state, but temporarily out of idle to do regular maintenance. */
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700177 private static final int LIGHT_STATE_IDLE_MAINTENANCE = 5;
Dianne Hackbornb6843652016-02-22 12:20:13 -0800178 /** Device light idle state is overriden, now applying deep doze state. */
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700179 private static final int LIGHT_STATE_OVERRIDE = 6;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700180 private static String lightStateToString(int state) {
181 switch (state) {
182 case LIGHT_STATE_ACTIVE: return "ACTIVE";
183 case LIGHT_STATE_INACTIVE: return "INACTIVE";
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700184 case LIGHT_STATE_PRE_IDLE: return "PRE_IDLE";
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700185 case LIGHT_STATE_IDLE: return "IDLE";
186 case LIGHT_STATE_IDLE_MAINTENANCE: return "IDLE_MAINTENANCE";
187 case LIGHT_STATE_OVERRIDE: return "OVERRIDE";
188 default: return Integer.toString(state);
189 }
190 }
191
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700192 private int mState;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700193 private int mLightState;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700194
195 private long mInactiveTimeout;
196 private long mNextAlarmTime;
197 private long mNextIdlePendingDelay;
198 private long mNextIdleDelay;
Dianne Hackborn953fc942016-03-29 15:36:24 -0700199 private long mNextLightIdleDelay;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700200 private long mNextLightAlarmTime;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800201 private long mCurIdleBudget;
202 private long mMaintenanceStartTime;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700203
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800204 private int mActiveIdleOpCount;
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700205 private PowerManager.WakeLock mActiveIdleWakeLock;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800206 private IBinder mDownloadServiceActive;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800207 private boolean mJobsActive;
208 private boolean mAlarmsActive;
Yao Chenca5edbb2016-01-13 14:44:36 -0800209 private boolean mReportedMaintenanceActivity;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800210
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700211 public final AtomicFile mConfigFile;
212
Yao Chenca5edbb2016-01-13 14:44:36 -0800213 private final RemoteCallbackList<IMaintenanceActivityListener> mMaintenanceActivityListeners =
214 new RemoteCallbackList<IMaintenanceActivityListener>();
215
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700216 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700217 * Package names the system has white-listed to opt out of power save restrictions,
218 * except for device idle mode.
219 */
220 private final ArrayMap<String, Integer> mPowerSaveWhitelistAppsExceptIdle = new ArrayMap<>();
221
222 /**
223 * Package names the system has white-listed to opt out of power save restrictions for
224 * all modes.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700225 */
226 private final ArrayMap<String, Integer> mPowerSaveWhitelistApps = new ArrayMap<>();
227
228 /**
229 * Package names the user has white-listed to opt out of power save restrictions.
230 */
231 private final ArrayMap<String, Integer> mPowerSaveWhitelistUserApps = new ArrayMap<>();
232
233 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700234 * App IDs of built-in system apps that have been white-listed except for idle modes.
235 */
236 private final SparseBooleanArray mPowerSaveWhitelistSystemAppIdsExceptIdle
237 = new SparseBooleanArray();
238
239 /**
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700240 * App IDs of built-in system apps that have been white-listed.
241 */
242 private final SparseBooleanArray mPowerSaveWhitelistSystemAppIds = new SparseBooleanArray();
243
244 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700245 * App IDs that have been white-listed to opt out of power save restrictions, except
246 * for device idle modes.
247 */
248 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
249
250 /**
251 * Current app IDs that are in the complete power save white list, but shouldn't be
252 * excluded from idle modes. This array can be shared with others because it will not be
253 * modified once set.
254 */
255 private int[] mPowerSaveWhitelistExceptIdleAppIdArray = new int[0];
256
257 /**
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700258 * App IDs that have been white-listed to opt out of power save restrictions.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700259 */
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700260 private final SparseBooleanArray mPowerSaveWhitelistAllAppIds = new SparseBooleanArray();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700261
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700262 /**
263 * Current app IDs that are in the complete power save white list. This array can
264 * be shared with others because it will not be modified once set.
265 */
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700266 private int[] mPowerSaveWhitelistAllAppIdArray = new int[0];
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700267
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700268 /**
Dianne Hackborn262ae5c2016-02-10 16:28:29 -0800269 * App IDs that have been white-listed by the user to opt out of power save restrictions.
270 */
271 private final SparseBooleanArray mPowerSaveWhitelistUserAppIds = new SparseBooleanArray();
272
273 /**
274 * Current app IDs that are in the user power save white list. This array can
275 * be shared with others because it will not be modified once set.
276 */
277 private int[] mPowerSaveWhitelistUserAppIdArray = new int[0];
278
279 /**
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700280 * List of end times for UIDs that are temporarily marked as being allowed to access
281 * the network and acquire wakelocks. Times are in milliseconds.
282 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700283 private final SparseArray<Pair<MutableLong, String>> mTempWhitelistAppIdEndTimes
284 = new SparseArray<>();
285
286 /**
287 * Callback to the NetworkPolicyManagerService to tell it that the temp whitelist has changed.
288 */
289 Runnable mNetworkPolicyTempWhitelistCallback;
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700290
291 /**
292 * Current app IDs of temporarily whitelist apps for high-priority messages.
293 */
294 private int[] mTempWhitelistAppIdArray = new int[0];
295
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800296 private static final int EVENT_NULL = 0;
297 private static final int EVENT_NORMAL = 1;
298 private static final int EVENT_LIGHT_IDLE = 2;
299 private static final int EVENT_LIGHT_MAINTENANCE = 3;
Dianne Hackbornb6843652016-02-22 12:20:13 -0800300 private static final int EVENT_DEEP_IDLE = 4;
301 private static final int EVENT_DEEP_MAINTENANCE = 5;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800302
303 private int[] mEventCmds = new int[EVENT_BUFFER_SIZE];
304 private long[] mEventTimes = new long[EVENT_BUFFER_SIZE];
305
306 private void addEvent(int cmd) {
307 if (mEventCmds[0] != cmd) {
308 System.arraycopy(mEventCmds, 0, mEventCmds, 1, EVENT_BUFFER_SIZE - 1);
309 System.arraycopy(mEventTimes, 0, mEventTimes, 1, EVENT_BUFFER_SIZE - 1);
310 mEventCmds[0] = cmd;
311 mEventTimes[0] = SystemClock.elapsedRealtime();
312 }
313 }
314
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700315 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
316 @Override public void onReceive(Context context, Intent intent) {
317 if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
318 int plugged = intent.getIntExtra("plugged", 0);
319 updateChargingLocked(plugged != 0);
Dianne Hackborn1b79ad72015-10-12 10:59:47 -0700320 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
321 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
322 Uri data = intent.getData();
323 String ssp;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700324 if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
Dianne Hackborn1b79ad72015-10-12 10:59:47 -0700325 removePowerSaveWhitelistAppInternal(ssp);
326 }
327 }
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700328 }
329 }
330 };
331
332 private final AlarmManager.OnAlarmListener mLightAlarmListener
333 = new AlarmManager.OnAlarmListener() {
334 @Override
335 public void onAlarm() {
336 synchronized (DeviceIdleController.this) {
337 stepLightIdleStateLocked("s:alarm");
338 }
339 }
340 };
341
342 private final AlarmManager.OnAlarmListener mDeepAlarmListener
343 = new AlarmManager.OnAlarmListener() {
344 @Override
345 public void onAlarm() {
346 synchronized (DeviceIdleController.this) {
347 stepIdleStateLocked("s:alarm");
348 }
349 }
350 };
351
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800352 private final BroadcastReceiver mIdleStartedDoneReceiver = new BroadcastReceiver() {
353 @Override public void onReceive(Context context, Intent intent) {
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700354 // When coming out of a deep idle, we will add in some delay before we allow
355 // the system to settle down and finish the maintenance window. This is
356 // to give a chance for any pending work to be scheduled.
357 if (PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED.equals(intent.getAction())) {
358 mHandler.sendEmptyMessageDelayed(MSG_FINISH_IDLE_OP,
359 mConstants.MIN_DEEP_MAINTENANCE_TIME);
360 } else {
361 mHandler.sendEmptyMessageDelayed(MSG_FINISH_IDLE_OP,
362 mConstants.MIN_LIGHT_MAINTENANCE_TIME);
363 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800364 }
365 };
366
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700367 private final DisplayManager.DisplayListener mDisplayListener
368 = new DisplayManager.DisplayListener() {
369 @Override public void onDisplayAdded(int displayId) {
370 }
371
372 @Override public void onDisplayRemoved(int displayId) {
373 }
374
375 @Override public void onDisplayChanged(int displayId) {
376 if (displayId == Display.DEFAULT_DISPLAY) {
377 synchronized (DeviceIdleController.this) {
378 updateDisplayLocked();
379 }
380 }
381 }
382 };
383
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700384 private final class MotionListener extends TriggerEventListener
385 implements SensorEventListener {
386
387 boolean active = false;
388
389 @Override
390 public void onTrigger(TriggerEvent event) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700391 synchronized (DeviceIdleController.this) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700392 active = false;
393 motionLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700394 }
395 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700396
397 @Override
398 public void onSensorChanged(SensorEvent event) {
399 synchronized (DeviceIdleController.this) {
400 mSensorManager.unregisterListener(this, mMotionSensor);
401 active = false;
402 motionLocked();
403 }
404 }
405
406 @Override
407 public void onAccuracyChanged(Sensor sensor, int accuracy) {}
408
409 public boolean registerLocked() {
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700410 boolean success;
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700411 if (mMotionSensor.getReportingMode() == Sensor.REPORTING_MODE_ONE_SHOT) {
412 success = mSensorManager.requestTriggerSensor(mMotionListener, mMotionSensor);
413 } else {
414 success = mSensorManager.registerListener(
415 mMotionListener, mMotionSensor, SensorManager.SENSOR_DELAY_NORMAL);
416 }
417 if (success) {
418 active = true;
419 } else {
420 Slog.e(TAG, "Unable to register for " + mMotionSensor);
421 }
422 return success;
423 }
424
425 public void unregisterLocked() {
426 if (mMotionSensor.getReportingMode() == Sensor.REPORTING_MODE_ONE_SHOT) {
427 mSensorManager.cancelTriggerSensor(mMotionListener, mMotionSensor);
428 } else {
429 mSensorManager.unregisterListener(mMotionListener);
430 }
431 active = false;
432 }
433 }
434 private final MotionListener mMotionListener = new MotionListener();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700435
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700436 private final LocationListener mGenericLocationListener = new LocationListener() {
437 @Override
438 public void onLocationChanged(Location location) {
439 synchronized (DeviceIdleController.this) {
440 receivedGenericLocationLocked(location);
441 }
442 }
443
444 @Override
445 public void onStatusChanged(String provider, int status, Bundle extras) {
446 }
447
448 @Override
449 public void onProviderEnabled(String provider) {
450 }
451
452 @Override
453 public void onProviderDisabled(String provider) {
454 }
455 };
456
457 private final LocationListener mGpsLocationListener = new LocationListener() {
458 @Override
459 public void onLocationChanged(Location location) {
460 synchronized (DeviceIdleController.this) {
461 receivedGpsLocationLocked(location);
462 }
463 }
464
465 @Override
466 public void onStatusChanged(String provider, int status, Bundle extras) {
467 }
468
469 @Override
470 public void onProviderEnabled(String provider) {
471 }
472
473 @Override
474 public void onProviderDisabled(String provider) {
475 }
476 };
477
Adam Lesinski31c05d12015-06-09 17:34:04 -0700478 /**
479 * All times are in milliseconds. These constants are kept synchronized with the system
480 * global Settings. Any access to this class or its fields should be done while
481 * holding the DeviceIdleController lock.
482 */
Dianne Hackborna750a632015-06-16 17:18:23 -0700483 private final class Constants extends ContentObserver {
Adam Lesinski31c05d12015-06-09 17:34:04 -0700484 // Key names stored in the settings value.
Dianne Hackborn953fc942016-03-29 15:36:24 -0700485 private static final String KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT
486 = "light_after_inactive_to";
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700487 private static final String KEY_LIGHT_PRE_IDLE_TIMEOUT = "light_pre_idle_to";
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700488 private static final String KEY_LIGHT_IDLE_TIMEOUT = "light_idle_to";
Dianne Hackborn953fc942016-03-29 15:36:24 -0700489 private static final String KEY_LIGHT_IDLE_FACTOR = "light_idle_factor";
490 private static final String KEY_LIGHT_MAX_IDLE_TIMEOUT = "light_max_idle_to";
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800491 private static final String KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET
492 = "light_idle_maintenance_min_budget";
493 private static final String KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET
494 = "light_idle_maintenance_max_budget";
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700495 private static final String KEY_MIN_LIGHT_MAINTENANCE_TIME = "min_light_maintenance_time";
496 private static final String KEY_MIN_DEEP_MAINTENANCE_TIME = "min_deep_maintenance_time";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700497 private static final String KEY_INACTIVE_TIMEOUT = "inactive_to";
498 private static final String KEY_SENSING_TIMEOUT = "sensing_to";
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700499 private static final String KEY_LOCATING_TIMEOUT = "locating_to";
500 private static final String KEY_LOCATION_ACCURACY = "location_accuracy";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700501 private static final String KEY_MOTION_INACTIVE_TIMEOUT = "motion_inactive_to";
502 private static final String KEY_IDLE_AFTER_INACTIVE_TIMEOUT = "idle_after_inactive_to";
503 private static final String KEY_IDLE_PENDING_TIMEOUT = "idle_pending_to";
504 private static final String KEY_MAX_IDLE_PENDING_TIMEOUT = "max_idle_pending_to";
505 private static final String KEY_IDLE_PENDING_FACTOR = "idle_pending_factor";
506 private static final String KEY_IDLE_TIMEOUT = "idle_to";
507 private static final String KEY_MAX_IDLE_TIMEOUT = "max_idle_to";
508 private static final String KEY_IDLE_FACTOR = "idle_factor";
509 private static final String KEY_MIN_TIME_TO_ALARM = "min_time_to_alarm";
510 private static final String KEY_MAX_TEMP_APP_WHITELIST_DURATION =
511 "max_temp_app_whitelist_duration";
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700512 private static final String KEY_MMS_TEMP_APP_WHITELIST_DURATION =
513 "mms_temp_app_whitelist_duration";
Dianne Hackborn451c3462015-07-21 17:39:46 -0700514 private static final String KEY_SMS_TEMP_APP_WHITELIST_DURATION =
515 "sms_temp_app_whitelist_duration";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700516
517 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700518 * This is the time, after becoming inactive, that we go in to the first
519 * light-weight idle mode.
520 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
521 * @see #KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT
522 */
523 public long LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT;
524
525 /**
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700526 * This is amount of time we will wait from the point where we decide we would
527 * like to go idle until we actually do, while waiting for jobs and other current
528 * activity to finish.
529 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
530 * @see #KEY_LIGHT_PRE_IDLE_TIMEOUT
531 */
532 public long LIGHT_PRE_IDLE_TIMEOUT;
533
534 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700535 * This is the initial time that we will run in idle maintenance mode.
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700536 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
537 * @see #KEY_LIGHT_IDLE_TIMEOUT
538 */
539 public long LIGHT_IDLE_TIMEOUT;
540
541 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700542 * Scaling factor to apply to the light idle mode time each time we complete a cycle.
543 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
544 * @see #KEY_LIGHT_IDLE_FACTOR
545 */
546 public float LIGHT_IDLE_FACTOR;
547
548 /**
549 * This is the maximum time we will run in idle maintenence mode.
550 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
551 * @see #KEY_LIGHT_MAX_IDLE_TIMEOUT
552 */
553 public long LIGHT_MAX_IDLE_TIMEOUT;
554
555 /**
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800556 * This is the minimum amount of time we want to make available for maintenance mode
557 * when lightly idling. That is, we will always have at least this amount of time
558 * available maintenance before timing out and cutting off maintenance mode.
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700559 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800560 * @see #KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700561 */
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800562 public long LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
563
564 /**
565 * This is the maximum amount of time we want to make available for maintenance mode
566 * when lightly idling. That is, if the system isn't using up its minimum maintenance
567 * budget and this time is being added to the budget reserve, this is the maximum
568 * reserve size we will allow to grow and thus the maximum amount of time we will
569 * allow for the maintenance window.
570 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
571 * @see #KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET
572 */
573 public long LIGHT_IDLE_MAINTENANCE_MAX_BUDGET;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700574
575 /**
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700576 * This is the minimum amount of time that we will stay in maintenance mode after
577 * a light doze. We have this minimum to allow various things to respond to switching
578 * in to maintenance mode and scheduling their work -- otherwise we may
579 * see there is nothing to do (no jobs or downloads pending) and go out of maintenance
580 * mode immediately.
581 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
582 * @see #KEY_MIN_LIGHT_MAINTENANCE_TIME
583 */
584 public long MIN_LIGHT_MAINTENANCE_TIME;
585
586 /**
587 * This is the minimum amount of time that we will stay in maintenance mode after
588 * a full doze. We have this minimum to allow various things to respond to switching
589 * in to maintenance mode and scheduling their work -- otherwise we may
590 * see there is nothing to do (no jobs or downloads pending) and go out of maintenance
591 * mode immediately.
592 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
593 * @see #KEY_MIN_DEEP_MAINTENANCE_TIME
594 */
595 public long MIN_DEEP_MAINTENANCE_TIME;
596
597 /**
Adam Lesinski31c05d12015-06-09 17:34:04 -0700598 * This is the time, after becoming inactive, at which we start looking at the
599 * motion sensor to determine if the device is being left alone. We don't do this
600 * immediately after going inactive just because we don't want to be continually running
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700601 * the motion sensor whenever the screen is off.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700602 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
603 * @see #KEY_INACTIVE_TIMEOUT
604 */
605 public long INACTIVE_TIMEOUT;
606
607 /**
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700608 * If we don't receive a callback from AnyMotion in this amount of time +
609 * {@link #LOCATING_TIMEOUT}, we will change from
Adam Lesinski31c05d12015-06-09 17:34:04 -0700610 * STATE_SENSING to STATE_INACTIVE, and any AnyMotion callbacks while not in STATE_SENSING
611 * will be ignored.
612 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
613 * @see #KEY_SENSING_TIMEOUT
614 */
615 public long SENSING_TIMEOUT;
616
617 /**
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700618 * This is how long we will wait to try to get a good location fix before going in to
619 * idle mode.
620 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
621 * @see #KEY_LOCATING_TIMEOUT
622 */
623 public long LOCATING_TIMEOUT;
624
625 /**
626 * The desired maximum accuracy (in meters) we consider the location to be good enough to go
627 * on to idle. We will be trying to get an accuracy fix at least this good or until
628 * {@link #LOCATING_TIMEOUT} expires.
629 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
630 * @see #KEY_LOCATION_ACCURACY
631 */
632 public float LOCATION_ACCURACY;
633
634 /**
Adam Lesinski31c05d12015-06-09 17:34:04 -0700635 * This is the time, after seeing motion, that we wait after becoming inactive from
636 * that until we start looking for motion again.
637 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
638 * @see #KEY_MOTION_INACTIVE_TIMEOUT
639 */
640 public long MOTION_INACTIVE_TIMEOUT;
641
642 /**
643 * This is the time, after the inactive timeout elapses, that we will wait looking
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700644 * for motion until we truly consider the device to be idle.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700645 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
646 * @see #KEY_IDLE_AFTER_INACTIVE_TIMEOUT
647 */
648 public long IDLE_AFTER_INACTIVE_TIMEOUT;
649
650 /**
651 * This is the initial time, after being idle, that we will allow ourself to be back
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700652 * in the IDLE_MAINTENANCE state allowing the system to run normally until we return to
653 * idle.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700654 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
655 * @see #KEY_IDLE_PENDING_TIMEOUT
656 */
657 public long IDLE_PENDING_TIMEOUT;
658
659 /**
660 * Maximum pending idle timeout (time spent running) we will be allowed to use.
661 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
662 * @see #KEY_MAX_IDLE_PENDING_TIMEOUT
663 */
664 public long MAX_IDLE_PENDING_TIMEOUT;
665
666 /**
667 * Scaling factor to apply to current pending idle timeout each time we cycle through
668 * that state.
669 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
670 * @see #KEY_IDLE_PENDING_FACTOR
671 */
672 public float IDLE_PENDING_FACTOR;
673
674 /**
675 * This is the initial time that we want to sit in the idle state before waking up
676 * again to return to pending idle and allowing normal work to run.
677 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
678 * @see #KEY_IDLE_TIMEOUT
679 */
680 public long IDLE_TIMEOUT;
681
682 /**
683 * Maximum idle duration we will be allowed to use.
684 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
685 * @see #KEY_MAX_IDLE_TIMEOUT
686 */
687 public long MAX_IDLE_TIMEOUT;
688
689 /**
690 * Scaling factor to apply to current idle timeout each time we cycle through that state.
691 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
692 * @see #KEY_IDLE_FACTOR
693 */
694 public float IDLE_FACTOR;
695
696 /**
697 * This is the minimum time we will allow until the next upcoming alarm for us to
698 * actually go in to idle mode.
699 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
700 * @see #KEY_MIN_TIME_TO_ALARM
701 */
702 public long MIN_TIME_TO_ALARM;
703
704 /**
705 * Max amount of time to temporarily whitelist an app when it receives a high priority
706 * tickle.
707 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
708 * @see #KEY_MAX_TEMP_APP_WHITELIST_DURATION
709 */
710 public long MAX_TEMP_APP_WHITELIST_DURATION;
711
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700712 /**
713 * Amount of time we would like to whitelist an app that is receiving an MMS.
714 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
715 * @see #KEY_MMS_TEMP_APP_WHITELIST_DURATION
716 */
717 public long MMS_TEMP_APP_WHITELIST_DURATION;
718
Dianne Hackborn451c3462015-07-21 17:39:46 -0700719 /**
720 * Amount of time we would like to whitelist an app that is receiving an SMS.
721 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
722 * @see #KEY_SMS_TEMP_APP_WHITELIST_DURATION
723 */
724 public long SMS_TEMP_APP_WHITELIST_DURATION;
725
Adam Lesinski31c05d12015-06-09 17:34:04 -0700726 private final ContentResolver mResolver;
Joe LaPennaf33b5bf2016-03-23 15:19:47 -0700727 private final boolean mHasWatch;
Adam Lesinski31c05d12015-06-09 17:34:04 -0700728 private final KeyValueListParser mParser = new KeyValueListParser(',');
729
730 public Constants(Handler handler, ContentResolver resolver) {
731 super(handler);
732 mResolver = resolver;
Joe LaPennaf33b5bf2016-03-23 15:19:47 -0700733 mHasWatch = getContext().getPackageManager().hasSystemFeature(
734 PackageManager.FEATURE_WATCH);
735 mResolver.registerContentObserver(Settings.Global.getUriFor(
736 mHasWatch ? Settings.Global.DEVICE_IDLE_CONSTANTS_WATCH
737 : Settings.Global.DEVICE_IDLE_CONSTANTS),
738 false, this);
Adam Lesinski31c05d12015-06-09 17:34:04 -0700739 updateConstants();
740 }
741
742 @Override
743 public void onChange(boolean selfChange, Uri uri) {
744 updateConstants();
745 }
746
747 private void updateConstants() {
748 synchronized (DeviceIdleController.this) {
749 try {
750 mParser.setString(Settings.Global.getString(mResolver,
Joe LaPennaf33b5bf2016-03-23 15:19:47 -0700751 mHasWatch ? Settings.Global.DEVICE_IDLE_CONSTANTS_WATCH
752 : Settings.Global.DEVICE_IDLE_CONSTANTS));
Adam Lesinski31c05d12015-06-09 17:34:04 -0700753 } catch (IllegalArgumentException e) {
754 // Failed to parse the settings string, log this and move on
755 // with defaults.
756 Slog.e(TAG, "Bad device idle settings", e);
757 }
758
Dianne Hackborn953fc942016-03-29 15:36:24 -0700759 LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT = mParser.getLong(
760 KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT,
761 !COMPRESS_TIME ? 5 * 60 * 1000L : 15 * 1000L);
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700762 LIGHT_PRE_IDLE_TIMEOUT = mParser.getLong(KEY_LIGHT_PRE_IDLE_TIMEOUT,
763 !COMPRESS_TIME ? 10 * 60 * 1000L : 30 * 1000L);
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700764 LIGHT_IDLE_TIMEOUT = mParser.getLong(KEY_LIGHT_IDLE_TIMEOUT,
Dianne Hackborn953fc942016-03-29 15:36:24 -0700765 !COMPRESS_TIME ? 5 * 60 * 1000L : 15 * 1000L);
766 LIGHT_IDLE_FACTOR = mParser.getFloat(KEY_LIGHT_IDLE_FACTOR,
767 2f);
768 LIGHT_MAX_IDLE_TIMEOUT = mParser.getLong(KEY_LIGHT_MAX_IDLE_TIMEOUT,
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700769 !COMPRESS_TIME ? 15 * 60 * 1000L : 60 * 1000L);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800770 LIGHT_IDLE_MAINTENANCE_MIN_BUDGET = mParser.getLong(
771 KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET,
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700772 !COMPRESS_TIME ? 1 * 60 * 1000L : 15 * 1000L);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800773 LIGHT_IDLE_MAINTENANCE_MAX_BUDGET = mParser.getLong(
774 KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET,
775 !COMPRESS_TIME ? 5 * 60 * 1000L : 30 * 1000L);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700776 MIN_LIGHT_MAINTENANCE_TIME = mParser.getLong(
777 KEY_MIN_LIGHT_MAINTENANCE_TIME,
778 !COMPRESS_TIME ? 5 * 1000L : 1 * 1000L);
779 MIN_DEEP_MAINTENANCE_TIME = mParser.getLong(
780 KEY_MIN_DEEP_MAINTENANCE_TIME,
781 !COMPRESS_TIME ? 30 * 1000L : 5 * 1000L);
Joe LaPenna0c5d3e92016-03-24 13:29:56 -0700782 long inactiveTimeoutDefault = (mHasWatch ? 15 : 30) * 60 * 1000L;
Adam Lesinski31c05d12015-06-09 17:34:04 -0700783 INACTIVE_TIMEOUT = mParser.getLong(KEY_INACTIVE_TIMEOUT,
Joe LaPenna0c5d3e92016-03-24 13:29:56 -0700784 !COMPRESS_TIME ? inactiveTimeoutDefault : (inactiveTimeoutDefault / 10));
Adam Lesinski31c05d12015-06-09 17:34:04 -0700785 SENSING_TIMEOUT = mParser.getLong(KEY_SENSING_TIMEOUT,
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700786 !DEBUG ? 4 * 60 * 1000L : 60 * 1000L);
787 LOCATING_TIMEOUT = mParser.getLong(KEY_LOCATING_TIMEOUT,
788 !DEBUG ? 30 * 1000L : 15 * 1000L);
789 LOCATION_ACCURACY = mParser.getFloat(KEY_LOCATION_ACCURACY, 20);
Adam Lesinski31c05d12015-06-09 17:34:04 -0700790 MOTION_INACTIVE_TIMEOUT = mParser.getLong(KEY_MOTION_INACTIVE_TIMEOUT,
791 !COMPRESS_TIME ? 10 * 60 * 1000L : 60 * 1000L);
Joe LaPenna0c5d3e92016-03-24 13:29:56 -0700792 long idleAfterInactiveTimeout = (mHasWatch ? 15 : 30) * 60 * 1000L;
Adam Lesinski31c05d12015-06-09 17:34:04 -0700793 IDLE_AFTER_INACTIVE_TIMEOUT = mParser.getLong(KEY_IDLE_AFTER_INACTIVE_TIMEOUT,
Joe LaPenna0c5d3e92016-03-24 13:29:56 -0700794 !COMPRESS_TIME ? idleAfterInactiveTimeout
795 : (idleAfterInactiveTimeout / 10));
Adam Lesinski31c05d12015-06-09 17:34:04 -0700796 IDLE_PENDING_TIMEOUT = mParser.getLong(KEY_IDLE_PENDING_TIMEOUT,
797 !COMPRESS_TIME ? 5 * 60 * 1000L : 30 * 1000L);
798 MAX_IDLE_PENDING_TIMEOUT = mParser.getLong(KEY_MAX_IDLE_PENDING_TIMEOUT,
799 !COMPRESS_TIME ? 10 * 60 * 1000L : 60 * 1000L);
800 IDLE_PENDING_FACTOR = mParser.getFloat(KEY_IDLE_PENDING_FACTOR,
801 2f);
802 IDLE_TIMEOUT = mParser.getLong(KEY_IDLE_TIMEOUT,
803 !COMPRESS_TIME ? 60 * 60 * 1000L : 6 * 60 * 1000L);
804 MAX_IDLE_TIMEOUT = mParser.getLong(KEY_MAX_IDLE_TIMEOUT,
805 !COMPRESS_TIME ? 6 * 60 * 60 * 1000L : 30 * 60 * 1000L);
806 IDLE_FACTOR = mParser.getFloat(KEY_IDLE_FACTOR,
807 2f);
808 MIN_TIME_TO_ALARM = mParser.getLong(KEY_MIN_TIME_TO_ALARM,
809 !COMPRESS_TIME ? 60 * 60 * 1000L : 6 * 60 * 1000L);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700810 MAX_TEMP_APP_WHITELIST_DURATION = mParser.getLong(
811 KEY_MAX_TEMP_APP_WHITELIST_DURATION, 5 * 60 * 1000L);
812 MMS_TEMP_APP_WHITELIST_DURATION = mParser.getLong(
Dianne Hackborn0b6134b2015-07-14 18:48:07 -0700813 KEY_MMS_TEMP_APP_WHITELIST_DURATION, 60 * 1000L);
Dianne Hackborn451c3462015-07-21 17:39:46 -0700814 SMS_TEMP_APP_WHITELIST_DURATION = mParser.getLong(
815 KEY_SMS_TEMP_APP_WHITELIST_DURATION, 20 * 1000L);
Adam Lesinski31c05d12015-06-09 17:34:04 -0700816 }
817 }
818
819 void dump(PrintWriter pw) {
820 pw.println(" Settings:");
821
Dianne Hackborn953fc942016-03-29 15:36:24 -0700822 pw.print(" "); pw.print(KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT); pw.print("=");
823 TimeUtils.formatDuration(LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT, pw);
824 pw.println();
825
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700826 pw.print(" "); pw.print(KEY_LIGHT_PRE_IDLE_TIMEOUT); pw.print("=");
827 TimeUtils.formatDuration(LIGHT_PRE_IDLE_TIMEOUT, pw);
828 pw.println();
829
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700830 pw.print(" "); pw.print(KEY_LIGHT_IDLE_TIMEOUT); pw.print("=");
831 TimeUtils.formatDuration(LIGHT_IDLE_TIMEOUT, pw);
832 pw.println();
833
Dianne Hackborn953fc942016-03-29 15:36:24 -0700834 pw.print(" "); pw.print(KEY_LIGHT_IDLE_FACTOR); pw.print("=");
835 pw.print(LIGHT_IDLE_FACTOR);
836 pw.println();
837
838 pw.print(" "); pw.print(KEY_LIGHT_MAX_IDLE_TIMEOUT); pw.print("=");
839 TimeUtils.formatDuration(LIGHT_MAX_IDLE_TIMEOUT, pw);
840 pw.println();
841
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800842 pw.print(" "); pw.print(KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET); pw.print("=");
843 TimeUtils.formatDuration(LIGHT_IDLE_MAINTENANCE_MIN_BUDGET, pw);
844 pw.println();
845
846 pw.print(" "); pw.print(KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET); pw.print("=");
847 TimeUtils.formatDuration(LIGHT_IDLE_MAINTENANCE_MAX_BUDGET, pw);
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700848 pw.println();
849
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700850 pw.print(" "); pw.print(KEY_MIN_LIGHT_MAINTENANCE_TIME); pw.print("=");
851 TimeUtils.formatDuration(MIN_LIGHT_MAINTENANCE_TIME, pw);
852 pw.println();
853
854 pw.print(" "); pw.print(KEY_MIN_DEEP_MAINTENANCE_TIME); pw.print("=");
855 TimeUtils.formatDuration(MIN_DEEP_MAINTENANCE_TIME, pw);
856 pw.println();
857
Dianne Hackborna750a632015-06-16 17:18:23 -0700858 pw.print(" "); pw.print(KEY_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700859 TimeUtils.formatDuration(INACTIVE_TIMEOUT, pw);
860 pw.println();
861
Dianne Hackborna750a632015-06-16 17:18:23 -0700862 pw.print(" "); pw.print(KEY_SENSING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700863 TimeUtils.formatDuration(SENSING_TIMEOUT, pw);
864 pw.println();
865
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700866 pw.print(" "); pw.print(KEY_LOCATING_TIMEOUT); pw.print("=");
867 TimeUtils.formatDuration(LOCATING_TIMEOUT, pw);
868 pw.println();
869
870 pw.print(" "); pw.print(KEY_LOCATION_ACCURACY); pw.print("=");
871 pw.print(LOCATION_ACCURACY); pw.print("m");
872 pw.println();
873
Dianne Hackborna750a632015-06-16 17:18:23 -0700874 pw.print(" "); pw.print(KEY_MOTION_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700875 TimeUtils.formatDuration(MOTION_INACTIVE_TIMEOUT, pw);
876 pw.println();
877
Dianne Hackborna750a632015-06-16 17:18:23 -0700878 pw.print(" "); pw.print(KEY_IDLE_AFTER_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700879 TimeUtils.formatDuration(IDLE_AFTER_INACTIVE_TIMEOUT, pw);
880 pw.println();
881
Dianne Hackborna750a632015-06-16 17:18:23 -0700882 pw.print(" "); pw.print(KEY_IDLE_PENDING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700883 TimeUtils.formatDuration(IDLE_PENDING_TIMEOUT, pw);
884 pw.println();
885
Dianne Hackborna750a632015-06-16 17:18:23 -0700886 pw.print(" "); pw.print(KEY_MAX_IDLE_PENDING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700887 TimeUtils.formatDuration(MAX_IDLE_PENDING_TIMEOUT, pw);
888 pw.println();
889
Dianne Hackborna750a632015-06-16 17:18:23 -0700890 pw.print(" "); pw.print(KEY_IDLE_PENDING_FACTOR); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700891 pw.println(IDLE_PENDING_FACTOR);
892
Dianne Hackborna750a632015-06-16 17:18:23 -0700893 pw.print(" "); pw.print(KEY_IDLE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700894 TimeUtils.formatDuration(IDLE_TIMEOUT, pw);
895 pw.println();
896
Dianne Hackborna750a632015-06-16 17:18:23 -0700897 pw.print(" "); pw.print(KEY_MAX_IDLE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700898 TimeUtils.formatDuration(MAX_IDLE_TIMEOUT, pw);
899 pw.println();
900
Dianne Hackborna750a632015-06-16 17:18:23 -0700901 pw.print(" "); pw.print(KEY_IDLE_FACTOR); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700902 pw.println(IDLE_FACTOR);
903
Dianne Hackborna750a632015-06-16 17:18:23 -0700904 pw.print(" "); pw.print(KEY_MIN_TIME_TO_ALARM); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700905 TimeUtils.formatDuration(MIN_TIME_TO_ALARM, pw);
906 pw.println();
907
Dianne Hackborna750a632015-06-16 17:18:23 -0700908 pw.print(" "); pw.print(KEY_MAX_TEMP_APP_WHITELIST_DURATION); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700909 TimeUtils.formatDuration(MAX_TEMP_APP_WHITELIST_DURATION, pw);
910 pw.println();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700911
912 pw.print(" "); pw.print(KEY_MMS_TEMP_APP_WHITELIST_DURATION); pw.print("=");
913 TimeUtils.formatDuration(MMS_TEMP_APP_WHITELIST_DURATION, pw);
914 pw.println();
Dianne Hackborn451c3462015-07-21 17:39:46 -0700915
916 pw.print(" "); pw.print(KEY_SMS_TEMP_APP_WHITELIST_DURATION); pw.print("=");
917 TimeUtils.formatDuration(SMS_TEMP_APP_WHITELIST_DURATION, pw);
918 pw.println();
Adam Lesinski31c05d12015-06-09 17:34:04 -0700919 }
920 }
921
922 private Constants mConstants;
923
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700924 @Override
925 public void onAnyMotionResult(int result) {
926 if (DEBUG) Slog.d(TAG, "onAnyMotionResult(" + result + ")");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700927 if (result == AnyMotionDetector.RESULT_MOVED) {
928 if (DEBUG) Slog.d(TAG, "RESULT_MOVED received.");
929 synchronized (this) {
930 handleMotionDetectedLocked(mConstants.INACTIVE_TIMEOUT, "sense_motion");
931 }
932 } else if (result == AnyMotionDetector.RESULT_STATIONARY) {
933 if (DEBUG) Slog.d(TAG, "RESULT_STATIONARY received.");
934 if (mState == STATE_SENSING) {
935 // If we are currently sensing, it is time to move to locating.
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700936 synchronized (this) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700937 mNotMoving = true;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800938 stepIdleStateLocked("s:stationary");
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700939 }
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700940 } else if (mState == STATE_LOCATING) {
941 // If we are currently locating, note that we are not moving and step
942 // if we have located the position.
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700943 synchronized (this) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700944 mNotMoving = true;
945 if (mLocated) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800946 stepIdleStateLocked("s:stationary");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700947 }
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700948 }
949 }
950 }
951 }
952
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700953 static final int MSG_WRITE_CONFIG = 1;
954 static final int MSG_REPORT_IDLE_ON = 2;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700955 static final int MSG_REPORT_IDLE_ON_LIGHT = 3;
956 static final int MSG_REPORT_IDLE_OFF = 4;
957 static final int MSG_REPORT_ACTIVE = 5;
958 static final int MSG_TEMP_APP_WHITELIST_TIMEOUT = 6;
Yao Chenca5edbb2016-01-13 14:44:36 -0800959 static final int MSG_REPORT_MAINTENANCE_ACTIVITY = 7;
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700960 static final int MSG_FINISH_IDLE_OP = 8;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700961
962 final class MyHandler extends Handler {
963 MyHandler(Looper looper) {
964 super(looper);
965 }
966
967 @Override public void handleMessage(Message msg) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700968 if (DEBUG) Slog.d(TAG, "handleMessage(" + msg.what + ")");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700969 switch (msg.what) {
970 case MSG_WRITE_CONFIG: {
971 handleWriteConfigFile();
972 } break;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700973 case MSG_REPORT_IDLE_ON:
974 case MSG_REPORT_IDLE_ON_LIGHT: {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700975 EventLogTags.writeDeviceIdleOnStart();
Dianne Hackbornb6843652016-02-22 12:20:13 -0800976 final boolean deepChanged;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700977 final boolean lightChanged;
978 if (msg.what == MSG_REPORT_IDLE_ON) {
Dianne Hackbornb6843652016-02-22 12:20:13 -0800979 deepChanged = mLocalPowerManager.setDeviceIdleMode(true);
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700980 lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
981 } else {
Dianne Hackbornb6843652016-02-22 12:20:13 -0800982 deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700983 lightChanged = mLocalPowerManager.setLightDeviceIdleMode(true);
984 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700985 try {
986 mNetworkPolicyManager.setDeviceIdleMode(true);
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700987 mBatteryStats.noteDeviceIdleMode(msg.what == MSG_REPORT_IDLE_ON
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700988 ? BatteryStats.DEVICE_IDLE_MODE_DEEP
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700989 : BatteryStats.DEVICE_IDLE_MODE_LIGHT, null, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700990 } catch (RemoteException e) {
991 }
Dianne Hackbornb6843652016-02-22 12:20:13 -0800992 if (deepChanged) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700993 getContext().sendBroadcastAsUser(mIdleIntent, UserHandle.ALL);
994 }
995 if (lightChanged) {
996 getContext().sendBroadcastAsUser(mLightIdleIntent, UserHandle.ALL);
997 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700998 EventLogTags.writeDeviceIdleOnComplete();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700999 } break;
1000 case MSG_REPORT_IDLE_OFF: {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001001 EventLogTags.writeDeviceIdleOffStart("unknown");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001002 final boolean deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001003 final boolean lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001004 try {
1005 mNetworkPolicyManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001006 mBatteryStats.noteDeviceIdleMode(BatteryStats.DEVICE_IDLE_MODE_OFF,
1007 null, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001008 } catch (RemoteException e) {
1009 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001010 if (deepChanged) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001011 incActiveIdleOps();
1012 getContext().sendOrderedBroadcastAsUser(mIdleIntent, UserHandle.ALL,
1013 null, mIdleStartedDoneReceiver, null, 0, null, null);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001014 }
1015 if (lightChanged) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001016 incActiveIdleOps();
1017 getContext().sendOrderedBroadcastAsUser(mLightIdleIntent, UserHandle.ALL,
1018 null, mIdleStartedDoneReceiver, null, 0, null, null);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001019 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001020 // Always start with one active op for the message being sent here.
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001021 // Now we are done!
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001022 decActiveIdleOps();
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001023 EventLogTags.writeDeviceIdleOffComplete();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001024 } break;
1025 case MSG_REPORT_ACTIVE: {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001026 String activeReason = (String)msg.obj;
1027 int activeUid = msg.arg1;
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001028 EventLogTags.writeDeviceIdleOffStart(
1029 activeReason != null ? activeReason : "unknown");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001030 final boolean deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001031 final boolean lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001032 try {
1033 mNetworkPolicyManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001034 mBatteryStats.noteDeviceIdleMode(BatteryStats.DEVICE_IDLE_MODE_OFF,
1035 activeReason, activeUid);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001036 } catch (RemoteException e) {
1037 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001038 if (deepChanged) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001039 getContext().sendBroadcastAsUser(mIdleIntent, UserHandle.ALL);
1040 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001041 if (lightChanged) {
1042 getContext().sendBroadcastAsUser(mLightIdleIntent, UserHandle.ALL);
1043 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001044 EventLogTags.writeDeviceIdleOffComplete();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001045 } break;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001046 case MSG_TEMP_APP_WHITELIST_TIMEOUT: {
1047 int uid = msg.arg1;
1048 checkTempAppWhitelistTimeout(uid);
1049 } break;
Yao Chenca5edbb2016-01-13 14:44:36 -08001050 case MSG_REPORT_MAINTENANCE_ACTIVITY: {
1051 boolean active = (msg.arg1 == 1);
1052 final int size = mMaintenanceActivityListeners.beginBroadcast();
1053 try {
1054 for (int i = 0; i < size; i++) {
1055 try {
1056 mMaintenanceActivityListeners.getBroadcastItem(i)
1057 .onMaintenanceActivityChanged(active);
1058 } catch (RemoteException ignored) {
1059 }
1060 }
1061 } finally {
1062 mMaintenanceActivityListeners.finishBroadcast();
1063 }
1064 } break;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001065 case MSG_FINISH_IDLE_OP: {
1066 decActiveIdleOps();
1067 } break;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001068 }
1069 }
1070 }
1071
1072 final MyHandler mHandler;
1073
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001074 BinderService mBinderService;
1075
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001076 private final class BinderService extends IDeviceIdleController.Stub {
1077 @Override public void addPowerSaveWhitelistApp(String name) {
1078 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1079 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001080 long ident = Binder.clearCallingIdentity();
1081 try {
1082 addPowerSaveWhitelistAppInternal(name);
1083 } finally {
1084 Binder.restoreCallingIdentity(ident);
1085 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001086 }
1087
1088 @Override public void removePowerSaveWhitelistApp(String name) {
1089 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1090 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001091 long ident = Binder.clearCallingIdentity();
1092 try {
1093 removePowerSaveWhitelistAppInternal(name);
1094 } finally {
1095 Binder.restoreCallingIdentity(ident);
1096 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001097 }
1098
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001099 @Override public String[] getSystemPowerWhitelistExceptIdle() {
1100 return getSystemPowerWhitelistExceptIdleInternal();
1101 }
1102
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001103 @Override public String[] getSystemPowerWhitelist() {
1104 return getSystemPowerWhitelistInternal();
1105 }
1106
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001107 @Override public String[] getUserPowerWhitelist() {
1108 return getUserPowerWhitelistInternal();
1109 }
1110
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001111 @Override public String[] getFullPowerWhitelistExceptIdle() {
1112 return getFullPowerWhitelistExceptIdleInternal();
1113 }
1114
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001115 @Override public String[] getFullPowerWhitelist() {
1116 return getFullPowerWhitelistInternal();
1117 }
1118
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001119 @Override public int[] getAppIdWhitelistExceptIdle() {
1120 return getAppIdWhitelistExceptIdleInternal();
1121 }
1122
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001123 @Override public int[] getAppIdWhitelist() {
1124 return getAppIdWhitelistInternal();
1125 }
1126
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001127 @Override public int[] getAppIdUserWhitelist() {
1128 return getAppIdUserWhitelistInternal();
1129 }
1130
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001131 @Override public int[] getAppIdTempWhitelist() {
1132 return getAppIdTempWhitelistInternal();
1133 }
1134
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001135 @Override public boolean isPowerSaveWhitelistExceptIdleApp(String name) {
1136 return isPowerSaveWhitelistExceptIdleAppInternal(name);
1137 }
1138
Amith Yamasani06bf8242015-05-08 16:36:21 -07001139 @Override public boolean isPowerSaveWhitelistApp(String name) {
1140 return isPowerSaveWhitelistAppInternal(name);
1141 }
1142
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001143 @Override public void addPowerSaveTempWhitelistApp(String packageName, long duration,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001144 int userId, String reason) throws RemoteException {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001145 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001146 }
1147
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001148 @Override public long addPowerSaveTempWhitelistAppForMms(String packageName,
1149 int userId, String reason) throws RemoteException {
1150 long duration = mConstants.MMS_TEMP_APP_WHITELIST_DURATION;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001151 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001152 return duration;
1153 }
1154
Dianne Hackborn451c3462015-07-21 17:39:46 -07001155 @Override public long addPowerSaveTempWhitelistAppForSms(String packageName,
1156 int userId, String reason) throws RemoteException {
1157 long duration = mConstants.SMS_TEMP_APP_WHITELIST_DURATION;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001158 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Dianne Hackborn451c3462015-07-21 17:39:46 -07001159 return duration;
1160 }
1161
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001162 @Override public void exitIdle(String reason) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001163 getContext().enforceCallingOrSelfPermission(Manifest.permission.DEVICE_POWER,
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001164 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001165 long ident = Binder.clearCallingIdentity();
1166 try {
1167 exitIdleInternal(reason);
1168 } finally {
1169 Binder.restoreCallingIdentity(ident);
1170 }
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001171 }
1172
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001173 @Override public void downloadServiceActive(IBinder token) {
1174 getContext().enforceCallingOrSelfPermission(
1175 "android.permission.SEND_DOWNLOAD_COMPLETED_INTENTS", null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001176 long ident = Binder.clearCallingIdentity();
1177 try {
1178 DeviceIdleController.this.downloadServiceActive(token);
1179 } finally {
1180 Binder.restoreCallingIdentity(ident);
1181 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001182 }
1183
1184 @Override public void downloadServiceInactive() {
1185 getContext().enforceCallingOrSelfPermission(
1186 "android.permission.SEND_DOWNLOAD_COMPLETED_INTENTS", null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001187 long ident = Binder.clearCallingIdentity();
1188 try {
1189 DeviceIdleController.this.downloadServiceInactive();
1190 } finally {
1191 Binder.restoreCallingIdentity(ident);
1192 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001193 }
1194
Yao Chenca5edbb2016-01-13 14:44:36 -08001195 @Override public boolean registerMaintenanceActivityListener(
1196 IMaintenanceActivityListener listener) {
1197 return DeviceIdleController.this.registerMaintenanceActivityListener(listener);
1198 }
1199
1200 @Override public void unregisterMaintenanceActivityListener(
1201 IMaintenanceActivityListener listener) {
1202 DeviceIdleController.this.unregisterMaintenanceActivityListener(listener);
1203 }
1204
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001205 @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1206 DeviceIdleController.this.dump(fd, pw, args);
1207 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001208
1209 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
1210 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
1211 (new Shell()).exec(this, in, out, err, args, resultReceiver);
1212 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001213 }
1214
Dianne Hackborna750a632015-06-16 17:18:23 -07001215 public final class LocalService {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001216 public void addPowerSaveTempWhitelistAppDirect(int appId, long duration, boolean sync,
1217 String reason) {
1218 addPowerSaveTempWhitelistAppDirectInternal(0, appId, duration, sync, reason);
1219 }
1220
1221 public void setNetworkPolicyTempWhitelistCallback(Runnable callback) {
1222 setNetworkPolicyTempWhitelistCallbackInternal(callback);
Dianne Hackborna750a632015-06-16 17:18:23 -07001223 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001224
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001225 public void setJobsActive(boolean active) {
1226 DeviceIdleController.this.setJobsActive(active);
1227 }
1228
1229 // Up-call from alarm manager.
1230 public void setAlarmsActive(boolean active) {
1231 DeviceIdleController.this.setAlarmsActive(active);
1232 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001233
1234 /**
1235 * Returns the array of app ids whitelisted by user. Take care not to
1236 * modify this, as it is a reference to the original copy. But the reference
1237 * can change when the list changes, so it needs to be re-acquired when
1238 * {@link PowerManager#ACTION_POWER_SAVE_WHITELIST_CHANGED} is sent.
1239 */
1240 public int[] getPowerSaveWhitelistUserAppIds() {
1241 return DeviceIdleController.this.getPowerSaveWhitelistUserAppIds();
1242 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001243 }
1244
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001245 public DeviceIdleController(Context context) {
1246 super(context);
1247 mConfigFile = new AtomicFile(new File(getSystemDir(), "deviceidle.xml"));
1248 mHandler = new MyHandler(BackgroundThread.getHandler().getLooper());
1249 }
1250
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001251 int[] getPowerSaveWhitelistUserAppIds() {
1252 synchronized (this) {
1253 return mPowerSaveWhitelistUserAppIdArray;
1254 }
1255 }
1256
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001257 private static File getSystemDir() {
1258 return new File(Environment.getDataDirectory(), "system");
1259 }
1260
1261 @Override
1262 public void onStart() {
1263 final PackageManager pm = getContext().getPackageManager();
1264
1265 synchronized (this) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001266 mLightEnabled = mDeepEnabled = getContext().getResources().getBoolean(
Dianne Hackborn92617032015-06-19 15:32:19 -07001267 com.android.internal.R.bool.config_enableAutoPowerModes);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001268 SystemConfig sysConfig = SystemConfig.getInstance();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001269 ArraySet<String> allowPowerExceptIdle = sysConfig.getAllowInPowerSaveExceptIdle();
1270 for (int i=0; i<allowPowerExceptIdle.size(); i++) {
1271 String pkg = allowPowerExceptIdle.valueAt(i);
1272 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001273 ApplicationInfo ai = pm.getApplicationInfo(pkg,
1274 PackageManager.MATCH_SYSTEM_ONLY);
1275 int appid = UserHandle.getAppId(ai.uid);
1276 mPowerSaveWhitelistAppsExceptIdle.put(ai.packageName, appid);
1277 mPowerSaveWhitelistSystemAppIdsExceptIdle.put(appid, true);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001278 } catch (PackageManager.NameNotFoundException e) {
1279 }
1280 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001281 ArraySet<String> allowPower = sysConfig.getAllowInPowerSave();
1282 for (int i=0; i<allowPower.size(); i++) {
1283 String pkg = allowPower.valueAt(i);
1284 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001285 ApplicationInfo ai = pm.getApplicationInfo(pkg,
1286 PackageManager.MATCH_SYSTEM_ONLY);
1287 int appid = UserHandle.getAppId(ai.uid);
1288 // These apps are on both the whitelist-except-idle as well
1289 // as the full whitelist, so they apply in all cases.
1290 mPowerSaveWhitelistAppsExceptIdle.put(ai.packageName, appid);
1291 mPowerSaveWhitelistSystemAppIdsExceptIdle.put(appid, true);
1292 mPowerSaveWhitelistApps.put(ai.packageName, appid);
1293 mPowerSaveWhitelistSystemAppIds.put(appid, true);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001294 } catch (PackageManager.NameNotFoundException e) {
1295 }
1296 }
1297
Adam Lesinski31c05d12015-06-09 17:34:04 -07001298 mConstants = new Constants(mHandler, getContext().getContentResolver());
1299
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001300 readConfigFileLocked();
1301 updateWhitelistAppIdsLocked();
1302
1303 mScreenOn = true;
1304 // Start out assuming we are charging. If we aren't, we will at least get
1305 // a battery update the next time the level drops.
1306 mCharging = true;
1307 mState = STATE_ACTIVE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001308 mLightState = LIGHT_STATE_ACTIVE;
Adam Lesinski31c05d12015-06-09 17:34:04 -07001309 mInactiveTimeout = mConstants.INACTIVE_TIMEOUT;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001310 }
1311
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001312 mBinderService = new BinderService();
1313 publishBinderService(Context.DEVICE_IDLE_CONTROLLER, mBinderService);
Dianne Hackborna750a632015-06-16 17:18:23 -07001314 publishLocalService(LocalService.class, new LocalService());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001315 }
1316
1317 @Override
1318 public void onBootPhase(int phase) {
1319 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1320 synchronized (this) {
1321 mAlarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
1322 mBatteryStats = BatteryStatsService.getService();
1323 mLocalPowerManager = getLocalService(PowerManagerInternal.class);
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001324 mPowerManager = getContext().getSystemService(PowerManager.class);
1325 mActiveIdleWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
1326 "deviceidle_maint");
1327 mActiveIdleWakeLock.setReferenceCounted(false);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001328 mLocalAlarmManager = getLocalService(AlarmManagerService.LocalService.class);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001329 mNetworkPolicyManager = INetworkPolicyManager.Stub.asInterface(
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001330 ServiceManager.getService(Context.NETWORK_POLICY_SERVICE));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001331 mDisplayManager = (DisplayManager) getContext().getSystemService(
1332 Context.DISPLAY_SERVICE);
1333 mSensorManager = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001334 int sigMotionSensorId = getContext().getResources().getInteger(
1335 com.android.internal.R.integer.config_autoPowerModeAnyMotionSensor);
1336 if (sigMotionSensorId > 0) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001337 mMotionSensor = mSensorManager.getDefaultSensor(sigMotionSensorId, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001338 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001339 if (mMotionSensor == null && getContext().getResources().getBoolean(
Joe LaPenna23d681b2015-08-27 15:12:11 -07001340 com.android.internal.R.bool.config_autoPowerModePreferWristTilt)) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001341 mMotionSensor = mSensorManager.getDefaultSensor(
1342 Sensor.TYPE_WRIST_TILT_GESTURE, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001343 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001344 if (mMotionSensor == null) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07001345 // As a last ditch, fall back to SMD.
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001346 mMotionSensor = mSensorManager.getDefaultSensor(
1347 Sensor.TYPE_SIGNIFICANT_MOTION, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001348 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001349
Joe LaPenna23d681b2015-08-27 15:12:11 -07001350 if (getContext().getResources().getBoolean(
1351 com.android.internal.R.bool.config_autoPowerModePrefetchLocation)) {
1352 mLocationManager = (LocationManager) getContext().getSystemService(
1353 Context.LOCATION_SERVICE);
1354 mLocationRequest = new LocationRequest()
1355 .setQuality(LocationRequest.ACCURACY_FINE)
1356 .setInterval(0)
1357 .setFastestInterval(0)
1358 .setNumUpdates(1);
1359 }
1360
1361 float angleThreshold = getContext().getResources().getInteger(
1362 com.android.internal.R.integer.config_autoPowerModeThresholdAngle) / 100f;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001363 mAnyMotionDetector = new AnyMotionDetector(
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001364 (PowerManager) getContext().getSystemService(Context.POWER_SERVICE),
Joe LaPenna23d681b2015-08-27 15:12:11 -07001365 mHandler, mSensorManager, this, angleThreshold);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001366
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001367 mIdleIntent = new Intent(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001368 mIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1369 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001370 mLightIdleIntent = new Intent(PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED);
1371 mLightIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1372 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001373
1374 IntentFilter filter = new IntentFilter();
1375 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001376 getContext().registerReceiver(mReceiver, filter);
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001377 filter = new IntentFilter();
1378 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1379 filter.addDataScheme("package");
1380 getContext().registerReceiver(mReceiver, filter);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001381
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001382 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001383 mLocalAlarmManager.setDeviceIdleUserWhitelist(mPowerSaveWhitelistUserAppIdArray);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001384 mDisplayManager.registerDisplayListener(mDisplayListener, null);
1385 updateDisplayLocked();
1386 }
1387 }
1388 }
1389
1390 public boolean addPowerSaveWhitelistAppInternal(String name) {
1391 synchronized (this) {
1392 try {
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001393 ApplicationInfo ai = getContext().getPackageManager().getApplicationInfo(name,
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001394 PackageManager.MATCH_UNINSTALLED_PACKAGES);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001395 if (mPowerSaveWhitelistUserApps.put(name, UserHandle.getAppId(ai.uid)) == null) {
1396 reportPowerSaveWhitelistChangedLocked();
1397 updateWhitelistAppIdsLocked();
1398 writeConfigFileLocked();
1399 }
1400 return true;
1401 } catch (PackageManager.NameNotFoundException e) {
1402 return false;
1403 }
1404 }
1405 }
1406
1407 public boolean removePowerSaveWhitelistAppInternal(String name) {
1408 synchronized (this) {
1409 if (mPowerSaveWhitelistUserApps.remove(name) != null) {
1410 reportPowerSaveWhitelistChangedLocked();
1411 updateWhitelistAppIdsLocked();
1412 writeConfigFileLocked();
1413 return true;
1414 }
1415 }
1416 return false;
1417 }
1418
Felipe Lemef8a46232016-02-10 13:51:54 -08001419 public boolean getPowerSaveWhitelistAppInternal(String name) {
1420 synchronized (this) {
1421 return mPowerSaveWhitelistUserApps.containsKey(name);
1422 }
1423 }
1424
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001425 public String[] getSystemPowerWhitelistExceptIdleInternal() {
1426 synchronized (this) {
1427 int size = mPowerSaveWhitelistAppsExceptIdle.size();
1428 String[] apps = new String[size];
1429 for (int i = 0; i < size; i++) {
1430 apps[i] = mPowerSaveWhitelistAppsExceptIdle.keyAt(i);
1431 }
1432 return apps;
1433 }
1434 }
1435
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001436 public String[] getSystemPowerWhitelistInternal() {
1437 synchronized (this) {
1438 int size = mPowerSaveWhitelistApps.size();
1439 String[] apps = new String[size];
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001440 for (int i = 0; i < size; i++) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001441 apps[i] = mPowerSaveWhitelistApps.keyAt(i);
1442 }
1443 return apps;
1444 }
1445 }
1446
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001447 public String[] getUserPowerWhitelistInternal() {
1448 synchronized (this) {
1449 int size = mPowerSaveWhitelistUserApps.size();
1450 String[] apps = new String[size];
1451 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1452 apps[i] = mPowerSaveWhitelistUserApps.keyAt(i);
1453 }
1454 return apps;
1455 }
1456 }
1457
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001458 public String[] getFullPowerWhitelistExceptIdleInternal() {
1459 synchronized (this) {
1460 int size = mPowerSaveWhitelistAppsExceptIdle.size() + mPowerSaveWhitelistUserApps.size();
1461 String[] apps = new String[size];
1462 int cur = 0;
1463 for (int i = 0; i < mPowerSaveWhitelistAppsExceptIdle.size(); i++) {
1464 apps[cur] = mPowerSaveWhitelistAppsExceptIdle.keyAt(i);
1465 cur++;
1466 }
1467 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1468 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
1469 cur++;
1470 }
1471 return apps;
1472 }
1473 }
1474
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001475 public String[] getFullPowerWhitelistInternal() {
1476 synchronized (this) {
1477 int size = mPowerSaveWhitelistApps.size() + mPowerSaveWhitelistUserApps.size();
1478 String[] apps = new String[size];
1479 int cur = 0;
1480 for (int i = 0; i < mPowerSaveWhitelistApps.size(); i++) {
1481 apps[cur] = mPowerSaveWhitelistApps.keyAt(i);
1482 cur++;
1483 }
1484 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1485 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
1486 cur++;
1487 }
1488 return apps;
1489 }
1490 }
1491
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001492 public boolean isPowerSaveWhitelistExceptIdleAppInternal(String packageName) {
1493 synchronized (this) {
1494 return mPowerSaveWhitelistAppsExceptIdle.containsKey(packageName)
1495 || mPowerSaveWhitelistUserApps.containsKey(packageName);
1496 }
1497 }
1498
Amith Yamasani06bf8242015-05-08 16:36:21 -07001499 public boolean isPowerSaveWhitelistAppInternal(String packageName) {
1500 synchronized (this) {
1501 return mPowerSaveWhitelistApps.containsKey(packageName)
1502 || mPowerSaveWhitelistUserApps.containsKey(packageName);
1503 }
1504 }
1505
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001506 public int[] getAppIdWhitelistExceptIdleInternal() {
1507 synchronized (this) {
1508 return mPowerSaveWhitelistExceptIdleAppIdArray;
1509 }
1510 }
1511
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001512 public int[] getAppIdWhitelistInternal() {
1513 synchronized (this) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001514 return mPowerSaveWhitelistAllAppIdArray;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001515 }
1516 }
1517
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001518 public int[] getAppIdUserWhitelistInternal() {
1519 synchronized (this) {
1520 return mPowerSaveWhitelistUserAppIdArray;
1521 }
1522 }
1523
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001524 public int[] getAppIdTempWhitelistInternal() {
1525 synchronized (this) {
1526 return mTempWhitelistAppIdArray;
1527 }
1528 }
1529
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001530 void addPowerSaveTempWhitelistAppChecked(String packageName, long duration,
1531 int userId, String reason) throws RemoteException {
1532 getContext().enforceCallingPermission(
1533 Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
1534 "No permission to change device idle whitelist");
1535 final int callingUid = Binder.getCallingUid();
1536 userId = ActivityManagerNative.getDefault().handleIncomingUser(
1537 Binder.getCallingPid(),
1538 callingUid,
1539 userId,
1540 /*allowAll=*/ false,
1541 /*requireFull=*/ false,
1542 "addPowerSaveTempWhitelistApp", null);
1543 final long token = Binder.clearCallingIdentity();
1544 try {
1545 addPowerSaveTempWhitelistAppInternal(callingUid,
1546 packageName, duration, userId, true, reason);
1547 } finally {
1548 Binder.restoreCallingIdentity(token);
1549 }
1550 }
1551
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001552 /**
1553 * Adds an app to the temporary whitelist and resets the endTime for granting the
1554 * app an exemption to access network and acquire wakelocks.
1555 */
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001556 void addPowerSaveTempWhitelistAppInternal(int callingUid, String packageName,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001557 long duration, int userId, boolean sync, String reason) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001558 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001559 int uid = getContext().getPackageManager().getPackageUidAsUser(packageName, userId);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001560 int appId = UserHandle.getAppId(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001561 addPowerSaveTempWhitelistAppDirectInternal(callingUid, appId, duration, sync, reason);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001562 } catch (NameNotFoundException e) {
1563 }
1564 }
1565
Dianne Hackborna750a632015-06-16 17:18:23 -07001566 /**
1567 * Adds an app to the temporary whitelist and resets the endTime for granting the
1568 * app an exemption to access network and acquire wakelocks.
1569 */
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001570 void addPowerSaveTempWhitelistAppDirectInternal(int callingUid, int appId,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001571 long duration, boolean sync, String reason) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001572 final long timeNow = SystemClock.elapsedRealtime();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001573 Runnable networkPolicyTempWhitelistCallback = null;
Dianne Hackborna750a632015-06-16 17:18:23 -07001574 synchronized (this) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001575 int callingAppId = UserHandle.getAppId(callingUid);
1576 if (callingAppId >= Process.FIRST_APPLICATION_UID) {
1577 if (!mPowerSaveWhitelistSystemAppIds.get(callingAppId)) {
1578 throw new SecurityException("Calling app " + UserHandle.formatUid(callingUid)
1579 + " is not on whitelist");
1580 }
1581 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001582 duration = Math.min(duration, mConstants.MAX_TEMP_APP_WHITELIST_DURATION);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001583 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.get(appId);
1584 final boolean newEntry = entry == null;
Dianne Hackborna750a632015-06-16 17:18:23 -07001585 // Set the new end time
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001586 if (newEntry) {
1587 entry = new Pair<>(new MutableLong(0), reason);
1588 mTempWhitelistAppIdEndTimes.put(appId, entry);
1589 }
1590 entry.first.value = timeNow + duration;
Dianne Hackborna750a632015-06-16 17:18:23 -07001591 if (DEBUG) {
1592 Slog.d(TAG, "Adding AppId " + appId + " to temp whitelist");
1593 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001594 if (newEntry) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001595 // No pending timeout for the app id, post a delayed message
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001596 try {
1597 mBatteryStats.noteEvent(BatteryStats.HistoryItem.EVENT_TEMP_WHITELIST_START,
1598 reason, appId);
1599 } catch (RemoteException e) {
1600 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001601 postTempActiveTimeoutMessage(appId, duration);
1602 updateTempWhitelistAppIdsLocked();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001603 if (mNetworkPolicyTempWhitelistCallback != null) {
1604 if (!sync) {
1605 mHandler.post(mNetworkPolicyTempWhitelistCallback);
1606 } else {
1607 networkPolicyTempWhitelistCallback = mNetworkPolicyTempWhitelistCallback;
1608 }
1609 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001610 reportTempWhitelistChangedLocked();
1611 }
1612 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001613 if (networkPolicyTempWhitelistCallback != null) {
1614 networkPolicyTempWhitelistCallback.run();
1615 }
1616 }
1617
1618 public void setNetworkPolicyTempWhitelistCallbackInternal(Runnable callback) {
1619 synchronized (this) {
1620 mNetworkPolicyTempWhitelistCallback = callback;
1621 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001622 }
1623
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001624 private void postTempActiveTimeoutMessage(int uid, long delay) {
1625 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_TEMP_APP_WHITELIST_TIMEOUT, uid, 0),
1626 delay);
1627 }
1628
1629 void checkTempAppWhitelistTimeout(int uid) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001630 final long timeNow = SystemClock.elapsedRealtime();
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001631 synchronized (this) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001632 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.get(uid);
1633 if (entry == null) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001634 // Nothing to do
1635 return;
1636 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001637 if (timeNow >= entry.first.value) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001638 mTempWhitelistAppIdEndTimes.delete(uid);
1639 if (DEBUG) {
1640 Slog.d(TAG, "Removing UID " + uid + " from temp whitelist");
1641 }
1642 updateTempWhitelistAppIdsLocked();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001643 if (mNetworkPolicyTempWhitelistCallback != null) {
1644 mHandler.post(mNetworkPolicyTempWhitelistCallback);
1645 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001646 reportTempWhitelistChangedLocked();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001647 try {
1648 mBatteryStats.noteEvent(BatteryStats.HistoryItem.EVENT_TEMP_WHITELIST_FINISH,
1649 entry.second, uid);
1650 } catch (RemoteException e) {
1651 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001652 } else {
1653 // Need more time
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001654 postTempActiveTimeoutMessage(uid, entry.first.value - timeNow);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001655 }
1656 }
1657 }
1658
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001659 public void exitIdleInternal(String reason) {
1660 synchronized (this) {
1661 becomeActiveLocked(reason, Binder.getCallingUid());
1662 }
1663 }
1664
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001665 void updateDisplayLocked() {
1666 mCurDisplay = mDisplayManager.getDisplay(Display.DEFAULT_DISPLAY);
1667 // We consider any situation where the display is showing something to be it on,
1668 // because if there is anything shown we are going to be updating it at some
1669 // frequency so can't be allowed to go into deep sleeps.
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001670 boolean screenOn = mCurDisplay.getState() == Display.STATE_ON;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001671 if (DEBUG) Slog.d(TAG, "updateDisplayLocked: screenOn=" + screenOn);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001672 if (!screenOn && mScreenOn) {
1673 mScreenOn = false;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001674 if (!mForceIdle) {
1675 becomeInactiveIfAppropriateLocked();
1676 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001677 } else if (screenOn) {
1678 mScreenOn = true;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001679 if (!mForceIdle) {
1680 becomeActiveLocked("screen", Process.myUid());
1681 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001682 }
1683 }
1684
1685 void updateChargingLocked(boolean charging) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001686 if (DEBUG) Slog.i(TAG, "updateChargingLocked: charging=" + charging);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001687 if (!charging && mCharging) {
1688 mCharging = false;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001689 if (!mForceIdle) {
1690 becomeInactiveIfAppropriateLocked();
1691 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001692 } else if (charging) {
1693 mCharging = charging;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001694 if (!mForceIdle) {
1695 becomeActiveLocked("charging", Process.myUid());
1696 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001697 }
1698 }
1699
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001700 void scheduleReportActiveLocked(String activeReason, int activeUid) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001701 Message msg = mHandler.obtainMessage(MSG_REPORT_ACTIVE, activeUid, 0, activeReason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001702 mHandler.sendMessage(msg);
1703 }
1704
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001705 void becomeActiveLocked(String activeReason, int activeUid) {
1706 if (DEBUG) Slog.i(TAG, "becomeActiveLocked, reason = " + activeReason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001707 if (mState != STATE_ACTIVE || mLightState != STATE_ACTIVE) {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001708 EventLogTags.writeDeviceIdle(STATE_ACTIVE, activeReason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001709 EventLogTags.writeDeviceIdleLight(LIGHT_STATE_ACTIVE, activeReason);
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001710 scheduleReportActiveLocked(activeReason, activeUid);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001711 mState = STATE_ACTIVE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001712 mLightState = LIGHT_STATE_ACTIVE;
Adam Lesinski31c05d12015-06-09 17:34:04 -07001713 mInactiveTimeout = mConstants.INACTIVE_TIMEOUT;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001714 mCurIdleBudget = 0;
1715 mMaintenanceStartTime = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001716 resetIdleManagementLocked();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001717 resetLightIdleManagementLocked();
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001718 addEvent(EVENT_NORMAL);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001719 }
1720 }
1721
1722 void becomeInactiveIfAppropriateLocked() {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001723 if (DEBUG) Slog.d(TAG, "becomeInactiveIfAppropriateLocked()");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001724 if ((!mScreenOn && !mCharging) || mForceIdle) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001725 // Screen has turned off; we are now going to become inactive and start
1726 // waiting to see if we will ultimately go idle.
Dianne Hackbornb6843652016-02-22 12:20:13 -08001727 if (mState == STATE_ACTIVE && mDeepEnabled) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001728 mState = STATE_INACTIVE;
1729 if (DEBUG) Slog.d(TAG, "Moved from STATE_ACTIVE to STATE_INACTIVE");
1730 resetIdleManagementLocked();
1731 scheduleAlarmLocked(mInactiveTimeout, false);
1732 EventLogTags.writeDeviceIdle(mState, "no activity");
1733 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001734 if (mLightState == LIGHT_STATE_ACTIVE && mLightEnabled) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001735 mLightState = LIGHT_STATE_INACTIVE;
1736 if (DEBUG) Slog.d(TAG, "Moved from LIGHT_STATE_ACTIVE to LIGHT_STATE_INACTIVE");
1737 resetLightIdleManagementLocked();
Dianne Hackborn953fc942016-03-29 15:36:24 -07001738 scheduleLightAlarmLocked(mConstants.LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001739 EventLogTags.writeDeviceIdleLight(mLightState, "no activity");
1740 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001741 }
1742 }
1743
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001744 void resetIdleManagementLocked() {
1745 mNextIdlePendingDelay = 0;
1746 mNextIdleDelay = 0;
Dianne Hackborn953fc942016-03-29 15:36:24 -07001747 mNextLightIdleDelay = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001748 cancelAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001749 cancelLocatingLocked();
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001750 stopMonitoringMotionLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001751 mAnyMotionDetector.stop();
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001752 }
1753
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001754 void resetLightIdleManagementLocked() {
1755 cancelLightAlarmLocked();
1756 }
1757
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001758 void exitForceIdleLocked() {
1759 if (mForceIdle) {
1760 mForceIdle = false;
1761 if (mScreenOn || mCharging) {
1762 becomeActiveLocked("exit-force-idle", Process.myUid());
1763 }
1764 }
1765 }
1766
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001767 void stepLightIdleStateLocked(String reason) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001768 if (mLightState == LIGHT_STATE_OVERRIDE) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001769 // If we are already in deep device idle mode, then
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001770 // there is nothing left to do for light mode.
1771 return;
1772 }
1773
1774 if (DEBUG) Slog.d(TAG, "stepLightIdleStateLocked: mLightState=" + mLightState);
1775 EventLogTags.writeDeviceIdleLightStep();
1776
1777 switch (mLightState) {
1778 case LIGHT_STATE_INACTIVE:
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001779 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
Dianne Hackborn953fc942016-03-29 15:36:24 -07001780 // Reset the upcoming idle delays.
1781 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001782 mMaintenanceStartTime = 0;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001783 if (!isOpsInactiveLocked()) {
1784 // We have some active ops going on... give them a chance to finish
1785 // before going in to our first idle.
1786 mLightState = LIGHT_STATE_PRE_IDLE;
1787 EventLogTags.writeDeviceIdleLight(mLightState, reason);
1788 scheduleLightAlarmLocked(mConstants.LIGHT_PRE_IDLE_TIMEOUT);
1789 break;
1790 }
1791 // Nothing active, fall through to immediately idle.
1792 case LIGHT_STATE_PRE_IDLE:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001793 case LIGHT_STATE_IDLE_MAINTENANCE:
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001794 if (mMaintenanceStartTime != 0) {
1795 long duration = SystemClock.elapsedRealtime() - mMaintenanceStartTime;
1796 if (duration < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
1797 // We didn't use up all of our minimum budget; add this to the reserve.
1798 mCurIdleBudget += (mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET-duration);
1799 } else {
1800 // We used more than our minimum budget; this comes out of the reserve.
1801 mCurIdleBudget -= (duration-mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET);
1802 }
1803 }
1804 mMaintenanceStartTime = 0;
Dianne Hackborn953fc942016-03-29 15:36:24 -07001805 scheduleLightAlarmLocked(mNextLightIdleDelay);
1806 mNextLightIdleDelay = Math.min(mConstants.LIGHT_MAX_IDLE_TIMEOUT,
1807 (long)(mNextLightIdleDelay * mConstants.LIGHT_IDLE_FACTOR));
1808 if (mNextLightIdleDelay < mConstants.LIGHT_IDLE_TIMEOUT) {
1809 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
1810 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001811 if (DEBUG) Slog.d(TAG, "Moved to LIGHT_STATE_IDLE.");
1812 mLightState = LIGHT_STATE_IDLE;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001813 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001814 addEvent(EVENT_LIGHT_IDLE);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001815 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON_LIGHT);
1816 break;
1817 case LIGHT_STATE_IDLE:
1818 // We have been idling long enough, now it is time to do some work.
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001819 mActiveIdleOpCount = 1;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001820 mActiveIdleWakeLock.acquire();
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001821 mMaintenanceStartTime = SystemClock.elapsedRealtime();
1822 if (mCurIdleBudget < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
1823 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
1824 } else if (mCurIdleBudget > mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET) {
1825 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET;
1826 }
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001827 scheduleLightAlarmLocked(mCurIdleBudget);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001828 if (DEBUG) Slog.d(TAG,
1829 "Moved from LIGHT_STATE_IDLE to LIGHT_STATE_IDLE_MAINTENANCE.");
1830 mLightState = LIGHT_STATE_IDLE_MAINTENANCE;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001831 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001832 addEvent(EVENT_LIGHT_MAINTENANCE);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001833 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
1834 break;
1835 }
1836 }
1837
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001838 void stepIdleStateLocked(String reason) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001839 if (DEBUG) Slog.d(TAG, "stepIdleStateLocked: mState=" + mState);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001840 EventLogTags.writeDeviceIdleStep();
1841
1842 final long now = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07001843 if ((now+mConstants.MIN_TIME_TO_ALARM) > mAlarmManager.getNextWakeFromIdleTime()) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001844 // Whoops, there is an upcoming alarm. We don't actually want to go idle.
1845 if (mState != STATE_ACTIVE) {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001846 becomeActiveLocked("alarm", Process.myUid());
Koji Fukui27b33302015-12-16 19:43:01 +09001847 becomeInactiveIfAppropriateLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001848 }
1849 return;
1850 }
1851
1852 switch (mState) {
1853 case STATE_INACTIVE:
1854 // We have now been inactive long enough, it is time to start looking
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001855 // for motion and sleep some more while doing so.
1856 startMonitoringMotionLocked();
Adam Lesinski31c05d12015-06-09 17:34:04 -07001857 scheduleAlarmLocked(mConstants.IDLE_AFTER_INACTIVE_TIMEOUT, false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001858 // Reset the upcoming idle delays.
Adam Lesinski31c05d12015-06-09 17:34:04 -07001859 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
1860 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001861 mState = STATE_IDLE_PENDING;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001862 if (DEBUG) Slog.d(TAG, "Moved from STATE_INACTIVE to STATE_IDLE_PENDING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001863 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001864 break;
1865 case STATE_IDLE_PENDING:
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001866 mState = STATE_SENSING;
1867 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE_PENDING to STATE_SENSING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001868 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackborn18acb552015-10-26 14:31:07 -07001869 scheduleAlarmLocked(mConstants.SENSING_TIMEOUT, false);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001870 cancelLocatingLocked();
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001871 mAnyMotionDetector.checkForAnyMotion();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001872 mNotMoving = false;
1873 mLocated = false;
1874 mLastGenericLocation = null;
1875 mLastGpsLocation = null;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001876 break;
1877 case STATE_SENSING:
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001878 mState = STATE_LOCATING;
1879 if (DEBUG) Slog.d(TAG, "Moved from STATE_SENSING to STATE_LOCATING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001880 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001881 scheduleAlarmLocked(mConstants.LOCATING_TIMEOUT, false);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001882 if (mLocationManager != null
1883 && mLocationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
1884 mLocationManager.requestLocationUpdates(mLocationRequest,
1885 mGenericLocationListener, mHandler.getLooper());
1886 mLocating = true;
1887 } else {
1888 mHasNetworkLocation = false;
1889 }
1890 if (mLocationManager != null
1891 && mLocationManager.getProvider(LocationManager.GPS_PROVIDER) != null) {
1892 mHasGps = true;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001893 mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 5,
1894 mGpsLocationListener, mHandler.getLooper());
Joe LaPenna23d681b2015-08-27 15:12:11 -07001895 mLocating = true;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001896 } else {
Joe LaPenna23d681b2015-08-27 15:12:11 -07001897 mHasGps = false;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001898 }
Joe LaPenna23d681b2015-08-27 15:12:11 -07001899 // If we have a location provider, we're all set, the listeners will move state
1900 // forward.
1901 if (mLocating) {
1902 break;
1903 }
1904
1905 // Otherwise, we have to move from locating into idle maintenance.
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001906 case STATE_LOCATING:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001907 cancelAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001908 cancelLocatingLocked();
1909 mAnyMotionDetector.stop();
Dianne Hackborn953fc942016-03-29 15:36:24 -07001910
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001911 case STATE_IDLE_MAINTENANCE:
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001912 scheduleAlarmLocked(mNextIdleDelay, true);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001913 if (DEBUG) Slog.d(TAG, "Moved to STATE_IDLE. Next alarm in " + mNextIdleDelay +
1914 " ms.");
Adam Lesinski31c05d12015-06-09 17:34:04 -07001915 mNextIdleDelay = (long)(mNextIdleDelay * mConstants.IDLE_FACTOR);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001916 if (DEBUG) Slog.d(TAG, "Setting mNextIdleDelay = " + mNextIdleDelay);
Adam Lesinski31c05d12015-06-09 17:34:04 -07001917 mNextIdleDelay = Math.min(mNextIdleDelay, mConstants.MAX_IDLE_TIMEOUT);
Dianne Hackborn953fc942016-03-29 15:36:24 -07001918 if (mNextIdleDelay < mConstants.IDLE_TIMEOUT) {
1919 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
1920 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001921 mState = STATE_IDLE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001922 if (mLightState != LIGHT_STATE_OVERRIDE) {
1923 mLightState = LIGHT_STATE_OVERRIDE;
1924 cancelLightAlarmLocked();
1925 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001926 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackbornb6843652016-02-22 12:20:13 -08001927 addEvent(EVENT_DEEP_IDLE);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001928 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON);
1929 break;
1930 case STATE_IDLE:
1931 // We have been idling long enough, now it is time to do some work.
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001932 mActiveIdleOpCount = 1;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001933 mActiveIdleWakeLock.acquire();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001934 scheduleAlarmLocked(mNextIdlePendingDelay, false);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001935 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE to STATE_IDLE_MAINTENANCE. " +
1936 "Next alarm in " + mNextIdlePendingDelay + " ms.");
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07001937 mMaintenanceStartTime = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07001938 mNextIdlePendingDelay = Math.min(mConstants.MAX_IDLE_PENDING_TIMEOUT,
1939 (long)(mNextIdlePendingDelay * mConstants.IDLE_PENDING_FACTOR));
Dianne Hackborn953fc942016-03-29 15:36:24 -07001940 if (mNextIdlePendingDelay < mConstants.IDLE_PENDING_TIMEOUT) {
1941 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
1942 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001943 mState = STATE_IDLE_MAINTENANCE;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001944 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackbornb6843652016-02-22 12:20:13 -08001945 addEvent(EVENT_DEEP_MAINTENANCE);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001946 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
1947 break;
1948 }
1949 }
1950
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001951 void incActiveIdleOps() {
1952 synchronized (this) {
1953 mActiveIdleOpCount++;
1954 }
1955 }
1956
1957 void decActiveIdleOps() {
1958 synchronized (this) {
1959 mActiveIdleOpCount--;
1960 if (mActiveIdleOpCount <= 0) {
1961 exitMaintenanceEarlyIfNeededLocked();
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001962 mActiveIdleWakeLock.release();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001963 }
1964 }
1965 }
1966
1967 void downloadServiceActive(IBinder token) {
1968 synchronized (this) {
1969 mDownloadServiceActive = token;
Yao Chenca5edbb2016-01-13 14:44:36 -08001970 reportMaintenanceActivityIfNeededLocked();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001971 try {
1972 token.linkToDeath(new IBinder.DeathRecipient() {
1973 @Override public void binderDied() {
1974 downloadServiceInactive();
1975 }
1976 }, 0);
1977 } catch (RemoteException e) {
1978 mDownloadServiceActive = null;
1979 }
1980 }
1981 }
1982
1983 void downloadServiceInactive() {
1984 synchronized (this) {
1985 mDownloadServiceActive = null;
Yao Chenca5edbb2016-01-13 14:44:36 -08001986 reportMaintenanceActivityIfNeededLocked();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001987 exitMaintenanceEarlyIfNeededLocked();
1988 }
1989 }
1990
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001991 void setJobsActive(boolean active) {
1992 synchronized (this) {
1993 mJobsActive = active;
Yao Chenca5edbb2016-01-13 14:44:36 -08001994 reportMaintenanceActivityIfNeededLocked();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001995 if (!active) {
1996 exitMaintenanceEarlyIfNeededLocked();
1997 }
1998 }
1999 }
2000
2001 void setAlarmsActive(boolean active) {
2002 synchronized (this) {
2003 mAlarmsActive = active;
2004 if (!active) {
2005 exitMaintenanceEarlyIfNeededLocked();
2006 }
2007 }
2008 }
2009
Yao Chenca5edbb2016-01-13 14:44:36 -08002010 boolean registerMaintenanceActivityListener(IMaintenanceActivityListener listener) {
2011 synchronized (this) {
2012 mMaintenanceActivityListeners.register(listener);
2013 return mReportedMaintenanceActivity;
2014 }
2015 }
2016
2017 void unregisterMaintenanceActivityListener(IMaintenanceActivityListener listener) {
2018 synchronized (this) {
2019 mMaintenanceActivityListeners.unregister(listener);
2020 }
2021 }
2022
2023 void reportMaintenanceActivityIfNeededLocked() {
Amith Yamasanicb926fc2016-03-14 17:15:20 -07002024 boolean active = mJobsActive | (mDownloadServiceActive != null);
Yao Chenca5edbb2016-01-13 14:44:36 -08002025 if (active == mReportedMaintenanceActivity) {
2026 return;
2027 }
2028 mReportedMaintenanceActivity = active;
2029 Message msg = mHandler.obtainMessage(MSG_REPORT_MAINTENANCE_ACTIVITY,
2030 mReportedMaintenanceActivity ? 1 : 0, 0);
2031 mHandler.sendMessage(msg);
2032 }
2033
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002034 boolean isOpsInactiveLocked() {
2035 return mActiveIdleOpCount <= 0 && mDownloadServiceActive == null
2036 && !mJobsActive && !mAlarmsActive;
2037 }
2038
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002039 void exitMaintenanceEarlyIfNeededLocked() {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002040 if (mState == STATE_IDLE_MAINTENANCE || mLightState == LIGHT_STATE_IDLE_MAINTENANCE
2041 || mLightState == LIGHT_STATE_PRE_IDLE) {
2042 if (isOpsInactiveLocked()) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002043 final long now = SystemClock.elapsedRealtime();
2044 if (DEBUG) {
2045 StringBuilder sb = new StringBuilder();
2046 sb.append("Exit: start=");
2047 TimeUtils.formatDuration(mMaintenanceStartTime, sb);
2048 sb.append(" now=");
2049 TimeUtils.formatDuration(now, sb);
2050 Slog.d(TAG, sb.toString());
2051 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002052 if (mState == STATE_IDLE_MAINTENANCE) {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002053 stepIdleStateLocked("s:early");
2054 } else if (mLightState == LIGHT_STATE_PRE_IDLE) {
2055 stepLightIdleStateLocked("s:predone");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002056 } else {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002057 stepLightIdleStateLocked("s:early");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002058 }
2059 }
2060 }
2061 }
2062
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002063 void motionLocked() {
2064 if (DEBUG) Slog.d(TAG, "motionLocked()");
2065 // The motion sensor will have been disabled at this point
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002066 handleMotionDetectedLocked(mConstants.MOTION_INACTIVE_TIMEOUT, "motion");
2067 }
2068
2069 void handleMotionDetectedLocked(long timeout, String type) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002070 // The device is not yet active, so we want to go back to the pending idle
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002071 // state to wait again for no motion. Note that we only monitor for motion
2072 // after moving out of the inactive state, so no need to worry about that.
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002073 boolean becomeInactive = false;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002074 if (mState != STATE_ACTIVE) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002075 scheduleReportActiveLocked(type, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002076 mState = STATE_ACTIVE;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002077 mInactiveTimeout = timeout;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002078 mCurIdleBudget = 0;
2079 mMaintenanceStartTime = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002080 EventLogTags.writeDeviceIdle(mState, type);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002081 addEvent(EVENT_NORMAL);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002082 becomeInactive = true;
2083 }
2084 if (mLightState == LIGHT_STATE_OVERRIDE) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002085 // We went out of light idle mode because we had started deep idle mode... let's
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002086 // now go back and reset things so we resume light idling if appropriate.
2087 mLightState = STATE_ACTIVE;
2088 EventLogTags.writeDeviceIdleLight(mLightState, type);
2089 becomeInactive = true;
2090 }
2091 if (becomeInactive) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002092 becomeInactiveIfAppropriateLocked();
2093 }
2094 }
2095
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002096 void receivedGenericLocationLocked(Location location) {
2097 if (mState != STATE_LOCATING) {
2098 cancelLocatingLocked();
2099 return;
2100 }
2101 if (DEBUG) Slog.d(TAG, "Generic location: " + location);
2102 mLastGenericLocation = new Location(location);
Joe LaPenna23d681b2015-08-27 15:12:11 -07002103 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY && mHasGps) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002104 return;
2105 }
2106 mLocated = true;
2107 if (mNotMoving) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002108 stepIdleStateLocked("s:location");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002109 }
2110 }
2111
2112 void receivedGpsLocationLocked(Location location) {
2113 if (mState != STATE_LOCATING) {
2114 cancelLocatingLocked();
2115 return;
2116 }
2117 if (DEBUG) Slog.d(TAG, "GPS location: " + location);
2118 mLastGpsLocation = new Location(location);
2119 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY) {
2120 return;
2121 }
2122 mLocated = true;
2123 if (mNotMoving) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002124 stepIdleStateLocked("s:gps");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002125 }
2126 }
2127
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002128 void startMonitoringMotionLocked() {
2129 if (DEBUG) Slog.d(TAG, "startMonitoringMotionLocked()");
2130 if (mMotionSensor != null && !mMotionListener.active) {
2131 mMotionListener.registerLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002132 }
2133 }
2134
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002135 void stopMonitoringMotionLocked() {
2136 if (DEBUG) Slog.d(TAG, "stopMonitoringMotionLocked()");
2137 if (mMotionSensor != null && mMotionListener.active) {
2138 mMotionListener.unregisterLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002139 }
2140 }
2141
2142 void cancelAlarmLocked() {
2143 if (mNextAlarmTime != 0) {
2144 mNextAlarmTime = 0;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002145 mAlarmManager.cancel(mDeepAlarmListener);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002146 }
2147 }
2148
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002149 void cancelLightAlarmLocked() {
2150 if (mNextLightAlarmTime != 0) {
2151 mNextLightAlarmTime = 0;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002152 mAlarmManager.cancel(mLightAlarmListener);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002153 }
2154 }
2155
2156 void cancelLocatingLocked() {
2157 if (mLocating) {
2158 mLocationManager.removeUpdates(mGenericLocationListener);
2159 mLocationManager.removeUpdates(mGpsLocationListener);
2160 mLocating = false;
2161 }
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002162 }
2163
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002164 void scheduleAlarmLocked(long delay, boolean idleUntil) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002165 if (DEBUG) Slog.d(TAG, "scheduleAlarmLocked(" + delay + ", " + idleUntil + ")");
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002166 if (mMotionSensor == null) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07002167 // If there is no motion sensor on this device, then we won't schedule
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002168 // alarms, because we can't determine if the device is not moving. This effectively
Joe LaPenna23d681b2015-08-27 15:12:11 -07002169 // turns off normal execution of device idling, although it is still possible to
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002170 // manually poke it by pretending like the alarm is going off.
2171 return;
2172 }
2173 mNextAlarmTime = SystemClock.elapsedRealtime() + delay;
2174 if (idleUntil) {
2175 mAlarmManager.setIdleUntil(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002176 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002177 } else {
2178 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002179 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002180 }
2181 }
2182
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002183 void scheduleLightAlarmLocked(long delay) {
2184 if (DEBUG) Slog.d(TAG, "scheduleLightAlarmLocked(" + delay + ")");
2185 if (mMotionSensor == null) {
2186 // If there is no motion sensor on this device, then we won't schedule
2187 // alarms, because we can't determine if the device is not moving. This effectively
2188 // turns off normal execution of device idling, although it is still possible to
2189 // manually poke it by pretending like the alarm is going off.
2190 return;
2191 }
2192 mNextLightAlarmTime = SystemClock.elapsedRealtime() + delay;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002193 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002194 mNextLightAlarmTime, "DeviceIdleController.light", mLightAlarmListener, mHandler);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002195 }
2196
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002197 private static int[] buildAppIdArray(ArrayMap<String, Integer> systemApps,
2198 ArrayMap<String, Integer> userApps, SparseBooleanArray outAppIds) {
2199 outAppIds.clear();
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002200 if (systemApps != null) {
2201 for (int i = 0; i < systemApps.size(); i++) {
2202 outAppIds.put(systemApps.valueAt(i), true);
2203 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002204 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002205 if (userApps != null) {
2206 for (int i = 0; i < userApps.size(); i++) {
2207 outAppIds.put(userApps.valueAt(i), true);
2208 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002209 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002210 int size = outAppIds.size();
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002211 int[] appids = new int[size];
2212 for (int i = 0; i < size; i++) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002213 appids[i] = outAppIds.keyAt(i);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002214 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002215 return appids;
2216 }
2217
2218 private void updateWhitelistAppIdsLocked() {
2219 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(mPowerSaveWhitelistAppsExceptIdle,
2220 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistExceptIdleAppIds);
2221 mPowerSaveWhitelistAllAppIdArray = buildAppIdArray(mPowerSaveWhitelistApps,
2222 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistAllAppIds);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002223 mPowerSaveWhitelistUserAppIdArray = buildAppIdArray(null,
2224 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistUserAppIds);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002225 if (mLocalPowerManager != null) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002226 if (DEBUG) {
2227 Slog.d(TAG, "Setting wakelock whitelist to "
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002228 + Arrays.toString(mPowerSaveWhitelistAllAppIdArray));
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002229 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002230 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002231 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002232 if (mLocalAlarmManager != null) {
2233 if (DEBUG) {
2234 Slog.d(TAG, "Setting alarm whitelist to "
2235 + Arrays.toString(mPowerSaveWhitelistUserAppIdArray));
2236 }
2237 mLocalAlarmManager.setDeviceIdleUserWhitelist(mPowerSaveWhitelistUserAppIdArray);
2238 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002239 }
2240
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002241 private void updateTempWhitelistAppIdsLocked() {
2242 final int size = mTempWhitelistAppIdEndTimes.size();
2243 if (mTempWhitelistAppIdArray.length != size) {
2244 mTempWhitelistAppIdArray = new int[size];
2245 }
2246 for (int i = 0; i < size; i++) {
2247 mTempWhitelistAppIdArray[i] = mTempWhitelistAppIdEndTimes.keyAt(i);
2248 }
2249 if (mLocalPowerManager != null) {
2250 if (DEBUG) {
2251 Slog.d(TAG, "Setting wakelock temp whitelist to "
2252 + Arrays.toString(mTempWhitelistAppIdArray));
2253 }
2254 mLocalPowerManager.setDeviceIdleTempWhitelist(mTempWhitelistAppIdArray);
2255 }
2256 }
2257
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002258 private void reportPowerSaveWhitelistChangedLocked() {
2259 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
2260 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Xiaohui Chene4de5a02015-09-22 15:33:31 -07002261 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002262 }
2263
2264 private void reportTempWhitelistChangedLocked() {
2265 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_TEMP_WHITELIST_CHANGED);
2266 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Xiaohui Chene4de5a02015-09-22 15:33:31 -07002267 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002268 }
2269
2270 void readConfigFileLocked() {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002271 if (DEBUG) Slog.d(TAG, "Reading config from " + mConfigFile.getBaseFile());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002272 mPowerSaveWhitelistUserApps.clear();
2273 FileInputStream stream;
2274 try {
2275 stream = mConfigFile.openRead();
2276 } catch (FileNotFoundException e) {
2277 return;
2278 }
2279 try {
2280 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002281 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002282 readConfigFileLocked(parser);
2283 } catch (XmlPullParserException e) {
2284 } finally {
2285 try {
2286 stream.close();
2287 } catch (IOException e) {
2288 }
2289 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002290 }
2291
2292 private void readConfigFileLocked(XmlPullParser parser) {
2293 final PackageManager pm = getContext().getPackageManager();
2294
2295 try {
2296 int type;
2297 while ((type = parser.next()) != XmlPullParser.START_TAG
2298 && type != XmlPullParser.END_DOCUMENT) {
2299 ;
2300 }
2301
2302 if (type != XmlPullParser.START_TAG) {
2303 throw new IllegalStateException("no start tag found");
2304 }
2305
2306 int outerDepth = parser.getDepth();
2307 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2308 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2309 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2310 continue;
2311 }
2312
2313 String tagName = parser.getName();
2314 if (tagName.equals("wl")) {
2315 String name = parser.getAttributeValue(null, "n");
2316 if (name != null) {
2317 try {
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07002318 ApplicationInfo ai = pm.getApplicationInfo(name,
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07002319 PackageManager.MATCH_UNINSTALLED_PACKAGES);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002320 mPowerSaveWhitelistUserApps.put(ai.packageName,
2321 UserHandle.getAppId(ai.uid));
2322 } catch (PackageManager.NameNotFoundException e) {
2323 }
2324 }
2325 } else {
2326 Slog.w(TAG, "Unknown element under <config>: "
2327 + parser.getName());
2328 XmlUtils.skipCurrentTag(parser);
2329 }
2330 }
2331
2332 } catch (IllegalStateException e) {
2333 Slog.w(TAG, "Failed parsing config " + e);
2334 } catch (NullPointerException e) {
2335 Slog.w(TAG, "Failed parsing config " + e);
2336 } catch (NumberFormatException e) {
2337 Slog.w(TAG, "Failed parsing config " + e);
2338 } catch (XmlPullParserException e) {
2339 Slog.w(TAG, "Failed parsing config " + e);
2340 } catch (IOException e) {
2341 Slog.w(TAG, "Failed parsing config " + e);
2342 } catch (IndexOutOfBoundsException e) {
2343 Slog.w(TAG, "Failed parsing config " + e);
2344 }
2345 }
2346
2347 void writeConfigFileLocked() {
2348 mHandler.removeMessages(MSG_WRITE_CONFIG);
2349 mHandler.sendEmptyMessageDelayed(MSG_WRITE_CONFIG, 5000);
2350 }
2351
2352 void handleWriteConfigFile() {
2353 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
2354
2355 try {
2356 synchronized (this) {
2357 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002358 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002359 writeConfigFileLocked(out);
2360 }
2361 } catch (IOException e) {
2362 }
2363
2364 synchronized (mConfigFile) {
2365 FileOutputStream stream = null;
2366 try {
2367 stream = mConfigFile.startWrite();
2368 memStream.writeTo(stream);
2369 stream.flush();
2370 FileUtils.sync(stream);
2371 stream.close();
2372 mConfigFile.finishWrite(stream);
2373 } catch (IOException e) {
2374 Slog.w(TAG, "Error writing config file", e);
2375 mConfigFile.failWrite(stream);
2376 }
2377 }
2378 }
2379
2380 void writeConfigFileLocked(XmlSerializer out) throws IOException {
2381 out.startDocument(null, true);
2382 out.startTag(null, "config");
2383 for (int i=0; i<mPowerSaveWhitelistUserApps.size(); i++) {
2384 String name = mPowerSaveWhitelistUserApps.keyAt(i);
2385 out.startTag(null, "wl");
2386 out.attribute(null, "n", name);
2387 out.endTag(null, "wl");
2388 }
2389 out.endTag(null, "config");
2390 out.endDocument();
2391 }
2392
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002393 static void dumpHelp(PrintWriter pw) {
2394 pw.println("Device idle controller (deviceidle) commands:");
2395 pw.println(" help");
2396 pw.println(" Print this help text.");
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002397 pw.println(" step [light|deep]");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002398 pw.println(" Immediately step to next state, without waiting for alarm.");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002399 pw.println(" force-idle");
2400 pw.println(" Force directly into idle mode, regardless of other device state.");
2401 pw.println(" Use \"step\" to get out.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002402 pw.println(" disable [light|deep|all]");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002403 pw.println(" Completely disable device idle mode.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002404 pw.println(" enable [light|deep|all]");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002405 pw.println(" Re-enable device idle mode after it had previously been disabled.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002406 pw.println(" enabled [light|deep|all]");
Dianne Hackborn92617032015-06-19 15:32:19 -07002407 pw.println(" Print 1 if device idle mode is currently enabled, else 0.");
Dianne Hackborn1b139682015-07-06 15:13:37 -07002408 pw.println(" whitelist");
2409 pw.println(" Print currently whitelisted apps.");
Dianne Hackborn92617032015-06-19 15:32:19 -07002410 pw.println(" whitelist [package ...]");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002411 pw.println(" Add (prefix with +) or remove (prefix with -) packages.");
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002412 pw.println(" tempwhitelist [-u] [package ..]");
Dianne Hackborn92617032015-06-19 15:32:19 -07002413 pw.println(" Temporarily place packages in whitelist for 10 seconds.");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002414 }
2415
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002416 class Shell extends ShellCommand {
2417 int userId = UserHandle.USER_SYSTEM;
2418
2419 @Override
2420 public int onCommand(String cmd) {
2421 return onShellCommand(this, cmd);
2422 }
2423
2424 @Override
2425 public void onHelp() {
2426 PrintWriter pw = getOutPrintWriter();
2427 dumpHelp(pw);
2428 }
2429 }
2430
2431 int onShellCommand(Shell shell, String cmd) {
2432 PrintWriter pw = shell.getOutPrintWriter();
2433 if ("step".equals(cmd)) {
2434 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2435 null);
2436 synchronized (this) {
2437 long token = Binder.clearCallingIdentity();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002438 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002439 try {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002440 if (arg == null || "deep".equals(arg)) {
2441 exitForceIdleLocked();
2442 stepIdleStateLocked("s:shell");
2443 pw.print("Stepped to deep: ");
2444 pw.println(stateToString(mState));
2445 } else if ("light".equals(arg)) {
2446 exitForceIdleLocked();
2447 stepLightIdleStateLocked("s:shell");
2448 pw.print("Stepped to light: "); pw.println(lightStateToString(mLightState));
2449 } else {
2450 pw.println("Unknown idle mode: " + arg);
2451 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002452 } finally {
2453 Binder.restoreCallingIdentity(token);
2454 }
2455 }
2456 } else if ("force-idle".equals(cmd)) {
2457 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2458 null);
2459 synchronized (this) {
2460 long token = Binder.clearCallingIdentity();
2461 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002462 if (!mDeepEnabled) {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002463 pw.println("Unable to go idle; not enabled");
2464 return -1;
2465 }
2466 mForceIdle = true;
2467 becomeInactiveIfAppropriateLocked();
2468 int curState = mState;
2469 while (curState != STATE_IDLE) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002470 stepIdleStateLocked("s:shell");
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002471 if (curState == mState) {
2472 pw.print("Unable to go idle; stopped at ");
2473 pw.println(stateToString(mState));
2474 exitForceIdleLocked();
2475 return -1;
2476 }
2477 curState = mState;
2478 }
2479 pw.println("Now forced in to idle mode");
2480 } finally {
2481 Binder.restoreCallingIdentity(token);
2482 }
2483 }
2484 } else if ("disable".equals(cmd)) {
2485 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2486 null);
2487 synchronized (this) {
2488 long token = Binder.clearCallingIdentity();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002489 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002490 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002491 boolean becomeActive = false;
2492 boolean valid = false;
2493 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
2494 valid = true;
2495 if (mDeepEnabled) {
2496 mDeepEnabled = false;
2497 becomeActive = true;
2498 pw.println("Deep idle mode disabled");
2499 }
2500 }
2501 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
2502 valid = true;
2503 if (mLightEnabled) {
2504 mLightEnabled = false;
2505 becomeActive = true;
2506 pw.println("Light idle mode disabled");
2507 }
2508 }
2509 if (becomeActive) {
2510 becomeActiveLocked((arg == null ? "all" : arg) + "-disabled",
2511 Process.myUid());
2512 }
2513 if (!valid) {
2514 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002515 }
2516 } finally {
2517 Binder.restoreCallingIdentity(token);
2518 }
2519 }
2520 } else if ("enable".equals(cmd)) {
2521 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2522 null);
2523 synchronized (this) {
2524 long token = Binder.clearCallingIdentity();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002525 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002526 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002527 boolean becomeInactive = false;
2528 boolean valid = false;
2529 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
2530 valid = true;
2531 if (!mDeepEnabled) {
2532 mDeepEnabled = true;
2533 becomeInactive = true;
2534 pw.println("Deep idle mode enabled");
2535 }
2536 }
2537 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
2538 valid = true;
2539 if (!mLightEnabled) {
2540 mLightEnabled = true;
2541 becomeInactive = true;
2542 pw.println("Light idle mode enable");
2543 }
2544 }
2545 if (becomeInactive) {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002546 becomeInactiveIfAppropriateLocked();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002547 }
2548 if (!valid) {
2549 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002550 }
2551 } finally {
2552 Binder.restoreCallingIdentity(token);
2553 }
2554 }
2555 } else if ("enabled".equals(cmd)) {
2556 synchronized (this) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002557 String arg = shell.getNextArg();
2558 if (arg == null || "all".equals(arg)) {
2559 pw.println(mDeepEnabled && mLightEnabled ? "1" : 0);
2560 } else if ("deep".equals(arg)) {
2561 pw.println(mDeepEnabled ? "1" : 0);
2562 } else if ("light".equals(arg)) {
2563 pw.println(mLightEnabled ? "1" : 0);
2564 } else {
2565 pw.println("Unknown idle mode: " + arg);
2566 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002567 }
2568 } else if ("whitelist".equals(cmd)) {
2569 long token = Binder.clearCallingIdentity();
2570 try {
2571 String arg = shell.getNextArg();
2572 if (arg != null) {
2573 getContext().enforceCallingOrSelfPermission(
2574 android.Manifest.permission.DEVICE_POWER, null);
2575 do {
2576 if (arg.length() < 1 || (arg.charAt(0) != '-'
Felipe Lemef8a46232016-02-10 13:51:54 -08002577 && arg.charAt(0) != '+' && arg.charAt(0) != '=')) {
2578 pw.println("Package must be prefixed with +, -, or =: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002579 return -1;
2580 }
2581 char op = arg.charAt(0);
2582 String pkg = arg.substring(1);
2583 if (op == '+') {
2584 if (addPowerSaveWhitelistAppInternal(pkg)) {
2585 pw.println("Added: " + pkg);
2586 } else {
2587 pw.println("Unknown package: " + pkg);
2588 }
Felipe Lemef8a46232016-02-10 13:51:54 -08002589 } else if (op == '-') {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002590 if (removePowerSaveWhitelistAppInternal(pkg)) {
2591 pw.println("Removed: " + pkg);
2592 }
Felipe Lemef8a46232016-02-10 13:51:54 -08002593 } else {
2594 pw.println(getPowerSaveWhitelistAppInternal(pkg));
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002595 }
2596 } while ((arg=shell.getNextArg()) != null);
2597 } else {
2598 synchronized (this) {
2599 for (int j=0; j<mPowerSaveWhitelistAppsExceptIdle.size(); j++) {
2600 pw.print("system-excidle,");
2601 pw.print(mPowerSaveWhitelistAppsExceptIdle.keyAt(j));
2602 pw.print(",");
2603 pw.println(mPowerSaveWhitelistAppsExceptIdle.valueAt(j));
2604 }
2605 for (int j=0; j<mPowerSaveWhitelistApps.size(); j++) {
2606 pw.print("system,");
2607 pw.print(mPowerSaveWhitelistApps.keyAt(j));
2608 pw.print(",");
2609 pw.println(mPowerSaveWhitelistApps.valueAt(j));
2610 }
2611 for (int j=0; j<mPowerSaveWhitelistUserApps.size(); j++) {
2612 pw.print("user,");
2613 pw.print(mPowerSaveWhitelistUserApps.keyAt(j));
2614 pw.print(",");
2615 pw.println(mPowerSaveWhitelistUserApps.valueAt(j));
2616 }
2617 }
2618 }
2619 } finally {
2620 Binder.restoreCallingIdentity(token);
2621 }
2622 } else if ("tempwhitelist".equals(cmd)) {
2623 String opt;
2624 while ((opt=shell.getNextOption()) != null) {
2625 if ("-u".equals(opt)) {
2626 opt = shell.getNextArg();
2627 if (opt == null) {
2628 pw.println("-u requires a user number");
2629 return -1;
2630 }
2631 shell.userId = Integer.parseInt(opt);
2632 }
2633 }
2634 String arg = shell.getNextArg();
2635 if (arg != null) {
2636 try {
2637 addPowerSaveTempWhitelistAppChecked(arg, 10000L, shell.userId, "shell");
2638 } catch (RemoteException re) {
2639 pw.println("Failed: " + re);
2640 }
2641 } else {
2642 pw.println("At least one package name must be specified");
2643 return -1;
2644 }
2645 } else {
2646 return shell.handleDefaultCommands(cmd);
2647 }
2648 return 0;
2649 }
2650
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002651 void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2652 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2653 != PackageManager.PERMISSION_GRANTED) {
2654 pw.println("Permission Denial: can't dump DeviceIdleController from from pid="
2655 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2656 + " without permission " + android.Manifest.permission.DUMP);
2657 return;
2658 }
2659
2660 if (args != null) {
Xiaohui Chen7c696362015-09-16 09:56:14 -07002661 int userId = UserHandle.USER_SYSTEM;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002662 for (int i=0; i<args.length; i++) {
2663 String arg = args[i];
2664 if ("-h".equals(arg)) {
2665 dumpHelp(pw);
2666 return;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002667 } else if ("-u".equals(arg)) {
2668 i++;
2669 if (i < args.length) {
2670 arg = args[i];
2671 userId = Integer.parseInt(arg);
2672 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002673 } else if ("-a".equals(arg)) {
2674 // Ignore, we always dump all.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002675 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
2676 pw.println("Unknown option: " + arg);
2677 return;
2678 } else {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002679 Shell shell = new Shell();
2680 shell.userId = userId;
2681 String[] newArgs = new String[args.length-i];
2682 System.arraycopy(args, i, newArgs, 0, args.length-i);
2683 shell.exec(mBinderService, null, fd, null, newArgs, new ResultReceiver(null));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002684 return;
2685 }
2686 }
2687 }
2688
2689 synchronized (this) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002690 mConstants.dump(pw);
2691
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002692 if (mEventCmds[0] != EVENT_NULL) {
2693 pw.println(" Idling history:");
2694 long now = SystemClock.elapsedRealtime();
2695 for (int i=EVENT_BUFFER_SIZE-1; i>=0; i--) {
2696 int cmd = mEventCmds[i];
2697 if (cmd == EVENT_NULL) {
2698 continue;
2699 }
2700 String label;
2701 switch (mEventCmds[i]) {
2702 case EVENT_NORMAL: label = " normal"; break;
2703 case EVENT_LIGHT_IDLE: label = " light-idle"; break;
2704 case EVENT_LIGHT_MAINTENANCE: label = "light-maint"; break;
Dianne Hackbornb6843652016-02-22 12:20:13 -08002705 case EVENT_DEEP_IDLE: label = " deep-idle"; break;
2706 case EVENT_DEEP_MAINTENANCE: label = " deep-maint"; break;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002707 default: label = " ??"; break;
2708 }
2709 pw.print(" ");
2710 pw.print(label);
2711 pw.print(": ");
2712 TimeUtils.formatDuration(mEventTimes[i], now, pw);;
2713 pw.println();
2714 }
2715 }
2716
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002717 int size = mPowerSaveWhitelistAppsExceptIdle.size();
2718 if (size > 0) {
2719 pw.println(" Whitelist (except idle) system apps:");
2720 for (int i = 0; i < size; i++) {
2721 pw.print(" ");
2722 pw.println(mPowerSaveWhitelistAppsExceptIdle.keyAt(i));
2723 }
2724 }
2725 size = mPowerSaveWhitelistApps.size();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002726 if (size > 0) {
2727 pw.println(" Whitelist system apps:");
2728 for (int i = 0; i < size; i++) {
2729 pw.print(" ");
2730 pw.println(mPowerSaveWhitelistApps.keyAt(i));
2731 }
2732 }
2733 size = mPowerSaveWhitelistUserApps.size();
2734 if (size > 0) {
2735 pw.println(" Whitelist user apps:");
2736 for (int i = 0; i < size; i++) {
2737 pw.print(" ");
2738 pw.println(mPowerSaveWhitelistUserApps.keyAt(i));
2739 }
2740 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002741 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2742 if (size > 0) {
2743 pw.println(" Whitelist (except idle) all app ids:");
2744 for (int i = 0; i < size; i++) {
2745 pw.print(" ");
2746 pw.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2747 pw.println();
2748 }
2749 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002750 size = mPowerSaveWhitelistUserAppIds.size();
2751 if (size > 0) {
2752 pw.println(" Whitelist user app ids:");
2753 for (int i = 0; i < size; i++) {
2754 pw.print(" ");
2755 pw.print(mPowerSaveWhitelistUserAppIds.keyAt(i));
2756 pw.println();
2757 }
2758 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002759 size = mPowerSaveWhitelistAllAppIds.size();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002760 if (size > 0) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002761 pw.println(" Whitelist all app ids:");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002762 for (int i = 0; i < size; i++) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002763 pw.print(" ");
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002764 pw.print(mPowerSaveWhitelistAllAppIds.keyAt(i));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002765 pw.println();
2766 }
2767 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002768 size = mTempWhitelistAppIdEndTimes.size();
2769 if (size > 0) {
2770 pw.println(" Temp whitelist schedule:");
2771 final long timeNow = SystemClock.elapsedRealtime();
2772 for (int i = 0; i < size; i++) {
2773 pw.print(" UID=");
2774 pw.print(mTempWhitelistAppIdEndTimes.keyAt(i));
2775 pw.print(": ");
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002776 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.valueAt(i);
2777 TimeUtils.formatDuration(entry.first.value, timeNow, pw);
2778 pw.print(" - ");
2779 pw.println(entry.second);
Dianne Hackborna750a632015-06-16 17:18:23 -07002780 }
2781 }
2782 size = mTempWhitelistAppIdArray != null ? mTempWhitelistAppIdArray.length : 0;
2783 if (size > 0) {
2784 pw.println(" Temp whitelist app ids:");
2785 for (int i = 0; i < size; i++) {
2786 pw.print(" ");
2787 pw.print(mTempWhitelistAppIdArray[i]);
2788 pw.println();
2789 }
2790 }
Adam Lesinski31c05d12015-06-09 17:34:04 -07002791
Dianne Hackbornb6843652016-02-22 12:20:13 -08002792 pw.print(" mLightEnabled="); pw.print(mLightEnabled);
2793 pw.print(" mDeepEnabled="); pw.println(mDeepEnabled);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002794 pw.print(" mForceIdle="); pw.println(mForceIdle);
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002795 pw.print(" mMotionSensor="); pw.println(mMotionSensor);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002796 pw.print(" mCurDisplay="); pw.println(mCurDisplay);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002797 pw.print(" mScreenOn="); pw.println(mScreenOn);
2798 pw.print(" mCharging="); pw.println(mCharging);
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002799 pw.print(" mMotionActive="); pw.println(mMotionListener.active);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002800 pw.print(" mNotMoving="); pw.println(mNotMoving);
Joe LaPenna23d681b2015-08-27 15:12:11 -07002801 pw.print(" mLocating="); pw.print(mLocating); pw.print(" mHasGps=");
2802 pw.print(mHasGps); pw.print(" mHasNetwork=");
2803 pw.print(mHasNetworkLocation); pw.print(" mLocated="); pw.println(mLocated);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002804 if (mLastGenericLocation != null) {
2805 pw.print(" mLastGenericLocation="); pw.println(mLastGenericLocation);
2806 }
2807 if (mLastGpsLocation != null) {
2808 pw.print(" mLastGpsLocation="); pw.println(mLastGpsLocation);
2809 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002810 pw.print(" mState="); pw.print(stateToString(mState));
2811 pw.print(" mLightState=");
2812 pw.println(lightStateToString(mLightState));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002813 pw.print(" mInactiveTimeout="); TimeUtils.formatDuration(mInactiveTimeout, pw);
2814 pw.println();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002815 if (mActiveIdleOpCount != 0) {
2816 pw.print(" mActiveIdleOpCount="); pw.println(mActiveIdleOpCount);
2817 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002818 if (mNextAlarmTime != 0) {
2819 pw.print(" mNextAlarmTime=");
2820 TimeUtils.formatDuration(mNextAlarmTime, SystemClock.elapsedRealtime(), pw);
2821 pw.println();
2822 }
2823 if (mNextIdlePendingDelay != 0) {
2824 pw.print(" mNextIdlePendingDelay=");
2825 TimeUtils.formatDuration(mNextIdlePendingDelay, pw);
2826 pw.println();
2827 }
2828 if (mNextIdleDelay != 0) {
2829 pw.print(" mNextIdleDelay=");
2830 TimeUtils.formatDuration(mNextIdleDelay, pw);
2831 pw.println();
2832 }
Dianne Hackborn953fc942016-03-29 15:36:24 -07002833 if (mNextLightIdleDelay != 0) {
2834 pw.print(" mNextIdleDelay=");
2835 TimeUtils.formatDuration(mNextLightIdleDelay, pw);
2836 pw.println();
2837 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002838 if (mNextLightAlarmTime != 0) {
2839 pw.print(" mNextLightAlarmTime=");
2840 TimeUtils.formatDuration(mNextLightAlarmTime, SystemClock.elapsedRealtime(), pw);
2841 pw.println();
2842 }
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002843 if (mCurIdleBudget != 0) {
2844 pw.print(" mCurIdleBudget=");
2845 TimeUtils.formatDuration(mCurIdleBudget, pw);
2846 pw.println();
2847 }
2848 if (mMaintenanceStartTime != 0) {
2849 pw.print(" mMaintenanceStartTime=");
2850 TimeUtils.formatDuration(mMaintenanceStartTime, SystemClock.elapsedRealtime(), pw);
2851 pw.println();
2852 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002853 if (mJobsActive) {
2854 pw.print(" mJobsActive="); pw.println(mJobsActive);
2855 }
2856 if (mAlarmsActive) {
2857 pw.print(" mAlarmsActive="); pw.println(mAlarmsActive);
2858 }
2859 if (mDownloadServiceActive != null) {
2860 pw.print(" mDownloadServiceActive="); pw.println(mDownloadServiceActive);
2861 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002862 }
2863 }
2864}