blob: 9f63e30d061afdac3038624b1e7062f43705b019 [file] [log] [blame]
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Amith Yamasaniaf575b92015-05-29 15:35:26 -070019import android.Manifest;
Sudheer Shankadc589ac2016-11-10 15:30:17 -080020import android.app.ActivityManager;
Dianne 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 Hackborn88c41352016-04-07 15:18:58 -070042import android.net.ConnectivityManager;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070043import android.net.INetworkPolicyManager;
Dianne Hackborn88c41352016-04-07 15:18:58 -070044import android.net.NetworkInfo;
Adam Lesinski31c05d12015-06-09 17:34:04 -070045import android.net.Uri;
Dianne Hackbornfd854ee2015-07-13 18:00:37 -070046import android.os.BatteryStats;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070047import android.os.Binder;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -070048import android.os.Bundle;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070049import android.os.Environment;
50import android.os.FileUtils;
51import android.os.Handler;
52import android.os.IDeviceIdleController;
Yao Chenca5edbb2016-01-13 14:44:36 -080053import android.os.IMaintenanceActivityListener;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070054import android.os.Looper;
55import android.os.Message;
56import android.os.PowerManager;
57import android.os.PowerManagerInternal;
Dianne Hackbornb6683c42015-06-18 17:40:33 -070058import android.os.Process;
Yao Chenca5edbb2016-01-13 14:44:36 -080059import android.os.RemoteCallbackList;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070060import android.os.RemoteException;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -070061import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070062import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070063import android.os.ShellCallback;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -070064import android.os.ShellCommand;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070065import android.os.SystemClock;
66import android.os.UserHandle;
Adam Lesinski31c05d12015-06-09 17:34:04 -070067import android.provider.Settings;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070068import android.util.ArrayMap;
69import android.util.ArraySet;
Adam Lesinski31c05d12015-06-09 17:34:04 -070070import android.util.KeyValueListParser;
Dianne Hackbornfd854ee2015-07-13 18:00:37 -070071import android.util.MutableLong;
72import android.util.Pair;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070073import android.util.Slog;
Dianne Hackbornfd854ee2015-07-13 18:00:37 -070074import android.util.SparseArray;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070075import android.util.SparseBooleanArray;
76import android.util.TimeUtils;
77import android.util.Xml;
78import android.view.Display;
Amith Yamasani520d8f22015-05-08 16:36:21 -070079
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070080import com.android.internal.app.IBatteryStats;
81import com.android.internal.os.AtomicFile;
82import com.android.internal.os.BackgroundThread;
83import com.android.internal.util.FastXmlSerializer;
84import com.android.internal.util.XmlUtils;
85import com.android.server.am.BatteryStatsService;
Amith Yamasani520d8f22015-05-08 16:36:21 -070086
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070087import org.xmlpull.v1.XmlPullParser;
88import org.xmlpull.v1.XmlPullParserException;
89import org.xmlpull.v1.XmlSerializer;
90
91import java.io.ByteArrayOutputStream;
92import java.io.File;
93import java.io.FileDescriptor;
94import java.io.FileInputStream;
95import java.io.FileNotFoundException;
96import java.io.FileOutputStream;
97import java.io.IOException;
98import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010099import java.nio.charset.StandardCharsets;
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700100import java.util.Arrays;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700101
102/**
103 * Keeps track of device idleness and drives low power mode based on that.
104 */
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700105public class DeviceIdleController extends SystemService
106 implements AnyMotionDetector.DeviceIdleCallback {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700107 private static final String TAG = "DeviceIdleController";
108
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700109 private static final boolean DEBUG = false;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700110
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700111 private static final boolean COMPRESS_TIME = false;
Amith Yamasani520d8f22015-05-08 16:36:21 -0700112
Dianne Hackborn953fc942016-03-29 15:36:24 -0700113 private static final int EVENT_BUFFER_SIZE = 100;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800114
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700115 private AlarmManager mAlarmManager;
116 private IBatteryStats mBatteryStats;
117 private PowerManagerInternal mLocalPowerManager;
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700118 private PowerManager mPowerManager;
Dianne Hackborn88c41352016-04-07 15:18:58 -0700119 private ConnectivityService mConnectivityService;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -0800120 private AlarmManagerService.LocalService mLocalAlarmManager;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700121 private INetworkPolicyManager mNetworkPolicyManager;
122 private DisplayManager mDisplayManager;
123 private SensorManager mSensorManager;
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700124 private Sensor mMotionSensor;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700125 private LocationManager mLocationManager;
126 private LocationRequest mLocationRequest;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700127 private Intent mIdleIntent;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700128 private Intent mLightIdleIntent;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700129 private Display mCurDisplay;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700130 private AnyMotionDetector mAnyMotionDetector;
Dianne Hackbornb6843652016-02-22 12:20:13 -0800131 private boolean mLightEnabled;
132 private boolean mDeepEnabled;
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700133 private boolean mForceIdle;
Dianne Hackborn88c41352016-04-07 15:18:58 -0700134 private boolean mNetworkConnected;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700135 private boolean mScreenOn;
136 private boolean mCharging;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700137 private boolean mNotMoving;
138 private boolean mLocating;
139 private boolean mLocated;
Joe LaPenna23d681b2015-08-27 15:12:11 -0700140 private boolean mHasGps;
141 private boolean mHasNetworkLocation;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700142 private Location mLastGenericLocation;
143 private Location mLastGpsLocation;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700144
145 /** Device is currently active. */
146 private static final int STATE_ACTIVE = 0;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700147 /** Device is inactive (screen off, no motion) and we are waiting to for idle. */
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700148 private static final int STATE_INACTIVE = 1;
149 /** Device is past the initial inactive period, and waiting for the next idle period. */
150 private static final int STATE_IDLE_PENDING = 2;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700151 /** Device is currently sensing motion. */
152 private static final int STATE_SENSING = 3;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700153 /** Device is currently finding location (and may still be sensing). */
154 private static final int STATE_LOCATING = 4;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700155 /** Device is in the idle state, trying to stay asleep as much as possible. */
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700156 private static final int STATE_IDLE = 5;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700157 /** Device is in the idle state, but temporarily out of idle to do regular maintenance. */
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700158 private static final int STATE_IDLE_MAINTENANCE = 6;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700159 private static String stateToString(int state) {
160 switch (state) {
161 case STATE_ACTIVE: return "ACTIVE";
162 case STATE_INACTIVE: return "INACTIVE";
163 case STATE_IDLE_PENDING: return "IDLE_PENDING";
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700164 case STATE_SENSING: return "SENSING";
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700165 case STATE_LOCATING: return "LOCATING";
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700166 case STATE_IDLE: return "IDLE";
167 case STATE_IDLE_MAINTENANCE: return "IDLE_MAINTENANCE";
168 default: return Integer.toString(state);
169 }
170 }
171
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700172 /** Device is currently active. */
173 private static final int LIGHT_STATE_ACTIVE = 0;
174 /** Device is inactive (screen off) and we are waiting to for the first light idle. */
175 private static final int LIGHT_STATE_INACTIVE = 1;
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700176 /** Device is about to go idle for the first time, wait for current work to complete. */
177 private static final int LIGHT_STATE_PRE_IDLE = 3;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700178 /** Device is in the light idle state, trying to stay asleep as much as possible. */
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700179 private static final int LIGHT_STATE_IDLE = 4;
Dianne Hackborn88c41352016-04-07 15:18:58 -0700180 /** Device is in the light idle state, we want to go in to idle maintenance but are
181 * waiting for network connectivity before doing so. */
182 private static final int LIGHT_STATE_WAITING_FOR_NETWORK = 5;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700183 /** Device is in the light idle state, but temporarily out of idle to do regular maintenance. */
Dianne Hackborn88c41352016-04-07 15:18:58 -0700184 private static final int LIGHT_STATE_IDLE_MAINTENANCE = 6;
Dianne Hackbornb6843652016-02-22 12:20:13 -0800185 /** Device light idle state is overriden, now applying deep doze state. */
Dianne Hackborn88c41352016-04-07 15:18:58 -0700186 private static final int LIGHT_STATE_OVERRIDE = 7;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700187 private static String lightStateToString(int state) {
188 switch (state) {
189 case LIGHT_STATE_ACTIVE: return "ACTIVE";
190 case LIGHT_STATE_INACTIVE: return "INACTIVE";
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700191 case LIGHT_STATE_PRE_IDLE: return "PRE_IDLE";
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700192 case LIGHT_STATE_IDLE: return "IDLE";
Dianne Hackborn88c41352016-04-07 15:18:58 -0700193 case LIGHT_STATE_WAITING_FOR_NETWORK: return "WAITING_FOR_NETWORK";
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700194 case LIGHT_STATE_IDLE_MAINTENANCE: return "IDLE_MAINTENANCE";
195 case LIGHT_STATE_OVERRIDE: return "OVERRIDE";
196 default: return Integer.toString(state);
197 }
198 }
199
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700200 private int mState;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700201 private int mLightState;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700202
203 private long mInactiveTimeout;
204 private long mNextAlarmTime;
205 private long mNextIdlePendingDelay;
206 private long mNextIdleDelay;
Dianne Hackborn953fc942016-03-29 15:36:24 -0700207 private long mNextLightIdleDelay;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700208 private long mNextLightAlarmTime;
Kevin Gabayan92f15e62016-04-04 17:52:22 -0700209 private long mNextSensingTimeoutAlarmTime;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800210 private long mCurIdleBudget;
211 private long mMaintenanceStartTime;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700212
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800213 private int mActiveIdleOpCount;
Joe Onorato8f0e9ced2016-12-08 17:48:49 -0800214 private PowerManager.WakeLock mActiveIdleWakeLock; // held when there are operations in progress
215 private PowerManager.WakeLock mGoingIdleWakeLock; // held when we are going idle so hardware
216 // (especially NetworkPolicyManager) can shut
217 // down.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800218 private boolean mJobsActive;
219 private boolean mAlarmsActive;
Yao Chenca5edbb2016-01-13 14:44:36 -0800220 private boolean mReportedMaintenanceActivity;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800221
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700222 public final AtomicFile mConfigFile;
223
Yao Chenca5edbb2016-01-13 14:44:36 -0800224 private final RemoteCallbackList<IMaintenanceActivityListener> mMaintenanceActivityListeners =
225 new RemoteCallbackList<IMaintenanceActivityListener>();
226
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700227 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700228 * Package names the system has white-listed to opt out of power save restrictions,
229 * except for device idle mode.
230 */
231 private final ArrayMap<String, Integer> mPowerSaveWhitelistAppsExceptIdle = new ArrayMap<>();
232
233 /**
234 * Package names the system has white-listed to opt out of power save restrictions for
235 * all modes.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700236 */
237 private final ArrayMap<String, Integer> mPowerSaveWhitelistApps = new ArrayMap<>();
238
239 /**
240 * Package names the user has white-listed to opt out of power save restrictions.
241 */
242 private final ArrayMap<String, Integer> mPowerSaveWhitelistUserApps = new ArrayMap<>();
243
244 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700245 * App IDs of built-in system apps that have been white-listed except for idle modes.
246 */
247 private final SparseBooleanArray mPowerSaveWhitelistSystemAppIdsExceptIdle
248 = new SparseBooleanArray();
249
250 /**
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700251 * App IDs of built-in system apps that have been white-listed.
252 */
253 private final SparseBooleanArray mPowerSaveWhitelistSystemAppIds = new SparseBooleanArray();
254
255 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700256 * App IDs that have been white-listed to opt out of power save restrictions, except
257 * for device idle modes.
258 */
259 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
260
261 /**
262 * Current app IDs that are in the complete power save white list, but shouldn't be
263 * excluded from idle modes. This array can be shared with others because it will not be
264 * modified once set.
265 */
266 private int[] mPowerSaveWhitelistExceptIdleAppIdArray = new int[0];
267
268 /**
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700269 * App IDs that have been white-listed to opt out of power save restrictions.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700270 */
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700271 private final SparseBooleanArray mPowerSaveWhitelistAllAppIds = new SparseBooleanArray();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700272
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700273 /**
274 * Current app IDs that are in the complete power save white list. This array can
275 * be shared with others because it will not be modified once set.
276 */
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700277 private int[] mPowerSaveWhitelistAllAppIdArray = new int[0];
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700278
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700279 /**
Dianne Hackborn262ae5c2016-02-10 16:28:29 -0800280 * App IDs that have been white-listed by the user to opt out of power save restrictions.
281 */
282 private final SparseBooleanArray mPowerSaveWhitelistUserAppIds = new SparseBooleanArray();
283
284 /**
285 * Current app IDs that are in the user power save white list. This array can
286 * be shared with others because it will not be modified once set.
287 */
288 private int[] mPowerSaveWhitelistUserAppIdArray = new int[0];
289
290 /**
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700291 * List of end times for UIDs that are temporarily marked as being allowed to access
292 * the network and acquire wakelocks. Times are in milliseconds.
293 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700294 private final SparseArray<Pair<MutableLong, String>> mTempWhitelistAppIdEndTimes
295 = new SparseArray<>();
296
297 /**
298 * Callback to the NetworkPolicyManagerService to tell it that the temp whitelist has changed.
299 */
300 Runnable mNetworkPolicyTempWhitelistCallback;
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700301
302 /**
303 * Current app IDs of temporarily whitelist apps for high-priority messages.
304 */
305 private int[] mTempWhitelistAppIdArray = new int[0];
306
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800307 private static final int EVENT_NULL = 0;
308 private static final int EVENT_NORMAL = 1;
309 private static final int EVENT_LIGHT_IDLE = 2;
310 private static final int EVENT_LIGHT_MAINTENANCE = 3;
Dianne Hackbornb6843652016-02-22 12:20:13 -0800311 private static final int EVENT_DEEP_IDLE = 4;
312 private static final int EVENT_DEEP_MAINTENANCE = 5;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800313
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -0700314 private final int[] mEventCmds = new int[EVENT_BUFFER_SIZE];
315 private final long[] mEventTimes = new long[EVENT_BUFFER_SIZE];
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800316
317 private void addEvent(int cmd) {
318 if (mEventCmds[0] != cmd) {
319 System.arraycopy(mEventCmds, 0, mEventCmds, 1, EVENT_BUFFER_SIZE - 1);
320 System.arraycopy(mEventTimes, 0, mEventTimes, 1, EVENT_BUFFER_SIZE - 1);
321 mEventCmds[0] = cmd;
322 mEventTimes[0] = SystemClock.elapsedRealtime();
323 }
324 }
325
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700326 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
327 @Override public void onReceive(Context context, Intent intent) {
Dianne Hackborn88c41352016-04-07 15:18:58 -0700328 switch (intent.getAction()) {
329 case ConnectivityManager.CONNECTIVITY_ACTION: {
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -0700330 updateConnectivityState(intent);
Dianne Hackborn88c41352016-04-07 15:18:58 -0700331 } break;
332 case Intent.ACTION_BATTERY_CHANGED: {
333 synchronized (DeviceIdleController.this) {
334 int plugged = intent.getIntExtra("plugged", 0);
335 updateChargingLocked(plugged != 0);
336 }
337 } break;
338 case Intent.ACTION_PACKAGE_REMOVED: {
339 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
340 Uri data = intent.getData();
341 String ssp;
342 if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
343 removePowerSaveWhitelistAppInternal(ssp);
344 }
345 }
346 } break;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700347 }
348 }
349 };
350
351 private final AlarmManager.OnAlarmListener mLightAlarmListener
352 = new AlarmManager.OnAlarmListener() {
353 @Override
354 public void onAlarm() {
355 synchronized (DeviceIdleController.this) {
356 stepLightIdleStateLocked("s:alarm");
357 }
358 }
359 };
360
Kevin Gabayan92f15e62016-04-04 17:52:22 -0700361 private final AlarmManager.OnAlarmListener mSensingTimeoutAlarmListener
362 = new AlarmManager.OnAlarmListener() {
363 @Override
364 public void onAlarm() {
365 if (mState == STATE_SENSING) {
366 synchronized (DeviceIdleController.this) {
367 becomeInactiveIfAppropriateLocked();
368 }
369 }
370 }
371 };
372
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700373 private final AlarmManager.OnAlarmListener mDeepAlarmListener
374 = new AlarmManager.OnAlarmListener() {
375 @Override
376 public void onAlarm() {
377 synchronized (DeviceIdleController.this) {
378 stepIdleStateLocked("s:alarm");
379 }
380 }
381 };
382
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800383 private final BroadcastReceiver mIdleStartedDoneReceiver = new BroadcastReceiver() {
384 @Override public void onReceive(Context context, Intent intent) {
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700385 // When coming out of a deep idle, we will add in some delay before we allow
386 // the system to settle down and finish the maintenance window. This is
387 // to give a chance for any pending work to be scheduled.
388 if (PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED.equals(intent.getAction())) {
389 mHandler.sendEmptyMessageDelayed(MSG_FINISH_IDLE_OP,
390 mConstants.MIN_DEEP_MAINTENANCE_TIME);
391 } else {
392 mHandler.sendEmptyMessageDelayed(MSG_FINISH_IDLE_OP,
393 mConstants.MIN_LIGHT_MAINTENANCE_TIME);
394 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800395 }
396 };
397
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700398 private final DisplayManager.DisplayListener mDisplayListener
399 = new DisplayManager.DisplayListener() {
400 @Override public void onDisplayAdded(int displayId) {
401 }
402
403 @Override public void onDisplayRemoved(int displayId) {
404 }
405
406 @Override public void onDisplayChanged(int displayId) {
407 if (displayId == Display.DEFAULT_DISPLAY) {
408 synchronized (DeviceIdleController.this) {
409 updateDisplayLocked();
410 }
411 }
412 }
413 };
414
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700415 private final class MotionListener extends TriggerEventListener
416 implements SensorEventListener {
417
418 boolean active = false;
419
420 @Override
421 public void onTrigger(TriggerEvent event) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700422 synchronized (DeviceIdleController.this) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700423 active = false;
424 motionLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700425 }
426 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700427
428 @Override
429 public void onSensorChanged(SensorEvent event) {
430 synchronized (DeviceIdleController.this) {
431 mSensorManager.unregisterListener(this, mMotionSensor);
432 active = false;
433 motionLocked();
434 }
435 }
436
437 @Override
438 public void onAccuracyChanged(Sensor sensor, int accuracy) {}
439
440 public boolean registerLocked() {
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700441 boolean success;
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700442 if (mMotionSensor.getReportingMode() == Sensor.REPORTING_MODE_ONE_SHOT) {
443 success = mSensorManager.requestTriggerSensor(mMotionListener, mMotionSensor);
444 } else {
445 success = mSensorManager.registerListener(
446 mMotionListener, mMotionSensor, SensorManager.SENSOR_DELAY_NORMAL);
447 }
448 if (success) {
449 active = true;
450 } else {
451 Slog.e(TAG, "Unable to register for " + mMotionSensor);
452 }
453 return success;
454 }
455
456 public void unregisterLocked() {
457 if (mMotionSensor.getReportingMode() == Sensor.REPORTING_MODE_ONE_SHOT) {
458 mSensorManager.cancelTriggerSensor(mMotionListener, mMotionSensor);
459 } else {
460 mSensorManager.unregisterListener(mMotionListener);
461 }
462 active = false;
463 }
464 }
465 private final MotionListener mMotionListener = new MotionListener();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700466
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700467 private final LocationListener mGenericLocationListener = new LocationListener() {
468 @Override
469 public void onLocationChanged(Location location) {
470 synchronized (DeviceIdleController.this) {
471 receivedGenericLocationLocked(location);
472 }
473 }
474
475 @Override
476 public void onStatusChanged(String provider, int status, Bundle extras) {
477 }
478
479 @Override
480 public void onProviderEnabled(String provider) {
481 }
482
483 @Override
484 public void onProviderDisabled(String provider) {
485 }
486 };
487
488 private final LocationListener mGpsLocationListener = new LocationListener() {
489 @Override
490 public void onLocationChanged(Location location) {
491 synchronized (DeviceIdleController.this) {
492 receivedGpsLocationLocked(location);
493 }
494 }
495
496 @Override
497 public void onStatusChanged(String provider, int status, Bundle extras) {
498 }
499
500 @Override
501 public void onProviderEnabled(String provider) {
502 }
503
504 @Override
505 public void onProviderDisabled(String provider) {
506 }
507 };
508
Adam Lesinski31c05d12015-06-09 17:34:04 -0700509 /**
510 * All times are in milliseconds. These constants are kept synchronized with the system
511 * global Settings. Any access to this class or its fields should be done while
512 * holding the DeviceIdleController lock.
513 */
Dianne Hackborna750a632015-06-16 17:18:23 -0700514 private final class Constants extends ContentObserver {
Adam Lesinski31c05d12015-06-09 17:34:04 -0700515 // Key names stored in the settings value.
Dianne Hackborn953fc942016-03-29 15:36:24 -0700516 private static final String KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT
517 = "light_after_inactive_to";
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700518 private static final String KEY_LIGHT_PRE_IDLE_TIMEOUT = "light_pre_idle_to";
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700519 private static final String KEY_LIGHT_IDLE_TIMEOUT = "light_idle_to";
Dianne Hackborn953fc942016-03-29 15:36:24 -0700520 private static final String KEY_LIGHT_IDLE_FACTOR = "light_idle_factor";
521 private static final String KEY_LIGHT_MAX_IDLE_TIMEOUT = "light_max_idle_to";
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800522 private static final String KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET
523 = "light_idle_maintenance_min_budget";
524 private static final String KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET
525 = "light_idle_maintenance_max_budget";
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700526 private static final String KEY_MIN_LIGHT_MAINTENANCE_TIME = "min_light_maintenance_time";
527 private static final String KEY_MIN_DEEP_MAINTENANCE_TIME = "min_deep_maintenance_time";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700528 private static final String KEY_INACTIVE_TIMEOUT = "inactive_to";
529 private static final String KEY_SENSING_TIMEOUT = "sensing_to";
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700530 private static final String KEY_LOCATING_TIMEOUT = "locating_to";
531 private static final String KEY_LOCATION_ACCURACY = "location_accuracy";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700532 private static final String KEY_MOTION_INACTIVE_TIMEOUT = "motion_inactive_to";
533 private static final String KEY_IDLE_AFTER_INACTIVE_TIMEOUT = "idle_after_inactive_to";
534 private static final String KEY_IDLE_PENDING_TIMEOUT = "idle_pending_to";
535 private static final String KEY_MAX_IDLE_PENDING_TIMEOUT = "max_idle_pending_to";
536 private static final String KEY_IDLE_PENDING_FACTOR = "idle_pending_factor";
537 private static final String KEY_IDLE_TIMEOUT = "idle_to";
538 private static final String KEY_MAX_IDLE_TIMEOUT = "max_idle_to";
539 private static final String KEY_IDLE_FACTOR = "idle_factor";
540 private static final String KEY_MIN_TIME_TO_ALARM = "min_time_to_alarm";
541 private static final String KEY_MAX_TEMP_APP_WHITELIST_DURATION =
542 "max_temp_app_whitelist_duration";
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700543 private static final String KEY_MMS_TEMP_APP_WHITELIST_DURATION =
544 "mms_temp_app_whitelist_duration";
Dianne Hackborn451c3462015-07-21 17:39:46 -0700545 private static final String KEY_SMS_TEMP_APP_WHITELIST_DURATION =
546 "sms_temp_app_whitelist_duration";
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700547 private static final String KEY_NOTIFICATION_WHITELIST_DURATION =
548 "notification_whitelist_duration";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700549
550 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700551 * This is the time, after becoming inactive, that we go in to the first
552 * light-weight idle mode.
553 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
554 * @see #KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT
555 */
556 public long LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT;
557
558 /**
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700559 * This is amount of time we will wait from the point where we decide we would
560 * like to go idle until we actually do, while waiting for jobs and other current
561 * activity to finish.
562 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
563 * @see #KEY_LIGHT_PRE_IDLE_TIMEOUT
564 */
565 public long LIGHT_PRE_IDLE_TIMEOUT;
566
567 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700568 * This is the initial time that we will run in idle maintenance mode.
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700569 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
570 * @see #KEY_LIGHT_IDLE_TIMEOUT
571 */
572 public long LIGHT_IDLE_TIMEOUT;
573
574 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700575 * Scaling factor to apply to the light idle mode time each time we complete a cycle.
576 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
577 * @see #KEY_LIGHT_IDLE_FACTOR
578 */
579 public float LIGHT_IDLE_FACTOR;
580
581 /**
582 * This is the maximum time we will run in idle maintenence mode.
583 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
584 * @see #KEY_LIGHT_MAX_IDLE_TIMEOUT
585 */
586 public long LIGHT_MAX_IDLE_TIMEOUT;
587
588 /**
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800589 * This is the minimum amount of time we want to make available for maintenance mode
590 * when lightly idling. That is, we will always have at least this amount of time
591 * available maintenance before timing out and cutting off maintenance mode.
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700592 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800593 * @see #KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700594 */
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800595 public long LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
596
597 /**
598 * This is the maximum amount of time we want to make available for maintenance mode
599 * when lightly idling. That is, if the system isn't using up its minimum maintenance
600 * budget and this time is being added to the budget reserve, this is the maximum
601 * reserve size we will allow to grow and thus the maximum amount of time we will
602 * allow for the maintenance window.
603 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
604 * @see #KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET
605 */
606 public long LIGHT_IDLE_MAINTENANCE_MAX_BUDGET;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700607
608 /**
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700609 * This is the minimum amount of time that we will stay in maintenance mode after
610 * a light doze. We have this minimum to allow various things to respond to switching
611 * in to maintenance mode and scheduling their work -- otherwise we may
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700612 * see there is nothing to do (no jobs pending) and go out of maintenance
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700613 * mode immediately.
614 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
615 * @see #KEY_MIN_LIGHT_MAINTENANCE_TIME
616 */
617 public long MIN_LIGHT_MAINTENANCE_TIME;
618
619 /**
620 * This is the minimum amount of time that we will stay in maintenance mode after
621 * a full doze. We have this minimum to allow various things to respond to switching
622 * in to maintenance mode and scheduling their work -- otherwise we may
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700623 * see there is nothing to do (no jobs pending) and go out of maintenance
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700624 * mode immediately.
625 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
626 * @see #KEY_MIN_DEEP_MAINTENANCE_TIME
627 */
628 public long MIN_DEEP_MAINTENANCE_TIME;
629
630 /**
Adam Lesinski31c05d12015-06-09 17:34:04 -0700631 * This is the time, after becoming inactive, at which we start looking at the
632 * motion sensor to determine if the device is being left alone. We don't do this
633 * immediately after going inactive just because we don't want to be continually running
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700634 * the motion sensor whenever the screen is off.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700635 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
636 * @see #KEY_INACTIVE_TIMEOUT
637 */
638 public long INACTIVE_TIMEOUT;
639
640 /**
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700641 * If we don't receive a callback from AnyMotion in this amount of time +
642 * {@link #LOCATING_TIMEOUT}, we will change from
Adam Lesinski31c05d12015-06-09 17:34:04 -0700643 * STATE_SENSING to STATE_INACTIVE, and any AnyMotion callbacks while not in STATE_SENSING
644 * will be ignored.
645 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
646 * @see #KEY_SENSING_TIMEOUT
647 */
648 public long SENSING_TIMEOUT;
649
650 /**
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700651 * This is how long we will wait to try to get a good location fix before going in to
652 * idle mode.
653 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
654 * @see #KEY_LOCATING_TIMEOUT
655 */
656 public long LOCATING_TIMEOUT;
657
658 /**
659 * The desired maximum accuracy (in meters) we consider the location to be good enough to go
660 * on to idle. We will be trying to get an accuracy fix at least this good or until
661 * {@link #LOCATING_TIMEOUT} expires.
662 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
663 * @see #KEY_LOCATION_ACCURACY
664 */
665 public float LOCATION_ACCURACY;
666
667 /**
Adam Lesinski31c05d12015-06-09 17:34:04 -0700668 * This is the time, after seeing motion, that we wait after becoming inactive from
669 * that until we start looking for motion again.
670 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
671 * @see #KEY_MOTION_INACTIVE_TIMEOUT
672 */
673 public long MOTION_INACTIVE_TIMEOUT;
674
675 /**
676 * This is the time, after the inactive timeout elapses, that we will wait looking
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700677 * for motion until we truly consider the device to be idle.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700678 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
679 * @see #KEY_IDLE_AFTER_INACTIVE_TIMEOUT
680 */
681 public long IDLE_AFTER_INACTIVE_TIMEOUT;
682
683 /**
684 * This is the initial time, after being idle, that we will allow ourself to be back
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700685 * in the IDLE_MAINTENANCE state allowing the system to run normally until we return to
686 * idle.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700687 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
688 * @see #KEY_IDLE_PENDING_TIMEOUT
689 */
690 public long IDLE_PENDING_TIMEOUT;
691
692 /**
693 * Maximum pending idle timeout (time spent running) we will be allowed to use.
694 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
695 * @see #KEY_MAX_IDLE_PENDING_TIMEOUT
696 */
697 public long MAX_IDLE_PENDING_TIMEOUT;
698
699 /**
700 * Scaling factor to apply to current pending idle timeout each time we cycle through
701 * that state.
702 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
703 * @see #KEY_IDLE_PENDING_FACTOR
704 */
705 public float IDLE_PENDING_FACTOR;
706
707 /**
708 * This is the initial time that we want to sit in the idle state before waking up
709 * again to return to pending idle and allowing normal work to run.
710 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
711 * @see #KEY_IDLE_TIMEOUT
712 */
713 public long IDLE_TIMEOUT;
714
715 /**
716 * Maximum idle duration we will be allowed to use.
717 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
718 * @see #KEY_MAX_IDLE_TIMEOUT
719 */
720 public long MAX_IDLE_TIMEOUT;
721
722 /**
723 * Scaling factor to apply to current idle timeout each time we cycle through that state.
724 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
725 * @see #KEY_IDLE_FACTOR
726 */
727 public float IDLE_FACTOR;
728
729 /**
730 * This is the minimum time we will allow until the next upcoming alarm for us to
731 * actually go in to idle mode.
732 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
733 * @see #KEY_MIN_TIME_TO_ALARM
734 */
735 public long MIN_TIME_TO_ALARM;
736
737 /**
738 * Max amount of time to temporarily whitelist an app when it receives a high priority
739 * tickle.
740 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
741 * @see #KEY_MAX_TEMP_APP_WHITELIST_DURATION
742 */
743 public long MAX_TEMP_APP_WHITELIST_DURATION;
744
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700745 /**
746 * Amount of time we would like to whitelist an app that is receiving an MMS.
747 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
748 * @see #KEY_MMS_TEMP_APP_WHITELIST_DURATION
749 */
750 public long MMS_TEMP_APP_WHITELIST_DURATION;
751
Dianne Hackborn451c3462015-07-21 17:39:46 -0700752 /**
753 * Amount of time we would like to whitelist an app that is receiving an SMS.
754 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
755 * @see #KEY_SMS_TEMP_APP_WHITELIST_DURATION
756 */
757 public long SMS_TEMP_APP_WHITELIST_DURATION;
758
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700759 /**
760 * Amount of time we would like to whitelist an app that is handling a
761 * {@link android.app.PendingIntent} triggered by a {@link android.app.Notification}.
762 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
763 * @see #KEY_NOTIFICATION_WHITELIST_DURATION
764 */
765 public long NOTIFICATION_WHITELIST_DURATION;
766
Adam Lesinski31c05d12015-06-09 17:34:04 -0700767 private final ContentResolver mResolver;
Joe LaPennaf33b5bf2016-03-23 15:19:47 -0700768 private final boolean mHasWatch;
Adam Lesinski31c05d12015-06-09 17:34:04 -0700769 private final KeyValueListParser mParser = new KeyValueListParser(',');
770
771 public Constants(Handler handler, ContentResolver resolver) {
772 super(handler);
773 mResolver = resolver;
Joe LaPennaf33b5bf2016-03-23 15:19:47 -0700774 mHasWatch = getContext().getPackageManager().hasSystemFeature(
775 PackageManager.FEATURE_WATCH);
776 mResolver.registerContentObserver(Settings.Global.getUriFor(
777 mHasWatch ? Settings.Global.DEVICE_IDLE_CONSTANTS_WATCH
778 : Settings.Global.DEVICE_IDLE_CONSTANTS),
779 false, this);
Adam Lesinski31c05d12015-06-09 17:34:04 -0700780 updateConstants();
781 }
782
783 @Override
784 public void onChange(boolean selfChange, Uri uri) {
785 updateConstants();
786 }
787
788 private void updateConstants() {
789 synchronized (DeviceIdleController.this) {
790 try {
791 mParser.setString(Settings.Global.getString(mResolver,
Joe LaPennaf33b5bf2016-03-23 15:19:47 -0700792 mHasWatch ? Settings.Global.DEVICE_IDLE_CONSTANTS_WATCH
793 : Settings.Global.DEVICE_IDLE_CONSTANTS));
Adam Lesinski31c05d12015-06-09 17:34:04 -0700794 } catch (IllegalArgumentException e) {
795 // Failed to parse the settings string, log this and move on
796 // with defaults.
797 Slog.e(TAG, "Bad device idle settings", e);
798 }
799
Dianne Hackborn953fc942016-03-29 15:36:24 -0700800 LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT = mParser.getLong(
801 KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT,
802 !COMPRESS_TIME ? 5 * 60 * 1000L : 15 * 1000L);
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700803 LIGHT_PRE_IDLE_TIMEOUT = mParser.getLong(KEY_LIGHT_PRE_IDLE_TIMEOUT,
804 !COMPRESS_TIME ? 10 * 60 * 1000L : 30 * 1000L);
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700805 LIGHT_IDLE_TIMEOUT = mParser.getLong(KEY_LIGHT_IDLE_TIMEOUT,
Dianne Hackborn953fc942016-03-29 15:36:24 -0700806 !COMPRESS_TIME ? 5 * 60 * 1000L : 15 * 1000L);
807 LIGHT_IDLE_FACTOR = mParser.getFloat(KEY_LIGHT_IDLE_FACTOR,
808 2f);
809 LIGHT_MAX_IDLE_TIMEOUT = mParser.getLong(KEY_LIGHT_MAX_IDLE_TIMEOUT,
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700810 !COMPRESS_TIME ? 15 * 60 * 1000L : 60 * 1000L);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800811 LIGHT_IDLE_MAINTENANCE_MIN_BUDGET = mParser.getLong(
812 KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET,
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700813 !COMPRESS_TIME ? 1 * 60 * 1000L : 15 * 1000L);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800814 LIGHT_IDLE_MAINTENANCE_MAX_BUDGET = mParser.getLong(
815 KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET,
816 !COMPRESS_TIME ? 5 * 60 * 1000L : 30 * 1000L);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700817 MIN_LIGHT_MAINTENANCE_TIME = mParser.getLong(
818 KEY_MIN_LIGHT_MAINTENANCE_TIME,
819 !COMPRESS_TIME ? 5 * 1000L : 1 * 1000L);
820 MIN_DEEP_MAINTENANCE_TIME = mParser.getLong(
821 KEY_MIN_DEEP_MAINTENANCE_TIME,
822 !COMPRESS_TIME ? 30 * 1000L : 5 * 1000L);
Joe LaPenna0c5d3e92016-03-24 13:29:56 -0700823 long inactiveTimeoutDefault = (mHasWatch ? 15 : 30) * 60 * 1000L;
Adam Lesinski31c05d12015-06-09 17:34:04 -0700824 INACTIVE_TIMEOUT = mParser.getLong(KEY_INACTIVE_TIMEOUT,
Joe LaPenna0c5d3e92016-03-24 13:29:56 -0700825 !COMPRESS_TIME ? inactiveTimeoutDefault : (inactiveTimeoutDefault / 10));
Adam Lesinski31c05d12015-06-09 17:34:04 -0700826 SENSING_TIMEOUT = mParser.getLong(KEY_SENSING_TIMEOUT,
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700827 !DEBUG ? 4 * 60 * 1000L : 60 * 1000L);
828 LOCATING_TIMEOUT = mParser.getLong(KEY_LOCATING_TIMEOUT,
829 !DEBUG ? 30 * 1000L : 15 * 1000L);
830 LOCATION_ACCURACY = mParser.getFloat(KEY_LOCATION_ACCURACY, 20);
Adam Lesinski31c05d12015-06-09 17:34:04 -0700831 MOTION_INACTIVE_TIMEOUT = mParser.getLong(KEY_MOTION_INACTIVE_TIMEOUT,
832 !COMPRESS_TIME ? 10 * 60 * 1000L : 60 * 1000L);
Joe LaPenna0c5d3e92016-03-24 13:29:56 -0700833 long idleAfterInactiveTimeout = (mHasWatch ? 15 : 30) * 60 * 1000L;
Adam Lesinski31c05d12015-06-09 17:34:04 -0700834 IDLE_AFTER_INACTIVE_TIMEOUT = mParser.getLong(KEY_IDLE_AFTER_INACTIVE_TIMEOUT,
Joe LaPenna0c5d3e92016-03-24 13:29:56 -0700835 !COMPRESS_TIME ? idleAfterInactiveTimeout
836 : (idleAfterInactiveTimeout / 10));
Adam Lesinski31c05d12015-06-09 17:34:04 -0700837 IDLE_PENDING_TIMEOUT = mParser.getLong(KEY_IDLE_PENDING_TIMEOUT,
838 !COMPRESS_TIME ? 5 * 60 * 1000L : 30 * 1000L);
839 MAX_IDLE_PENDING_TIMEOUT = mParser.getLong(KEY_MAX_IDLE_PENDING_TIMEOUT,
840 !COMPRESS_TIME ? 10 * 60 * 1000L : 60 * 1000L);
841 IDLE_PENDING_FACTOR = mParser.getFloat(KEY_IDLE_PENDING_FACTOR,
842 2f);
843 IDLE_TIMEOUT = mParser.getLong(KEY_IDLE_TIMEOUT,
844 !COMPRESS_TIME ? 60 * 60 * 1000L : 6 * 60 * 1000L);
845 MAX_IDLE_TIMEOUT = mParser.getLong(KEY_MAX_IDLE_TIMEOUT,
846 !COMPRESS_TIME ? 6 * 60 * 60 * 1000L : 30 * 60 * 1000L);
847 IDLE_FACTOR = mParser.getFloat(KEY_IDLE_FACTOR,
848 2f);
849 MIN_TIME_TO_ALARM = mParser.getLong(KEY_MIN_TIME_TO_ALARM,
850 !COMPRESS_TIME ? 60 * 60 * 1000L : 6 * 60 * 1000L);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700851 MAX_TEMP_APP_WHITELIST_DURATION = mParser.getLong(
852 KEY_MAX_TEMP_APP_WHITELIST_DURATION, 5 * 60 * 1000L);
853 MMS_TEMP_APP_WHITELIST_DURATION = mParser.getLong(
Dianne Hackborn0b6134b2015-07-14 18:48:07 -0700854 KEY_MMS_TEMP_APP_WHITELIST_DURATION, 60 * 1000L);
Dianne Hackborn451c3462015-07-21 17:39:46 -0700855 SMS_TEMP_APP_WHITELIST_DURATION = mParser.getLong(
856 KEY_SMS_TEMP_APP_WHITELIST_DURATION, 20 * 1000L);
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700857 NOTIFICATION_WHITELIST_DURATION = mParser.getLong(
858 KEY_NOTIFICATION_WHITELIST_DURATION, 30 * 1000L);
Adam Lesinski31c05d12015-06-09 17:34:04 -0700859 }
860 }
861
862 void dump(PrintWriter pw) {
863 pw.println(" Settings:");
864
Dianne Hackborn953fc942016-03-29 15:36:24 -0700865 pw.print(" "); pw.print(KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT); pw.print("=");
866 TimeUtils.formatDuration(LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT, pw);
867 pw.println();
868
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700869 pw.print(" "); pw.print(KEY_LIGHT_PRE_IDLE_TIMEOUT); pw.print("=");
870 TimeUtils.formatDuration(LIGHT_PRE_IDLE_TIMEOUT, pw);
871 pw.println();
872
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700873 pw.print(" "); pw.print(KEY_LIGHT_IDLE_TIMEOUT); pw.print("=");
874 TimeUtils.formatDuration(LIGHT_IDLE_TIMEOUT, pw);
875 pw.println();
876
Dianne Hackborn953fc942016-03-29 15:36:24 -0700877 pw.print(" "); pw.print(KEY_LIGHT_IDLE_FACTOR); pw.print("=");
878 pw.print(LIGHT_IDLE_FACTOR);
879 pw.println();
880
881 pw.print(" "); pw.print(KEY_LIGHT_MAX_IDLE_TIMEOUT); pw.print("=");
882 TimeUtils.formatDuration(LIGHT_MAX_IDLE_TIMEOUT, pw);
883 pw.println();
884
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800885 pw.print(" "); pw.print(KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET); pw.print("=");
886 TimeUtils.formatDuration(LIGHT_IDLE_MAINTENANCE_MIN_BUDGET, pw);
887 pw.println();
888
889 pw.print(" "); pw.print(KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET); pw.print("=");
890 TimeUtils.formatDuration(LIGHT_IDLE_MAINTENANCE_MAX_BUDGET, pw);
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700891 pw.println();
892
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700893 pw.print(" "); pw.print(KEY_MIN_LIGHT_MAINTENANCE_TIME); pw.print("=");
894 TimeUtils.formatDuration(MIN_LIGHT_MAINTENANCE_TIME, pw);
895 pw.println();
896
897 pw.print(" "); pw.print(KEY_MIN_DEEP_MAINTENANCE_TIME); pw.print("=");
898 TimeUtils.formatDuration(MIN_DEEP_MAINTENANCE_TIME, pw);
899 pw.println();
900
Dianne Hackborna750a632015-06-16 17:18:23 -0700901 pw.print(" "); pw.print(KEY_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700902 TimeUtils.formatDuration(INACTIVE_TIMEOUT, pw);
903 pw.println();
904
Dianne Hackborna750a632015-06-16 17:18:23 -0700905 pw.print(" "); pw.print(KEY_SENSING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700906 TimeUtils.formatDuration(SENSING_TIMEOUT, pw);
907 pw.println();
908
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700909 pw.print(" "); pw.print(KEY_LOCATING_TIMEOUT); pw.print("=");
910 TimeUtils.formatDuration(LOCATING_TIMEOUT, pw);
911 pw.println();
912
913 pw.print(" "); pw.print(KEY_LOCATION_ACCURACY); pw.print("=");
914 pw.print(LOCATION_ACCURACY); pw.print("m");
915 pw.println();
916
Dianne Hackborna750a632015-06-16 17:18:23 -0700917 pw.print(" "); pw.print(KEY_MOTION_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700918 TimeUtils.formatDuration(MOTION_INACTIVE_TIMEOUT, pw);
919 pw.println();
920
Dianne Hackborna750a632015-06-16 17:18:23 -0700921 pw.print(" "); pw.print(KEY_IDLE_AFTER_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700922 TimeUtils.formatDuration(IDLE_AFTER_INACTIVE_TIMEOUT, pw);
923 pw.println();
924
Dianne Hackborna750a632015-06-16 17:18:23 -0700925 pw.print(" "); pw.print(KEY_IDLE_PENDING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700926 TimeUtils.formatDuration(IDLE_PENDING_TIMEOUT, pw);
927 pw.println();
928
Dianne Hackborna750a632015-06-16 17:18:23 -0700929 pw.print(" "); pw.print(KEY_MAX_IDLE_PENDING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700930 TimeUtils.formatDuration(MAX_IDLE_PENDING_TIMEOUT, pw);
931 pw.println();
932
Dianne Hackborna750a632015-06-16 17:18:23 -0700933 pw.print(" "); pw.print(KEY_IDLE_PENDING_FACTOR); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700934 pw.println(IDLE_PENDING_FACTOR);
935
Dianne Hackborna750a632015-06-16 17:18:23 -0700936 pw.print(" "); pw.print(KEY_IDLE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700937 TimeUtils.formatDuration(IDLE_TIMEOUT, pw);
938 pw.println();
939
Dianne Hackborna750a632015-06-16 17:18:23 -0700940 pw.print(" "); pw.print(KEY_MAX_IDLE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700941 TimeUtils.formatDuration(MAX_IDLE_TIMEOUT, pw);
942 pw.println();
943
Dianne Hackborna750a632015-06-16 17:18:23 -0700944 pw.print(" "); pw.print(KEY_IDLE_FACTOR); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700945 pw.println(IDLE_FACTOR);
946
Dianne Hackborna750a632015-06-16 17:18:23 -0700947 pw.print(" "); pw.print(KEY_MIN_TIME_TO_ALARM); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700948 TimeUtils.formatDuration(MIN_TIME_TO_ALARM, pw);
949 pw.println();
950
Dianne Hackborna750a632015-06-16 17:18:23 -0700951 pw.print(" "); pw.print(KEY_MAX_TEMP_APP_WHITELIST_DURATION); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700952 TimeUtils.formatDuration(MAX_TEMP_APP_WHITELIST_DURATION, pw);
953 pw.println();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700954
955 pw.print(" "); pw.print(KEY_MMS_TEMP_APP_WHITELIST_DURATION); pw.print("=");
956 TimeUtils.formatDuration(MMS_TEMP_APP_WHITELIST_DURATION, pw);
957 pw.println();
Dianne Hackborn451c3462015-07-21 17:39:46 -0700958
959 pw.print(" "); pw.print(KEY_SMS_TEMP_APP_WHITELIST_DURATION); pw.print("=");
960 TimeUtils.formatDuration(SMS_TEMP_APP_WHITELIST_DURATION, pw);
961 pw.println();
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700962
963 pw.print(" "); pw.print(KEY_NOTIFICATION_WHITELIST_DURATION); pw.print("=");
964 TimeUtils.formatDuration(NOTIFICATION_WHITELIST_DURATION, pw);
965 pw.println();
Adam Lesinski31c05d12015-06-09 17:34:04 -0700966 }
967 }
968
969 private Constants mConstants;
970
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700971 @Override
972 public void onAnyMotionResult(int result) {
973 if (DEBUG) Slog.d(TAG, "onAnyMotionResult(" + result + ")");
Kevin Gabayan92f15e62016-04-04 17:52:22 -0700974 if (result != AnyMotionDetector.RESULT_UNKNOWN) {
975 synchronized (this) {
976 cancelSensingTimeoutAlarmLocked();
977 }
978 }
Kevin Gabayandcf47012016-07-08 10:41:24 -0700979 if ((result == AnyMotionDetector.RESULT_MOVED) ||
980 (result == AnyMotionDetector.RESULT_UNKNOWN)) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700981 synchronized (this) {
Kevin Gabayandcf47012016-07-08 10:41:24 -0700982 handleMotionDetectedLocked(mConstants.INACTIVE_TIMEOUT, "non_stationary");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700983 }
984 } else if (result == AnyMotionDetector.RESULT_STATIONARY) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700985 if (mState == STATE_SENSING) {
986 // If we are currently sensing, it is time to move to locating.
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700987 synchronized (this) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700988 mNotMoving = true;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800989 stepIdleStateLocked("s:stationary");
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700990 }
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700991 } else if (mState == STATE_LOCATING) {
992 // If we are currently locating, note that we are not moving and step
993 // if we have located the position.
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700994 synchronized (this) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700995 mNotMoving = true;
996 if (mLocated) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800997 stepIdleStateLocked("s:stationary");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700998 }
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700999 }
1000 }
1001 }
1002 }
1003
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001004 private static final int MSG_WRITE_CONFIG = 1;
1005 private static final int MSG_REPORT_IDLE_ON = 2;
1006 private static final int MSG_REPORT_IDLE_ON_LIGHT = 3;
1007 private static final int MSG_REPORT_IDLE_OFF = 4;
1008 private static final int MSG_REPORT_ACTIVE = 5;
1009 private static final int MSG_TEMP_APP_WHITELIST_TIMEOUT = 6;
1010 private static final int MSG_REPORT_MAINTENANCE_ACTIVITY = 7;
1011 private static final int MSG_FINISH_IDLE_OP = 8;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001012
1013 final class MyHandler extends Handler {
1014 MyHandler(Looper looper) {
1015 super(looper);
1016 }
1017
1018 @Override public void handleMessage(Message msg) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001019 if (DEBUG) Slog.d(TAG, "handleMessage(" + msg.what + ")");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001020 switch (msg.what) {
1021 case MSG_WRITE_CONFIG: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001022 // Does not hold a wakelock. Just let this happen whenever.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001023 handleWriteConfigFile();
1024 } break;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001025 case MSG_REPORT_IDLE_ON:
1026 case MSG_REPORT_IDLE_ON_LIGHT: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001027 // mGoingIdleWakeLock is held at this point
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001028 EventLogTags.writeDeviceIdleOnStart();
Dianne Hackbornb6843652016-02-22 12:20:13 -08001029 final boolean deepChanged;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001030 final boolean lightChanged;
1031 if (msg.what == MSG_REPORT_IDLE_ON) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001032 deepChanged = mLocalPowerManager.setDeviceIdleMode(true);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001033 lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
1034 } else {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001035 deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001036 lightChanged = mLocalPowerManager.setLightDeviceIdleMode(true);
1037 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001038 try {
1039 mNetworkPolicyManager.setDeviceIdleMode(true);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001040 mBatteryStats.noteDeviceIdleMode(msg.what == MSG_REPORT_IDLE_ON
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07001041 ? BatteryStats.DEVICE_IDLE_MODE_DEEP
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001042 : BatteryStats.DEVICE_IDLE_MODE_LIGHT, null, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001043 } catch (RemoteException e) {
1044 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001045 if (deepChanged) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001046 getContext().sendBroadcastAsUser(mIdleIntent, UserHandle.ALL);
1047 }
1048 if (lightChanged) {
1049 getContext().sendBroadcastAsUser(mLightIdleIntent, UserHandle.ALL);
1050 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001051 EventLogTags.writeDeviceIdleOnComplete();
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001052 mGoingIdleWakeLock.release();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001053 } break;
1054 case MSG_REPORT_IDLE_OFF: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001055 // mActiveIdleWakeLock is held at this point
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001056 EventLogTags.writeDeviceIdleOffStart("unknown");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001057 final boolean deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001058 final boolean lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001059 try {
1060 mNetworkPolicyManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001061 mBatteryStats.noteDeviceIdleMode(BatteryStats.DEVICE_IDLE_MODE_OFF,
1062 null, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001063 } catch (RemoteException e) {
1064 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001065 if (deepChanged) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001066 incActiveIdleOps();
1067 getContext().sendOrderedBroadcastAsUser(mIdleIntent, UserHandle.ALL,
1068 null, mIdleStartedDoneReceiver, null, 0, null, null);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001069 }
1070 if (lightChanged) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001071 incActiveIdleOps();
1072 getContext().sendOrderedBroadcastAsUser(mLightIdleIntent, UserHandle.ALL,
1073 null, mIdleStartedDoneReceiver, null, 0, null, null);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001074 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001075 // Always start with one active op for the message being sent here.
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001076 // Now we are done!
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001077 decActiveIdleOps();
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001078 EventLogTags.writeDeviceIdleOffComplete();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001079 } break;
1080 case MSG_REPORT_ACTIVE: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001081 // The device is awake at this point, so no wakelock necessary.
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001082 String activeReason = (String)msg.obj;
1083 int activeUid = msg.arg1;
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001084 EventLogTags.writeDeviceIdleOffStart(
1085 activeReason != null ? activeReason : "unknown");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001086 final boolean deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001087 final boolean lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001088 try {
1089 mNetworkPolicyManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001090 mBatteryStats.noteDeviceIdleMode(BatteryStats.DEVICE_IDLE_MODE_OFF,
1091 activeReason, activeUid);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001092 } catch (RemoteException e) {
1093 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001094 if (deepChanged) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001095 getContext().sendBroadcastAsUser(mIdleIntent, UserHandle.ALL);
1096 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001097 if (lightChanged) {
1098 getContext().sendBroadcastAsUser(mLightIdleIntent, UserHandle.ALL);
1099 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001100 EventLogTags.writeDeviceIdleOffComplete();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001101 } break;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001102 case MSG_TEMP_APP_WHITELIST_TIMEOUT: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001103 // TODO: What is keeping the device awake at this point? Does it need to be?
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001104 int uid = msg.arg1;
1105 checkTempAppWhitelistTimeout(uid);
1106 } break;
Yao Chenca5edbb2016-01-13 14:44:36 -08001107 case MSG_REPORT_MAINTENANCE_ACTIVITY: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001108 // TODO: What is keeping the device awake at this point? Does it need to be?
Yao Chenca5edbb2016-01-13 14:44:36 -08001109 boolean active = (msg.arg1 == 1);
1110 final int size = mMaintenanceActivityListeners.beginBroadcast();
1111 try {
1112 for (int i = 0; i < size; i++) {
1113 try {
1114 mMaintenanceActivityListeners.getBroadcastItem(i)
1115 .onMaintenanceActivityChanged(active);
1116 } catch (RemoteException ignored) {
1117 }
1118 }
1119 } finally {
1120 mMaintenanceActivityListeners.finishBroadcast();
1121 }
1122 } break;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001123 case MSG_FINISH_IDLE_OP: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001124 // mActiveIdleWakeLock is held at this point
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001125 decActiveIdleOps();
1126 } break;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001127 }
1128 }
1129 }
1130
1131 final MyHandler mHandler;
1132
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001133 BinderService mBinderService;
1134
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001135 private final class BinderService extends IDeviceIdleController.Stub {
1136 @Override public void addPowerSaveWhitelistApp(String name) {
1137 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1138 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001139 long ident = Binder.clearCallingIdentity();
1140 try {
1141 addPowerSaveWhitelistAppInternal(name);
1142 } finally {
1143 Binder.restoreCallingIdentity(ident);
1144 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001145 }
1146
1147 @Override public void removePowerSaveWhitelistApp(String name) {
1148 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1149 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001150 long ident = Binder.clearCallingIdentity();
1151 try {
1152 removePowerSaveWhitelistAppInternal(name);
1153 } finally {
1154 Binder.restoreCallingIdentity(ident);
1155 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001156 }
1157
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001158 @Override public String[] getSystemPowerWhitelistExceptIdle() {
1159 return getSystemPowerWhitelistExceptIdleInternal();
1160 }
1161
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001162 @Override public String[] getSystemPowerWhitelist() {
1163 return getSystemPowerWhitelistInternal();
1164 }
1165
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001166 @Override public String[] getUserPowerWhitelist() {
1167 return getUserPowerWhitelistInternal();
1168 }
1169
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001170 @Override public String[] getFullPowerWhitelistExceptIdle() {
1171 return getFullPowerWhitelistExceptIdleInternal();
1172 }
1173
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001174 @Override public String[] getFullPowerWhitelist() {
1175 return getFullPowerWhitelistInternal();
1176 }
1177
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001178 @Override public int[] getAppIdWhitelistExceptIdle() {
1179 return getAppIdWhitelistExceptIdleInternal();
1180 }
1181
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001182 @Override public int[] getAppIdWhitelist() {
1183 return getAppIdWhitelistInternal();
1184 }
1185
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001186 @Override public int[] getAppIdUserWhitelist() {
1187 return getAppIdUserWhitelistInternal();
1188 }
1189
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001190 @Override public int[] getAppIdTempWhitelist() {
1191 return getAppIdTempWhitelistInternal();
1192 }
1193
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001194 @Override public boolean isPowerSaveWhitelistExceptIdleApp(String name) {
1195 return isPowerSaveWhitelistExceptIdleAppInternal(name);
1196 }
1197
Amith Yamasani06bf8242015-05-08 16:36:21 -07001198 @Override public boolean isPowerSaveWhitelistApp(String name) {
1199 return isPowerSaveWhitelistAppInternal(name);
1200 }
1201
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001202 @Override public void addPowerSaveTempWhitelistApp(String packageName, long duration,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001203 int userId, String reason) throws RemoteException {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001204 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001205 }
1206
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001207 @Override public long addPowerSaveTempWhitelistAppForMms(String packageName,
1208 int userId, String reason) throws RemoteException {
1209 long duration = mConstants.MMS_TEMP_APP_WHITELIST_DURATION;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001210 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001211 return duration;
1212 }
1213
Dianne Hackborn451c3462015-07-21 17:39:46 -07001214 @Override public long addPowerSaveTempWhitelistAppForSms(String packageName,
1215 int userId, String reason) throws RemoteException {
1216 long duration = mConstants.SMS_TEMP_APP_WHITELIST_DURATION;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001217 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Dianne Hackborn451c3462015-07-21 17:39:46 -07001218 return duration;
1219 }
1220
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001221 @Override public void exitIdle(String reason) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001222 getContext().enforceCallingOrSelfPermission(Manifest.permission.DEVICE_POWER,
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001223 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001224 long ident = Binder.clearCallingIdentity();
1225 try {
1226 exitIdleInternal(reason);
1227 } finally {
1228 Binder.restoreCallingIdentity(ident);
1229 }
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001230 }
1231
Yao Chenca5edbb2016-01-13 14:44:36 -08001232 @Override public boolean registerMaintenanceActivityListener(
1233 IMaintenanceActivityListener listener) {
1234 return DeviceIdleController.this.registerMaintenanceActivityListener(listener);
1235 }
1236
1237 @Override public void unregisterMaintenanceActivityListener(
1238 IMaintenanceActivityListener listener) {
1239 DeviceIdleController.this.unregisterMaintenanceActivityListener(listener);
1240 }
1241
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001242 @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1243 DeviceIdleController.this.dump(fd, pw, args);
1244 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001245
1246 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07001247 FileDescriptor err, String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
1248 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001249 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001250 }
1251
Felipe Lemeef134662016-08-10 14:46:39 -07001252 public class LocalService {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001253 public void addPowerSaveTempWhitelistAppDirect(int appId, long duration, boolean sync,
1254 String reason) {
1255 addPowerSaveTempWhitelistAppDirectInternal(0, appId, duration, sync, reason);
1256 }
1257
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001258 public long getNotificationWhitelistDuration() {
1259 return mConstants.NOTIFICATION_WHITELIST_DURATION;
1260 }
1261
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001262 public void setNetworkPolicyTempWhitelistCallback(Runnable callback) {
1263 setNetworkPolicyTempWhitelistCallbackInternal(callback);
Dianne Hackborna750a632015-06-16 17:18:23 -07001264 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001265
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001266 public void setJobsActive(boolean active) {
1267 DeviceIdleController.this.setJobsActive(active);
1268 }
1269
1270 // Up-call from alarm manager.
1271 public void setAlarmsActive(boolean active) {
1272 DeviceIdleController.this.setAlarmsActive(active);
1273 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001274
1275 /**
1276 * Returns the array of app ids whitelisted by user. Take care not to
1277 * modify this, as it is a reference to the original copy. But the reference
1278 * can change when the list changes, so it needs to be re-acquired when
1279 * {@link PowerManager#ACTION_POWER_SAVE_WHITELIST_CHANGED} is sent.
1280 */
1281 public int[] getPowerSaveWhitelistUserAppIds() {
1282 return DeviceIdleController.this.getPowerSaveWhitelistUserAppIds();
1283 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001284 }
1285
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001286 public DeviceIdleController(Context context) {
1287 super(context);
1288 mConfigFile = new AtomicFile(new File(getSystemDir(), "deviceidle.xml"));
1289 mHandler = new MyHandler(BackgroundThread.getHandler().getLooper());
1290 }
1291
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001292 int[] getPowerSaveWhitelistUserAppIds() {
1293 synchronized (this) {
1294 return mPowerSaveWhitelistUserAppIdArray;
1295 }
1296 }
1297
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001298 private static File getSystemDir() {
1299 return new File(Environment.getDataDirectory(), "system");
1300 }
1301
1302 @Override
1303 public void onStart() {
1304 final PackageManager pm = getContext().getPackageManager();
1305
1306 synchronized (this) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001307 mLightEnabled = mDeepEnabled = getContext().getResources().getBoolean(
Dianne Hackborn92617032015-06-19 15:32:19 -07001308 com.android.internal.R.bool.config_enableAutoPowerModes);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001309 SystemConfig sysConfig = SystemConfig.getInstance();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001310 ArraySet<String> allowPowerExceptIdle = sysConfig.getAllowInPowerSaveExceptIdle();
1311 for (int i=0; i<allowPowerExceptIdle.size(); i++) {
1312 String pkg = allowPowerExceptIdle.valueAt(i);
1313 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001314 ApplicationInfo ai = pm.getApplicationInfo(pkg,
1315 PackageManager.MATCH_SYSTEM_ONLY);
1316 int appid = UserHandle.getAppId(ai.uid);
1317 mPowerSaveWhitelistAppsExceptIdle.put(ai.packageName, appid);
1318 mPowerSaveWhitelistSystemAppIdsExceptIdle.put(appid, true);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001319 } catch (PackageManager.NameNotFoundException e) {
1320 }
1321 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001322 ArraySet<String> allowPower = sysConfig.getAllowInPowerSave();
1323 for (int i=0; i<allowPower.size(); i++) {
1324 String pkg = allowPower.valueAt(i);
1325 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001326 ApplicationInfo ai = pm.getApplicationInfo(pkg,
1327 PackageManager.MATCH_SYSTEM_ONLY);
1328 int appid = UserHandle.getAppId(ai.uid);
1329 // These apps are on both the whitelist-except-idle as well
1330 // as the full whitelist, so they apply in all cases.
1331 mPowerSaveWhitelistAppsExceptIdle.put(ai.packageName, appid);
1332 mPowerSaveWhitelistSystemAppIdsExceptIdle.put(appid, true);
1333 mPowerSaveWhitelistApps.put(ai.packageName, appid);
1334 mPowerSaveWhitelistSystemAppIds.put(appid, true);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001335 } catch (PackageManager.NameNotFoundException e) {
1336 }
1337 }
1338
Adam Lesinski31c05d12015-06-09 17:34:04 -07001339 mConstants = new Constants(mHandler, getContext().getContentResolver());
1340
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001341 readConfigFileLocked();
1342 updateWhitelistAppIdsLocked();
1343
Dianne Hackborn88c41352016-04-07 15:18:58 -07001344 mNetworkConnected = true;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001345 mScreenOn = true;
1346 // Start out assuming we are charging. If we aren't, we will at least get
1347 // a battery update the next time the level drops.
1348 mCharging = true;
1349 mState = STATE_ACTIVE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001350 mLightState = LIGHT_STATE_ACTIVE;
Adam Lesinski31c05d12015-06-09 17:34:04 -07001351 mInactiveTimeout = mConstants.INACTIVE_TIMEOUT;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001352 }
1353
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001354 mBinderService = new BinderService();
1355 publishBinderService(Context.DEVICE_IDLE_CONTROLLER, mBinderService);
Dianne Hackborna750a632015-06-16 17:18:23 -07001356 publishLocalService(LocalService.class, new LocalService());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001357 }
1358
1359 @Override
1360 public void onBootPhase(int phase) {
1361 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1362 synchronized (this) {
1363 mAlarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
1364 mBatteryStats = BatteryStatsService.getService();
1365 mLocalPowerManager = getLocalService(PowerManagerInternal.class);
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001366 mPowerManager = getContext().getSystemService(PowerManager.class);
1367 mActiveIdleWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
1368 "deviceidle_maint");
1369 mActiveIdleWakeLock.setReferenceCounted(false);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001370 mGoingIdleWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
1371 "deviceidle_going_idle");
1372 mGoingIdleWakeLock.setReferenceCounted(true);
Dianne Hackborn88c41352016-04-07 15:18:58 -07001373 mConnectivityService = (ConnectivityService)ServiceManager.getService(
1374 Context.CONNECTIVITY_SERVICE);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001375 mLocalAlarmManager = getLocalService(AlarmManagerService.LocalService.class);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001376 mNetworkPolicyManager = INetworkPolicyManager.Stub.asInterface(
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001377 ServiceManager.getService(Context.NETWORK_POLICY_SERVICE));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001378 mDisplayManager = (DisplayManager) getContext().getSystemService(
1379 Context.DISPLAY_SERVICE);
1380 mSensorManager = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001381 int sigMotionSensorId = getContext().getResources().getInteger(
1382 com.android.internal.R.integer.config_autoPowerModeAnyMotionSensor);
1383 if (sigMotionSensorId > 0) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001384 mMotionSensor = mSensorManager.getDefaultSensor(sigMotionSensorId, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001385 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001386 if (mMotionSensor == null && getContext().getResources().getBoolean(
Joe LaPenna23d681b2015-08-27 15:12:11 -07001387 com.android.internal.R.bool.config_autoPowerModePreferWristTilt)) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001388 mMotionSensor = mSensorManager.getDefaultSensor(
1389 Sensor.TYPE_WRIST_TILT_GESTURE, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001390 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001391 if (mMotionSensor == null) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07001392 // As a last ditch, fall back to SMD.
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001393 mMotionSensor = mSensorManager.getDefaultSensor(
1394 Sensor.TYPE_SIGNIFICANT_MOTION, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001395 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001396
Joe LaPenna23d681b2015-08-27 15:12:11 -07001397 if (getContext().getResources().getBoolean(
1398 com.android.internal.R.bool.config_autoPowerModePrefetchLocation)) {
1399 mLocationManager = (LocationManager) getContext().getSystemService(
1400 Context.LOCATION_SERVICE);
1401 mLocationRequest = new LocationRequest()
1402 .setQuality(LocationRequest.ACCURACY_FINE)
1403 .setInterval(0)
1404 .setFastestInterval(0)
1405 .setNumUpdates(1);
1406 }
1407
1408 float angleThreshold = getContext().getResources().getInteger(
1409 com.android.internal.R.integer.config_autoPowerModeThresholdAngle) / 100f;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001410 mAnyMotionDetector = new AnyMotionDetector(
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001411 (PowerManager) getContext().getSystemService(Context.POWER_SERVICE),
Joe LaPenna23d681b2015-08-27 15:12:11 -07001412 mHandler, mSensorManager, this, angleThreshold);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001413
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001414 mIdleIntent = new Intent(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001415 mIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1416 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001417 mLightIdleIntent = new Intent(PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED);
1418 mLightIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1419 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001420
1421 IntentFilter filter = new IntentFilter();
1422 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001423 getContext().registerReceiver(mReceiver, filter);
Amith Yamasaniac59f75e2016-05-05 12:38:17 -07001424
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001425 filter = new IntentFilter();
1426 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1427 filter.addDataScheme("package");
Amith Yamasaniac59f75e2016-05-05 12:38:17 -07001428 getContext().registerReceiver(mReceiver, filter);
1429
Dianne Hackborn88c41352016-04-07 15:18:58 -07001430 filter = new IntentFilter();
1431 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001432 getContext().registerReceiver(mReceiver, filter);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001433
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001434 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001435 mLocalAlarmManager.setDeviceIdleUserWhitelist(mPowerSaveWhitelistUserAppIdArray);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001436 mDisplayManager.registerDisplayListener(mDisplayListener, null);
1437 updateDisplayLocked();
1438 }
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -07001439 updateConnectivityState(null);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001440 }
1441 }
1442
1443 public boolean addPowerSaveWhitelistAppInternal(String name) {
1444 synchronized (this) {
1445 try {
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001446 ApplicationInfo ai = getContext().getPackageManager().getApplicationInfo(name,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07001447 PackageManager.MATCH_ANY_USER);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001448 if (mPowerSaveWhitelistUserApps.put(name, UserHandle.getAppId(ai.uid)) == null) {
1449 reportPowerSaveWhitelistChangedLocked();
1450 updateWhitelistAppIdsLocked();
1451 writeConfigFileLocked();
1452 }
1453 return true;
1454 } catch (PackageManager.NameNotFoundException e) {
1455 return false;
1456 }
1457 }
1458 }
1459
1460 public boolean removePowerSaveWhitelistAppInternal(String name) {
1461 synchronized (this) {
1462 if (mPowerSaveWhitelistUserApps.remove(name) != null) {
1463 reportPowerSaveWhitelistChangedLocked();
1464 updateWhitelistAppIdsLocked();
1465 writeConfigFileLocked();
1466 return true;
1467 }
1468 }
1469 return false;
1470 }
1471
Felipe Lemef8a46232016-02-10 13:51:54 -08001472 public boolean getPowerSaveWhitelistAppInternal(String name) {
1473 synchronized (this) {
1474 return mPowerSaveWhitelistUserApps.containsKey(name);
1475 }
1476 }
1477
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001478 public String[] getSystemPowerWhitelistExceptIdleInternal() {
1479 synchronized (this) {
1480 int size = mPowerSaveWhitelistAppsExceptIdle.size();
1481 String[] apps = new String[size];
1482 for (int i = 0; i < size; i++) {
1483 apps[i] = mPowerSaveWhitelistAppsExceptIdle.keyAt(i);
1484 }
1485 return apps;
1486 }
1487 }
1488
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001489 public String[] getSystemPowerWhitelistInternal() {
1490 synchronized (this) {
1491 int size = mPowerSaveWhitelistApps.size();
1492 String[] apps = new String[size];
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001493 for (int i = 0; i < size; i++) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001494 apps[i] = mPowerSaveWhitelistApps.keyAt(i);
1495 }
1496 return apps;
1497 }
1498 }
1499
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001500 public String[] getUserPowerWhitelistInternal() {
1501 synchronized (this) {
1502 int size = mPowerSaveWhitelistUserApps.size();
1503 String[] apps = new String[size];
1504 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1505 apps[i] = mPowerSaveWhitelistUserApps.keyAt(i);
1506 }
1507 return apps;
1508 }
1509 }
1510
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001511 public String[] getFullPowerWhitelistExceptIdleInternal() {
1512 synchronized (this) {
1513 int size = mPowerSaveWhitelistAppsExceptIdle.size() + mPowerSaveWhitelistUserApps.size();
1514 String[] apps = new String[size];
1515 int cur = 0;
1516 for (int i = 0; i < mPowerSaveWhitelistAppsExceptIdle.size(); i++) {
1517 apps[cur] = mPowerSaveWhitelistAppsExceptIdle.keyAt(i);
1518 cur++;
1519 }
1520 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1521 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
1522 cur++;
1523 }
1524 return apps;
1525 }
1526 }
1527
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001528 public String[] getFullPowerWhitelistInternal() {
1529 synchronized (this) {
1530 int size = mPowerSaveWhitelistApps.size() + mPowerSaveWhitelistUserApps.size();
1531 String[] apps = new String[size];
1532 int cur = 0;
1533 for (int i = 0; i < mPowerSaveWhitelistApps.size(); i++) {
1534 apps[cur] = mPowerSaveWhitelistApps.keyAt(i);
1535 cur++;
1536 }
1537 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1538 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
1539 cur++;
1540 }
1541 return apps;
1542 }
1543 }
1544
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001545 public boolean isPowerSaveWhitelistExceptIdleAppInternal(String packageName) {
1546 synchronized (this) {
1547 return mPowerSaveWhitelistAppsExceptIdle.containsKey(packageName)
1548 || mPowerSaveWhitelistUserApps.containsKey(packageName);
1549 }
1550 }
1551
Amith Yamasani06bf8242015-05-08 16:36:21 -07001552 public boolean isPowerSaveWhitelistAppInternal(String packageName) {
1553 synchronized (this) {
1554 return mPowerSaveWhitelistApps.containsKey(packageName)
1555 || mPowerSaveWhitelistUserApps.containsKey(packageName);
1556 }
1557 }
1558
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001559 public int[] getAppIdWhitelistExceptIdleInternal() {
1560 synchronized (this) {
1561 return mPowerSaveWhitelistExceptIdleAppIdArray;
1562 }
1563 }
1564
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001565 public int[] getAppIdWhitelistInternal() {
1566 synchronized (this) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001567 return mPowerSaveWhitelistAllAppIdArray;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001568 }
1569 }
1570
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001571 public int[] getAppIdUserWhitelistInternal() {
1572 synchronized (this) {
1573 return mPowerSaveWhitelistUserAppIdArray;
1574 }
1575 }
1576
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001577 public int[] getAppIdTempWhitelistInternal() {
1578 synchronized (this) {
1579 return mTempWhitelistAppIdArray;
1580 }
1581 }
1582
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001583 void addPowerSaveTempWhitelistAppChecked(String packageName, long duration,
1584 int userId, String reason) throws RemoteException {
1585 getContext().enforceCallingPermission(
1586 Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
1587 "No permission to change device idle whitelist");
1588 final int callingUid = Binder.getCallingUid();
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001589 userId = ActivityManager.getService().handleIncomingUser(
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001590 Binder.getCallingPid(),
1591 callingUid,
1592 userId,
1593 /*allowAll=*/ false,
1594 /*requireFull=*/ false,
1595 "addPowerSaveTempWhitelistApp", null);
1596 final long token = Binder.clearCallingIdentity();
1597 try {
1598 addPowerSaveTempWhitelistAppInternal(callingUid,
1599 packageName, duration, userId, true, reason);
1600 } finally {
1601 Binder.restoreCallingIdentity(token);
1602 }
1603 }
1604
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001605 /**
1606 * Adds an app to the temporary whitelist and resets the endTime for granting the
1607 * app an exemption to access network and acquire wakelocks.
1608 */
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001609 void addPowerSaveTempWhitelistAppInternal(int callingUid, String packageName,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001610 long duration, int userId, boolean sync, String reason) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001611 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001612 int uid = getContext().getPackageManager().getPackageUidAsUser(packageName, userId);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001613 int appId = UserHandle.getAppId(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001614 addPowerSaveTempWhitelistAppDirectInternal(callingUid, appId, duration, sync, reason);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001615 } catch (NameNotFoundException e) {
1616 }
1617 }
1618
Dianne Hackborna750a632015-06-16 17:18:23 -07001619 /**
1620 * Adds an app to the temporary whitelist and resets the endTime for granting the
1621 * app an exemption to access network and acquire wakelocks.
1622 */
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001623 void addPowerSaveTempWhitelistAppDirectInternal(int callingUid, int appId,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001624 long duration, boolean sync, String reason) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001625 final long timeNow = SystemClock.elapsedRealtime();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001626 Runnable networkPolicyTempWhitelistCallback = null;
Dianne Hackborna750a632015-06-16 17:18:23 -07001627 synchronized (this) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001628 int callingAppId = UserHandle.getAppId(callingUid);
1629 if (callingAppId >= Process.FIRST_APPLICATION_UID) {
1630 if (!mPowerSaveWhitelistSystemAppIds.get(callingAppId)) {
1631 throw new SecurityException("Calling app " + UserHandle.formatUid(callingUid)
1632 + " is not on whitelist");
1633 }
1634 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001635 duration = Math.min(duration, mConstants.MAX_TEMP_APP_WHITELIST_DURATION);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001636 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.get(appId);
1637 final boolean newEntry = entry == null;
Dianne Hackborna750a632015-06-16 17:18:23 -07001638 // Set the new end time
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001639 if (newEntry) {
1640 entry = new Pair<>(new MutableLong(0), reason);
1641 mTempWhitelistAppIdEndTimes.put(appId, entry);
1642 }
1643 entry.first.value = timeNow + duration;
Dianne Hackborna750a632015-06-16 17:18:23 -07001644 if (DEBUG) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001645 Slog.d(TAG, "Adding AppId " + appId + " to temp whitelist. New entry: " + newEntry);
Dianne Hackborna750a632015-06-16 17:18:23 -07001646 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001647 if (newEntry) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001648 // No pending timeout for the app id, post a delayed message
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001649 try {
1650 mBatteryStats.noteEvent(BatteryStats.HistoryItem.EVENT_TEMP_WHITELIST_START,
1651 reason, appId);
1652 } catch (RemoteException e) {
1653 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001654 postTempActiveTimeoutMessage(appId, duration);
1655 updateTempWhitelistAppIdsLocked();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001656 if (mNetworkPolicyTempWhitelistCallback != null) {
1657 if (!sync) {
1658 mHandler.post(mNetworkPolicyTempWhitelistCallback);
1659 } else {
1660 networkPolicyTempWhitelistCallback = mNetworkPolicyTempWhitelistCallback;
1661 }
1662 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001663 reportTempWhitelistChangedLocked();
1664 }
1665 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001666 if (networkPolicyTempWhitelistCallback != null) {
1667 networkPolicyTempWhitelistCallback.run();
1668 }
1669 }
1670
1671 public void setNetworkPolicyTempWhitelistCallbackInternal(Runnable callback) {
1672 synchronized (this) {
1673 mNetworkPolicyTempWhitelistCallback = callback;
1674 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001675 }
1676
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001677 private void postTempActiveTimeoutMessage(int uid, long delay) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001678 if (DEBUG) {
1679 Slog.d(TAG, "postTempActiveTimeoutMessage: uid=" + uid + ", delay=" + delay);
1680 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001681 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_TEMP_APP_WHITELIST_TIMEOUT, uid, 0),
1682 delay);
1683 }
1684
1685 void checkTempAppWhitelistTimeout(int uid) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001686 final long timeNow = SystemClock.elapsedRealtime();
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001687 if (DEBUG) {
1688 Slog.d(TAG, "checkTempAppWhitelistTimeout: uid=" + uid + ", timeNow=" + timeNow);
1689 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001690 synchronized (this) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001691 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.get(uid);
1692 if (entry == null) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001693 // Nothing to do
1694 return;
1695 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001696 if (timeNow >= entry.first.value) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001697 mTempWhitelistAppIdEndTimes.delete(uid);
1698 if (DEBUG) {
1699 Slog.d(TAG, "Removing UID " + uid + " from temp whitelist");
1700 }
1701 updateTempWhitelistAppIdsLocked();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001702 if (mNetworkPolicyTempWhitelistCallback != null) {
1703 mHandler.post(mNetworkPolicyTempWhitelistCallback);
1704 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001705 reportTempWhitelistChangedLocked();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001706 try {
1707 mBatteryStats.noteEvent(BatteryStats.HistoryItem.EVENT_TEMP_WHITELIST_FINISH,
1708 entry.second, uid);
1709 } catch (RemoteException e) {
1710 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001711 } else {
1712 // Need more time
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001713 if (DEBUG) {
1714 Slog.d(TAG, "Time to remove UID " + uid + ": " + entry.first.value);
1715 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001716 postTempActiveTimeoutMessage(uid, entry.first.value - timeNow);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001717 }
1718 }
1719 }
1720
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001721 public void exitIdleInternal(String reason) {
1722 synchronized (this) {
1723 becomeActiveLocked(reason, Binder.getCallingUid());
1724 }
1725 }
1726
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -07001727 void updateConnectivityState(Intent connIntent) {
1728 ConnectivityService cm;
1729 synchronized (this) {
1730 cm = mConnectivityService;
1731 }
1732 if (cm == null) {
1733 return;
1734 }
1735 // Note: can't call out to ConnectivityService with our lock held.
1736 NetworkInfo ni = cm.getActiveNetworkInfo();
1737 synchronized (this) {
Dianne Hackborn88c41352016-04-07 15:18:58 -07001738 boolean conn;
1739 if (ni == null) {
1740 conn = false;
1741 } else {
1742 if (connIntent == null) {
1743 conn = ni.isConnected();
1744 } else {
1745 final int networkType =
1746 connIntent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1747 ConnectivityManager.TYPE_NONE);
1748 if (ni.getType() != networkType) {
1749 return;
1750 }
1751 conn = !connIntent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,
1752 false);
1753 }
1754 }
1755 if (conn != mNetworkConnected) {
1756 mNetworkConnected = conn;
1757 if (conn && mLightState == LIGHT_STATE_WAITING_FOR_NETWORK) {
1758 stepLightIdleStateLocked("network");
1759 }
1760 }
1761 }
1762 }
1763
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001764 void updateDisplayLocked() {
1765 mCurDisplay = mDisplayManager.getDisplay(Display.DEFAULT_DISPLAY);
1766 // We consider any situation where the display is showing something to be it on,
1767 // because if there is anything shown we are going to be updating it at some
1768 // frequency so can't be allowed to go into deep sleeps.
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001769 boolean screenOn = mCurDisplay.getState() == Display.STATE_ON;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001770 if (DEBUG) Slog.d(TAG, "updateDisplayLocked: screenOn=" + screenOn);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001771 if (!screenOn && mScreenOn) {
1772 mScreenOn = false;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001773 if (!mForceIdle) {
1774 becomeInactiveIfAppropriateLocked();
1775 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001776 } else if (screenOn) {
1777 mScreenOn = true;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001778 if (!mForceIdle) {
1779 becomeActiveLocked("screen", Process.myUid());
1780 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001781 }
1782 }
1783
1784 void updateChargingLocked(boolean charging) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001785 if (DEBUG) Slog.i(TAG, "updateChargingLocked: charging=" + charging);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001786 if (!charging && mCharging) {
1787 mCharging = false;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001788 if (!mForceIdle) {
1789 becomeInactiveIfAppropriateLocked();
1790 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001791 } else if (charging) {
1792 mCharging = charging;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001793 if (!mForceIdle) {
1794 becomeActiveLocked("charging", Process.myUid());
1795 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001796 }
1797 }
1798
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001799 void scheduleReportActiveLocked(String activeReason, int activeUid) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001800 Message msg = mHandler.obtainMessage(MSG_REPORT_ACTIVE, activeUid, 0, activeReason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001801 mHandler.sendMessage(msg);
1802 }
1803
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001804 void becomeActiveLocked(String activeReason, int activeUid) {
1805 if (DEBUG) Slog.i(TAG, "becomeActiveLocked, reason = " + activeReason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001806 if (mState != STATE_ACTIVE || mLightState != STATE_ACTIVE) {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001807 EventLogTags.writeDeviceIdle(STATE_ACTIVE, activeReason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001808 EventLogTags.writeDeviceIdleLight(LIGHT_STATE_ACTIVE, activeReason);
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001809 scheduleReportActiveLocked(activeReason, activeUid);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001810 mState = STATE_ACTIVE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001811 mLightState = LIGHT_STATE_ACTIVE;
Adam Lesinski31c05d12015-06-09 17:34:04 -07001812 mInactiveTimeout = mConstants.INACTIVE_TIMEOUT;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001813 mCurIdleBudget = 0;
1814 mMaintenanceStartTime = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001815 resetIdleManagementLocked();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001816 resetLightIdleManagementLocked();
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001817 addEvent(EVENT_NORMAL);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001818 }
1819 }
1820
1821 void becomeInactiveIfAppropriateLocked() {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001822 if (DEBUG) Slog.d(TAG, "becomeInactiveIfAppropriateLocked()");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001823 if ((!mScreenOn && !mCharging) || mForceIdle) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001824 // Screen has turned off; we are now going to become inactive and start
1825 // waiting to see if we will ultimately go idle.
Dianne Hackbornb6843652016-02-22 12:20:13 -08001826 if (mState == STATE_ACTIVE && mDeepEnabled) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001827 mState = STATE_INACTIVE;
1828 if (DEBUG) Slog.d(TAG, "Moved from STATE_ACTIVE to STATE_INACTIVE");
1829 resetIdleManagementLocked();
1830 scheduleAlarmLocked(mInactiveTimeout, false);
1831 EventLogTags.writeDeviceIdle(mState, "no activity");
1832 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001833 if (mLightState == LIGHT_STATE_ACTIVE && mLightEnabled) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001834 mLightState = LIGHT_STATE_INACTIVE;
1835 if (DEBUG) Slog.d(TAG, "Moved from LIGHT_STATE_ACTIVE to LIGHT_STATE_INACTIVE");
1836 resetLightIdleManagementLocked();
Dianne Hackborn953fc942016-03-29 15:36:24 -07001837 scheduleLightAlarmLocked(mConstants.LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001838 EventLogTags.writeDeviceIdleLight(mLightState, "no activity");
1839 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001840 }
1841 }
1842
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001843 void resetIdleManagementLocked() {
1844 mNextIdlePendingDelay = 0;
1845 mNextIdleDelay = 0;
Dianne Hackborn953fc942016-03-29 15:36:24 -07001846 mNextLightIdleDelay = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001847 cancelAlarmLocked();
Kevin Gabayan92f15e62016-04-04 17:52:22 -07001848 cancelSensingTimeoutAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001849 cancelLocatingLocked();
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001850 stopMonitoringMotionLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001851 mAnyMotionDetector.stop();
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001852 }
1853
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001854 void resetLightIdleManagementLocked() {
1855 cancelLightAlarmLocked();
1856 }
1857
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001858 void exitForceIdleLocked() {
1859 if (mForceIdle) {
1860 mForceIdle = false;
1861 if (mScreenOn || mCharging) {
Dianne Hackborn88c41352016-04-07 15:18:58 -07001862 becomeActiveLocked("exit-force", Process.myUid());
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001863 }
1864 }
1865 }
1866
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001867 void stepLightIdleStateLocked(String reason) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001868 if (mLightState == LIGHT_STATE_OVERRIDE) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001869 // If we are already in deep device idle mode, then
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001870 // there is nothing left to do for light mode.
1871 return;
1872 }
1873
1874 if (DEBUG) Slog.d(TAG, "stepLightIdleStateLocked: mLightState=" + mLightState);
1875 EventLogTags.writeDeviceIdleLightStep();
1876
1877 switch (mLightState) {
1878 case LIGHT_STATE_INACTIVE:
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001879 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
Dianne Hackborn953fc942016-03-29 15:36:24 -07001880 // Reset the upcoming idle delays.
1881 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001882 mMaintenanceStartTime = 0;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001883 if (!isOpsInactiveLocked()) {
1884 // We have some active ops going on... give them a chance to finish
1885 // before going in to our first idle.
1886 mLightState = LIGHT_STATE_PRE_IDLE;
1887 EventLogTags.writeDeviceIdleLight(mLightState, reason);
1888 scheduleLightAlarmLocked(mConstants.LIGHT_PRE_IDLE_TIMEOUT);
1889 break;
1890 }
1891 // Nothing active, fall through to immediately idle.
1892 case LIGHT_STATE_PRE_IDLE:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001893 case LIGHT_STATE_IDLE_MAINTENANCE:
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001894 if (mMaintenanceStartTime != 0) {
1895 long duration = SystemClock.elapsedRealtime() - mMaintenanceStartTime;
1896 if (duration < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
1897 // We didn't use up all of our minimum budget; add this to the reserve.
1898 mCurIdleBudget += (mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET-duration);
1899 } else {
1900 // We used more than our minimum budget; this comes out of the reserve.
1901 mCurIdleBudget -= (duration-mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET);
1902 }
1903 }
1904 mMaintenanceStartTime = 0;
Dianne Hackborn953fc942016-03-29 15:36:24 -07001905 scheduleLightAlarmLocked(mNextLightIdleDelay);
1906 mNextLightIdleDelay = Math.min(mConstants.LIGHT_MAX_IDLE_TIMEOUT,
1907 (long)(mNextLightIdleDelay * mConstants.LIGHT_IDLE_FACTOR));
1908 if (mNextLightIdleDelay < mConstants.LIGHT_IDLE_TIMEOUT) {
1909 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
1910 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001911 if (DEBUG) Slog.d(TAG, "Moved to LIGHT_STATE_IDLE.");
1912 mLightState = LIGHT_STATE_IDLE;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001913 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001914 addEvent(EVENT_LIGHT_IDLE);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001915 mGoingIdleWakeLock.acquire();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001916 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON_LIGHT);
1917 break;
1918 case LIGHT_STATE_IDLE:
Dianne Hackborn88c41352016-04-07 15:18:58 -07001919 case LIGHT_STATE_WAITING_FOR_NETWORK:
1920 if (mNetworkConnected || mLightState == LIGHT_STATE_WAITING_FOR_NETWORK) {
1921 // We have been idling long enough, now it is time to do some work.
1922 mActiveIdleOpCount = 1;
1923 mActiveIdleWakeLock.acquire();
1924 mMaintenanceStartTime = SystemClock.elapsedRealtime();
1925 if (mCurIdleBudget < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
1926 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
1927 } else if (mCurIdleBudget > mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET) {
1928 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET;
1929 }
1930 scheduleLightAlarmLocked(mCurIdleBudget);
1931 if (DEBUG) Slog.d(TAG,
1932 "Moved from LIGHT_STATE_IDLE to LIGHT_STATE_IDLE_MAINTENANCE.");
1933 mLightState = LIGHT_STATE_IDLE_MAINTENANCE;
1934 EventLogTags.writeDeviceIdleLight(mLightState, reason);
1935 addEvent(EVENT_LIGHT_MAINTENANCE);
1936 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
1937 } else {
1938 // We'd like to do maintenance, but currently don't have network
1939 // connectivity... let's try to wait until the network comes back.
1940 // We'll only wait for another full idle period, however, and then give up.
1941 scheduleLightAlarmLocked(mNextLightIdleDelay);
1942 if (DEBUG) Slog.d(TAG, "Moved to LIGHT_WAITING_FOR_NETWORK.");
1943 mLightState = LIGHT_STATE_WAITING_FOR_NETWORK;
1944 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001945 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001946 break;
1947 }
1948 }
1949
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001950 void stepIdleStateLocked(String reason) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001951 if (DEBUG) Slog.d(TAG, "stepIdleStateLocked: mState=" + mState);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001952 EventLogTags.writeDeviceIdleStep();
1953
1954 final long now = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07001955 if ((now+mConstants.MIN_TIME_TO_ALARM) > mAlarmManager.getNextWakeFromIdleTime()) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001956 // Whoops, there is an upcoming alarm. We don't actually want to go idle.
1957 if (mState != STATE_ACTIVE) {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001958 becomeActiveLocked("alarm", Process.myUid());
Koji Fukui27b33302015-12-16 19:43:01 +09001959 becomeInactiveIfAppropriateLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001960 }
1961 return;
1962 }
1963
1964 switch (mState) {
1965 case STATE_INACTIVE:
1966 // We have now been inactive long enough, it is time to start looking
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001967 // for motion and sleep some more while doing so.
1968 startMonitoringMotionLocked();
Adam Lesinski31c05d12015-06-09 17:34:04 -07001969 scheduleAlarmLocked(mConstants.IDLE_AFTER_INACTIVE_TIMEOUT, false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001970 // Reset the upcoming idle delays.
Adam Lesinski31c05d12015-06-09 17:34:04 -07001971 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
1972 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001973 mState = STATE_IDLE_PENDING;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001974 if (DEBUG) Slog.d(TAG, "Moved from STATE_INACTIVE to STATE_IDLE_PENDING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001975 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001976 break;
1977 case STATE_IDLE_PENDING:
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001978 mState = STATE_SENSING;
1979 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE_PENDING to STATE_SENSING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001980 EventLogTags.writeDeviceIdle(mState, reason);
Kevin Gabayan92f15e62016-04-04 17:52:22 -07001981 scheduleSensingTimeoutAlarmLocked(mConstants.SENSING_TIMEOUT);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001982 cancelLocatingLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001983 mNotMoving = false;
1984 mLocated = false;
1985 mLastGenericLocation = null;
1986 mLastGpsLocation = null;
Kevin Gabayan92f15e62016-04-04 17:52:22 -07001987 mAnyMotionDetector.checkForAnyMotion();
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001988 break;
1989 case STATE_SENSING:
Kevin Gabayan92f15e62016-04-04 17:52:22 -07001990 cancelSensingTimeoutAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001991 mState = STATE_LOCATING;
1992 if (DEBUG) Slog.d(TAG, "Moved from STATE_SENSING to STATE_LOCATING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001993 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001994 scheduleAlarmLocked(mConstants.LOCATING_TIMEOUT, false);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001995 if (mLocationManager != null
1996 && mLocationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
1997 mLocationManager.requestLocationUpdates(mLocationRequest,
1998 mGenericLocationListener, mHandler.getLooper());
1999 mLocating = true;
2000 } else {
2001 mHasNetworkLocation = false;
2002 }
2003 if (mLocationManager != null
2004 && mLocationManager.getProvider(LocationManager.GPS_PROVIDER) != null) {
2005 mHasGps = true;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002006 mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 5,
2007 mGpsLocationListener, mHandler.getLooper());
Joe LaPenna23d681b2015-08-27 15:12:11 -07002008 mLocating = true;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002009 } else {
Joe LaPenna23d681b2015-08-27 15:12:11 -07002010 mHasGps = false;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002011 }
Joe LaPenna23d681b2015-08-27 15:12:11 -07002012 // If we have a location provider, we're all set, the listeners will move state
2013 // forward.
2014 if (mLocating) {
2015 break;
2016 }
2017
2018 // Otherwise, we have to move from locating into idle maintenance.
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002019 case STATE_LOCATING:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002020 cancelAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002021 cancelLocatingLocked();
2022 mAnyMotionDetector.stop();
Dianne Hackborn953fc942016-03-29 15:36:24 -07002023
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002024 case STATE_IDLE_MAINTENANCE:
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002025 scheduleAlarmLocked(mNextIdleDelay, true);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002026 if (DEBUG) Slog.d(TAG, "Moved to STATE_IDLE. Next alarm in " + mNextIdleDelay +
2027 " ms.");
Adam Lesinski31c05d12015-06-09 17:34:04 -07002028 mNextIdleDelay = (long)(mNextIdleDelay * mConstants.IDLE_FACTOR);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002029 if (DEBUG) Slog.d(TAG, "Setting mNextIdleDelay = " + mNextIdleDelay);
Adam Lesinski31c05d12015-06-09 17:34:04 -07002030 mNextIdleDelay = Math.min(mNextIdleDelay, mConstants.MAX_IDLE_TIMEOUT);
Dianne Hackborn953fc942016-03-29 15:36:24 -07002031 if (mNextIdleDelay < mConstants.IDLE_TIMEOUT) {
2032 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
2033 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002034 mState = STATE_IDLE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002035 if (mLightState != LIGHT_STATE_OVERRIDE) {
2036 mLightState = LIGHT_STATE_OVERRIDE;
2037 cancelLightAlarmLocked();
2038 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002039 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackbornb6843652016-02-22 12:20:13 -08002040 addEvent(EVENT_DEEP_IDLE);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08002041 mGoingIdleWakeLock.acquire();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002042 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON);
2043 break;
2044 case STATE_IDLE:
2045 // We have been idling long enough, now it is time to do some work.
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002046 mActiveIdleOpCount = 1;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002047 mActiveIdleWakeLock.acquire();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002048 scheduleAlarmLocked(mNextIdlePendingDelay, false);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002049 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE to STATE_IDLE_MAINTENANCE. " +
2050 "Next alarm in " + mNextIdlePendingDelay + " ms.");
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002051 mMaintenanceStartTime = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07002052 mNextIdlePendingDelay = Math.min(mConstants.MAX_IDLE_PENDING_TIMEOUT,
2053 (long)(mNextIdlePendingDelay * mConstants.IDLE_PENDING_FACTOR));
Dianne Hackborn953fc942016-03-29 15:36:24 -07002054 if (mNextIdlePendingDelay < mConstants.IDLE_PENDING_TIMEOUT) {
2055 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
2056 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002057 mState = STATE_IDLE_MAINTENANCE;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002058 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackbornb6843652016-02-22 12:20:13 -08002059 addEvent(EVENT_DEEP_MAINTENANCE);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002060 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
2061 break;
2062 }
2063 }
2064
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002065 void incActiveIdleOps() {
2066 synchronized (this) {
2067 mActiveIdleOpCount++;
2068 }
2069 }
2070
2071 void decActiveIdleOps() {
2072 synchronized (this) {
2073 mActiveIdleOpCount--;
2074 if (mActiveIdleOpCount <= 0) {
2075 exitMaintenanceEarlyIfNeededLocked();
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002076 mActiveIdleWakeLock.release();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002077 }
2078 }
2079 }
2080
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002081 void setJobsActive(boolean active) {
2082 synchronized (this) {
2083 mJobsActive = active;
Yao Chenca5edbb2016-01-13 14:44:36 -08002084 reportMaintenanceActivityIfNeededLocked();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002085 if (!active) {
2086 exitMaintenanceEarlyIfNeededLocked();
2087 }
2088 }
2089 }
2090
2091 void setAlarmsActive(boolean active) {
2092 synchronized (this) {
2093 mAlarmsActive = active;
2094 if (!active) {
2095 exitMaintenanceEarlyIfNeededLocked();
2096 }
2097 }
2098 }
2099
Yao Chenca5edbb2016-01-13 14:44:36 -08002100 boolean registerMaintenanceActivityListener(IMaintenanceActivityListener listener) {
2101 synchronized (this) {
2102 mMaintenanceActivityListeners.register(listener);
2103 return mReportedMaintenanceActivity;
2104 }
2105 }
2106
2107 void unregisterMaintenanceActivityListener(IMaintenanceActivityListener listener) {
2108 synchronized (this) {
2109 mMaintenanceActivityListeners.unregister(listener);
2110 }
2111 }
2112
2113 void reportMaintenanceActivityIfNeededLocked() {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07002114 boolean active = mJobsActive;
Yao Chenca5edbb2016-01-13 14:44:36 -08002115 if (active == mReportedMaintenanceActivity) {
2116 return;
2117 }
2118 mReportedMaintenanceActivity = active;
2119 Message msg = mHandler.obtainMessage(MSG_REPORT_MAINTENANCE_ACTIVITY,
2120 mReportedMaintenanceActivity ? 1 : 0, 0);
2121 mHandler.sendMessage(msg);
2122 }
2123
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002124 boolean isOpsInactiveLocked() {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07002125 return mActiveIdleOpCount <= 0 && !mJobsActive && !mAlarmsActive;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002126 }
2127
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002128 void exitMaintenanceEarlyIfNeededLocked() {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002129 if (mState == STATE_IDLE_MAINTENANCE || mLightState == LIGHT_STATE_IDLE_MAINTENANCE
2130 || mLightState == LIGHT_STATE_PRE_IDLE) {
2131 if (isOpsInactiveLocked()) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002132 final long now = SystemClock.elapsedRealtime();
2133 if (DEBUG) {
2134 StringBuilder sb = new StringBuilder();
2135 sb.append("Exit: start=");
2136 TimeUtils.formatDuration(mMaintenanceStartTime, sb);
2137 sb.append(" now=");
2138 TimeUtils.formatDuration(now, sb);
2139 Slog.d(TAG, sb.toString());
2140 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002141 if (mState == STATE_IDLE_MAINTENANCE) {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002142 stepIdleStateLocked("s:early");
2143 } else if (mLightState == LIGHT_STATE_PRE_IDLE) {
2144 stepLightIdleStateLocked("s:predone");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002145 } else {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002146 stepLightIdleStateLocked("s:early");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002147 }
2148 }
2149 }
2150 }
2151
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002152 void motionLocked() {
2153 if (DEBUG) Slog.d(TAG, "motionLocked()");
2154 // The motion sensor will have been disabled at this point
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002155 handleMotionDetectedLocked(mConstants.MOTION_INACTIVE_TIMEOUT, "motion");
2156 }
2157
2158 void handleMotionDetectedLocked(long timeout, String type) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002159 // The device is not yet active, so we want to go back to the pending idle
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002160 // state to wait again for no motion. Note that we only monitor for motion
2161 // after moving out of the inactive state, so no need to worry about that.
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002162 boolean becomeInactive = false;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002163 if (mState != STATE_ACTIVE) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002164 scheduleReportActiveLocked(type, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002165 mState = STATE_ACTIVE;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002166 mInactiveTimeout = timeout;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002167 mCurIdleBudget = 0;
2168 mMaintenanceStartTime = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002169 EventLogTags.writeDeviceIdle(mState, type);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002170 addEvent(EVENT_NORMAL);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002171 becomeInactive = true;
2172 }
2173 if (mLightState == LIGHT_STATE_OVERRIDE) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002174 // We went out of light idle mode because we had started deep idle mode... let's
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002175 // now go back and reset things so we resume light idling if appropriate.
2176 mLightState = STATE_ACTIVE;
2177 EventLogTags.writeDeviceIdleLight(mLightState, type);
2178 becomeInactive = true;
2179 }
2180 if (becomeInactive) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002181 becomeInactiveIfAppropriateLocked();
2182 }
2183 }
2184
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002185 void receivedGenericLocationLocked(Location location) {
2186 if (mState != STATE_LOCATING) {
2187 cancelLocatingLocked();
2188 return;
2189 }
2190 if (DEBUG) Slog.d(TAG, "Generic location: " + location);
2191 mLastGenericLocation = new Location(location);
Joe LaPenna23d681b2015-08-27 15:12:11 -07002192 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY && mHasGps) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002193 return;
2194 }
2195 mLocated = true;
2196 if (mNotMoving) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002197 stepIdleStateLocked("s:location");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002198 }
2199 }
2200
2201 void receivedGpsLocationLocked(Location location) {
2202 if (mState != STATE_LOCATING) {
2203 cancelLocatingLocked();
2204 return;
2205 }
2206 if (DEBUG) Slog.d(TAG, "GPS location: " + location);
2207 mLastGpsLocation = new Location(location);
2208 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY) {
2209 return;
2210 }
2211 mLocated = true;
2212 if (mNotMoving) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002213 stepIdleStateLocked("s:gps");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002214 }
2215 }
2216
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002217 void startMonitoringMotionLocked() {
2218 if (DEBUG) Slog.d(TAG, "startMonitoringMotionLocked()");
2219 if (mMotionSensor != null && !mMotionListener.active) {
2220 mMotionListener.registerLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002221 }
2222 }
2223
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002224 void stopMonitoringMotionLocked() {
2225 if (DEBUG) Slog.d(TAG, "stopMonitoringMotionLocked()");
2226 if (mMotionSensor != null && mMotionListener.active) {
2227 mMotionListener.unregisterLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002228 }
2229 }
2230
2231 void cancelAlarmLocked() {
2232 if (mNextAlarmTime != 0) {
2233 mNextAlarmTime = 0;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002234 mAlarmManager.cancel(mDeepAlarmListener);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002235 }
2236 }
2237
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002238 void cancelLightAlarmLocked() {
2239 if (mNextLightAlarmTime != 0) {
2240 mNextLightAlarmTime = 0;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002241 mAlarmManager.cancel(mLightAlarmListener);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002242 }
2243 }
2244
2245 void cancelLocatingLocked() {
2246 if (mLocating) {
2247 mLocationManager.removeUpdates(mGenericLocationListener);
2248 mLocationManager.removeUpdates(mGpsLocationListener);
2249 mLocating = false;
2250 }
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002251 }
2252
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002253 void cancelSensingTimeoutAlarmLocked() {
2254 if (mNextSensingTimeoutAlarmTime != 0) {
2255 mNextSensingTimeoutAlarmTime = 0;
2256 mAlarmManager.cancel(mSensingTimeoutAlarmListener);
2257 }
2258 }
2259
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002260 void scheduleAlarmLocked(long delay, boolean idleUntil) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002261 if (DEBUG) Slog.d(TAG, "scheduleAlarmLocked(" + delay + ", " + idleUntil + ")");
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002262 if (mMotionSensor == null) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07002263 // If there is no motion sensor on this device, then we won't schedule
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002264 // alarms, because we can't determine if the device is not moving. This effectively
Joe LaPenna23d681b2015-08-27 15:12:11 -07002265 // turns off normal execution of device idling, although it is still possible to
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002266 // manually poke it by pretending like the alarm is going off.
2267 return;
2268 }
2269 mNextAlarmTime = SystemClock.elapsedRealtime() + delay;
2270 if (idleUntil) {
2271 mAlarmManager.setIdleUntil(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002272 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002273 } else {
2274 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002275 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002276 }
2277 }
2278
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002279 void scheduleLightAlarmLocked(long delay) {
2280 if (DEBUG) Slog.d(TAG, "scheduleLightAlarmLocked(" + delay + ")");
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002281 mNextLightAlarmTime = SystemClock.elapsedRealtime() + delay;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002282 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002283 mNextLightAlarmTime, "DeviceIdleController.light", mLightAlarmListener, mHandler);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002284 }
2285
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002286 void scheduleSensingTimeoutAlarmLocked(long delay) {
2287 if (DEBUG) Slog.d(TAG, "scheduleSensingAlarmLocked(" + delay + ")");
2288 mNextSensingTimeoutAlarmTime = SystemClock.elapsedRealtime() + delay;
2289 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, mNextSensingTimeoutAlarmTime,
2290 "DeviceIdleController.sensing", mSensingTimeoutAlarmListener, mHandler);
2291 }
2292
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002293 private static int[] buildAppIdArray(ArrayMap<String, Integer> systemApps,
2294 ArrayMap<String, Integer> userApps, SparseBooleanArray outAppIds) {
2295 outAppIds.clear();
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002296 if (systemApps != null) {
2297 for (int i = 0; i < systemApps.size(); i++) {
2298 outAppIds.put(systemApps.valueAt(i), true);
2299 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002300 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002301 if (userApps != null) {
2302 for (int i = 0; i < userApps.size(); i++) {
2303 outAppIds.put(userApps.valueAt(i), true);
2304 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002305 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002306 int size = outAppIds.size();
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002307 int[] appids = new int[size];
2308 for (int i = 0; i < size; i++) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002309 appids[i] = outAppIds.keyAt(i);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002310 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002311 return appids;
2312 }
2313
2314 private void updateWhitelistAppIdsLocked() {
2315 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(mPowerSaveWhitelistAppsExceptIdle,
2316 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistExceptIdleAppIds);
2317 mPowerSaveWhitelistAllAppIdArray = buildAppIdArray(mPowerSaveWhitelistApps,
2318 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistAllAppIds);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002319 mPowerSaveWhitelistUserAppIdArray = buildAppIdArray(null,
2320 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistUserAppIds);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002321 if (mLocalPowerManager != null) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002322 if (DEBUG) {
2323 Slog.d(TAG, "Setting wakelock whitelist to "
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002324 + Arrays.toString(mPowerSaveWhitelistAllAppIdArray));
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002325 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002326 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002327 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002328 if (mLocalAlarmManager != null) {
2329 if (DEBUG) {
2330 Slog.d(TAG, "Setting alarm whitelist to "
2331 + Arrays.toString(mPowerSaveWhitelistUserAppIdArray));
2332 }
2333 mLocalAlarmManager.setDeviceIdleUserWhitelist(mPowerSaveWhitelistUserAppIdArray);
2334 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002335 }
2336
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002337 private void updateTempWhitelistAppIdsLocked() {
2338 final int size = mTempWhitelistAppIdEndTimes.size();
2339 if (mTempWhitelistAppIdArray.length != size) {
2340 mTempWhitelistAppIdArray = new int[size];
2341 }
2342 for (int i = 0; i < size; i++) {
2343 mTempWhitelistAppIdArray[i] = mTempWhitelistAppIdEndTimes.keyAt(i);
2344 }
2345 if (mLocalPowerManager != null) {
2346 if (DEBUG) {
2347 Slog.d(TAG, "Setting wakelock temp whitelist to "
2348 + Arrays.toString(mTempWhitelistAppIdArray));
2349 }
2350 mLocalPowerManager.setDeviceIdleTempWhitelist(mTempWhitelistAppIdArray);
2351 }
2352 }
2353
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002354 private void reportPowerSaveWhitelistChangedLocked() {
2355 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
2356 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Xiaohui Chene4de5a02015-09-22 15:33:31 -07002357 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002358 }
2359
2360 private void reportTempWhitelistChangedLocked() {
2361 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_TEMP_WHITELIST_CHANGED);
2362 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Xiaohui Chene4de5a02015-09-22 15:33:31 -07002363 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002364 }
2365
2366 void readConfigFileLocked() {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002367 if (DEBUG) Slog.d(TAG, "Reading config from " + mConfigFile.getBaseFile());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002368 mPowerSaveWhitelistUserApps.clear();
2369 FileInputStream stream;
2370 try {
2371 stream = mConfigFile.openRead();
2372 } catch (FileNotFoundException e) {
2373 return;
2374 }
2375 try {
2376 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002377 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002378 readConfigFileLocked(parser);
2379 } catch (XmlPullParserException e) {
2380 } finally {
2381 try {
2382 stream.close();
2383 } catch (IOException e) {
2384 }
2385 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002386 }
2387
2388 private void readConfigFileLocked(XmlPullParser parser) {
2389 final PackageManager pm = getContext().getPackageManager();
2390
2391 try {
2392 int type;
2393 while ((type = parser.next()) != XmlPullParser.START_TAG
2394 && type != XmlPullParser.END_DOCUMENT) {
2395 ;
2396 }
2397
2398 if (type != XmlPullParser.START_TAG) {
2399 throw new IllegalStateException("no start tag found");
2400 }
2401
2402 int outerDepth = parser.getDepth();
2403 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2404 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2405 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2406 continue;
2407 }
2408
2409 String tagName = parser.getName();
2410 if (tagName.equals("wl")) {
2411 String name = parser.getAttributeValue(null, "n");
2412 if (name != null) {
2413 try {
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07002414 ApplicationInfo ai = pm.getApplicationInfo(name,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002415 PackageManager.MATCH_ANY_USER);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002416 mPowerSaveWhitelistUserApps.put(ai.packageName,
2417 UserHandle.getAppId(ai.uid));
2418 } catch (PackageManager.NameNotFoundException e) {
2419 }
2420 }
2421 } else {
2422 Slog.w(TAG, "Unknown element under <config>: "
2423 + parser.getName());
2424 XmlUtils.skipCurrentTag(parser);
2425 }
2426 }
2427
2428 } catch (IllegalStateException e) {
2429 Slog.w(TAG, "Failed parsing config " + e);
2430 } catch (NullPointerException e) {
2431 Slog.w(TAG, "Failed parsing config " + e);
2432 } catch (NumberFormatException e) {
2433 Slog.w(TAG, "Failed parsing config " + e);
2434 } catch (XmlPullParserException e) {
2435 Slog.w(TAG, "Failed parsing config " + e);
2436 } catch (IOException e) {
2437 Slog.w(TAG, "Failed parsing config " + e);
2438 } catch (IndexOutOfBoundsException e) {
2439 Slog.w(TAG, "Failed parsing config " + e);
2440 }
2441 }
2442
2443 void writeConfigFileLocked() {
2444 mHandler.removeMessages(MSG_WRITE_CONFIG);
2445 mHandler.sendEmptyMessageDelayed(MSG_WRITE_CONFIG, 5000);
2446 }
2447
2448 void handleWriteConfigFile() {
2449 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
2450
2451 try {
2452 synchronized (this) {
2453 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002454 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002455 writeConfigFileLocked(out);
2456 }
2457 } catch (IOException e) {
2458 }
2459
2460 synchronized (mConfigFile) {
2461 FileOutputStream stream = null;
2462 try {
2463 stream = mConfigFile.startWrite();
2464 memStream.writeTo(stream);
2465 stream.flush();
2466 FileUtils.sync(stream);
2467 stream.close();
2468 mConfigFile.finishWrite(stream);
2469 } catch (IOException e) {
2470 Slog.w(TAG, "Error writing config file", e);
2471 mConfigFile.failWrite(stream);
2472 }
2473 }
2474 }
2475
2476 void writeConfigFileLocked(XmlSerializer out) throws IOException {
2477 out.startDocument(null, true);
2478 out.startTag(null, "config");
2479 for (int i=0; i<mPowerSaveWhitelistUserApps.size(); i++) {
2480 String name = mPowerSaveWhitelistUserApps.keyAt(i);
2481 out.startTag(null, "wl");
2482 out.attribute(null, "n", name);
2483 out.endTag(null, "wl");
2484 }
2485 out.endTag(null, "config");
2486 out.endDocument();
2487 }
2488
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002489 static void dumpHelp(PrintWriter pw) {
2490 pw.println("Device idle controller (deviceidle) commands:");
2491 pw.println(" help");
2492 pw.println(" Print this help text.");
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002493 pw.println(" step [light|deep]");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002494 pw.println(" Immediately step to next state, without waiting for alarm.");
Dianne Hackborn88c41352016-04-07 15:18:58 -07002495 pw.println(" force-idle [light|deep]");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002496 pw.println(" Force directly into idle mode, regardless of other device state.");
Dianne Hackborn88c41352016-04-07 15:18:58 -07002497 pw.println(" force-inactive");
2498 pw.println(" Force to be inactive, ready to freely step idle states.");
2499 pw.println(" unforce");
2500 pw.println(" Resume normal functioning after force-idle or force-inactive.");
2501 pw.println(" get [light|deep|force|screen|charging|network]");
2502 pw.println(" Retrieve the current given state.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002503 pw.println(" disable [light|deep|all]");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002504 pw.println(" Completely disable device idle mode.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002505 pw.println(" enable [light|deep|all]");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002506 pw.println(" Re-enable device idle mode after it had previously been disabled.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002507 pw.println(" enabled [light|deep|all]");
Dianne Hackborn92617032015-06-19 15:32:19 -07002508 pw.println(" Print 1 if device idle mode is currently enabled, else 0.");
Dianne Hackborn1b139682015-07-06 15:13:37 -07002509 pw.println(" whitelist");
2510 pw.println(" Print currently whitelisted apps.");
Dianne Hackborn92617032015-06-19 15:32:19 -07002511 pw.println(" whitelist [package ...]");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002512 pw.println(" Add (prefix with +) or remove (prefix with -) packages.");
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002513 pw.println(" tempwhitelist");
2514 pw.println(" Print packages that are temporarily whitelisted.");
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002515 pw.println(" tempwhitelist [-u] [package ..]");
Dianne Hackborn92617032015-06-19 15:32:19 -07002516 pw.println(" Temporarily place packages in whitelist for 10 seconds.");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002517 }
2518
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002519 class Shell extends ShellCommand {
2520 int userId = UserHandle.USER_SYSTEM;
2521
2522 @Override
2523 public int onCommand(String cmd) {
2524 return onShellCommand(this, cmd);
2525 }
2526
2527 @Override
2528 public void onHelp() {
2529 PrintWriter pw = getOutPrintWriter();
2530 dumpHelp(pw);
2531 }
2532 }
2533
2534 int onShellCommand(Shell shell, String cmd) {
2535 PrintWriter pw = shell.getOutPrintWriter();
2536 if ("step".equals(cmd)) {
2537 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2538 null);
2539 synchronized (this) {
2540 long token = Binder.clearCallingIdentity();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002541 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002542 try {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002543 if (arg == null || "deep".equals(arg)) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002544 stepIdleStateLocked("s:shell");
2545 pw.print("Stepped to deep: ");
2546 pw.println(stateToString(mState));
2547 } else if ("light".equals(arg)) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002548 stepLightIdleStateLocked("s:shell");
2549 pw.print("Stepped to light: "); pw.println(lightStateToString(mLightState));
2550 } else {
2551 pw.println("Unknown idle mode: " + arg);
2552 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002553 } finally {
2554 Binder.restoreCallingIdentity(token);
2555 }
2556 }
2557 } else if ("force-idle".equals(cmd)) {
2558 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2559 null);
2560 synchronized (this) {
2561 long token = Binder.clearCallingIdentity();
Dianne Hackborn88c41352016-04-07 15:18:58 -07002562 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002563 try {
Dianne Hackborn88c41352016-04-07 15:18:58 -07002564 if (arg == null || "deep".equals(arg)) {
2565 if (!mDeepEnabled) {
2566 pw.println("Unable to go deep idle; not enabled");
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002567 return -1;
2568 }
Dianne Hackborn88c41352016-04-07 15:18:58 -07002569 mForceIdle = true;
2570 becomeInactiveIfAppropriateLocked();
2571 int curState = mState;
2572 while (curState != STATE_IDLE) {
2573 stepIdleStateLocked("s:shell");
2574 if (curState == mState) {
2575 pw.print("Unable to go deep idle; stopped at ");
2576 pw.println(stateToString(mState));
2577 exitForceIdleLocked();
2578 return -1;
2579 }
2580 curState = mState;
2581 }
2582 pw.println("Now forced in to deep idle mode");
2583 } else if ("light".equals(arg)) {
2584 mForceIdle = true;
2585 becomeInactiveIfAppropriateLocked();
2586 int curLightState = mLightState;
2587 while (curLightState != LIGHT_STATE_IDLE) {
2588 stepIdleStateLocked("s:shell");
2589 if (curLightState == mLightState) {
2590 pw.print("Unable to go light idle; stopped at ");
2591 pw.println(lightStateToString(mLightState));
2592 exitForceIdleLocked();
2593 return -1;
2594 }
2595 curLightState = mLightState;
2596 }
2597 pw.println("Now forced in to light idle mode");
2598 } else {
2599 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002600 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002601 } finally {
2602 Binder.restoreCallingIdentity(token);
2603 }
2604 }
Dianne Hackborn88c41352016-04-07 15:18:58 -07002605 } else if ("force-inactive".equals(cmd)) {
2606 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2607 null);
2608 synchronized (this) {
2609 long token = Binder.clearCallingIdentity();
2610 try {
2611 mForceIdle = true;
2612 becomeInactiveIfAppropriateLocked();
2613 pw.print("Light state: ");
2614 pw.print(lightStateToString(mLightState));
2615 pw.print(", deep state: ");
2616 pw.println(stateToString(mState));
2617 } finally {
2618 Binder.restoreCallingIdentity(token);
2619 }
2620 }
2621 } else if ("unforce".equals(cmd)) {
2622 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2623 null);
2624 synchronized (this) {
2625 long token = Binder.clearCallingIdentity();
2626 try {
2627 exitForceIdleLocked();
2628 pw.print("Light state: ");
2629 pw.print(lightStateToString(mLightState));
2630 pw.print(", deep state: ");
2631 pw.println(stateToString(mState));
2632 } finally {
2633 Binder.restoreCallingIdentity(token);
2634 }
2635 }
2636 } else if ("get".equals(cmd)) {
2637 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2638 null);
2639 synchronized (this) {
2640 String arg = shell.getNextArg();
2641 if (arg != null) {
2642 long token = Binder.clearCallingIdentity();
2643 try {
2644 switch (arg) {
2645 case "light": pw.println(lightStateToString(mLightState)); break;
2646 case "deep": pw.println(stateToString(mState)); break;
2647 case "force": pw.println(mForceIdle); break;
2648 case "screen": pw.println(mScreenOn); break;
2649 case "charging": pw.println(mCharging); break;
2650 case "network": pw.println(mNetworkConnected); break;
2651 default: pw.println("Unknown get option: " + arg); break;
2652 }
2653 } finally {
2654 Binder.restoreCallingIdentity(token);
2655 }
2656 } else {
2657 pw.println("Argument required");
2658 }
2659 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002660 } else if ("disable".equals(cmd)) {
2661 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2662 null);
2663 synchronized (this) {
2664 long token = Binder.clearCallingIdentity();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002665 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002666 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002667 boolean becomeActive = false;
2668 boolean valid = false;
2669 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
2670 valid = true;
2671 if (mDeepEnabled) {
2672 mDeepEnabled = false;
2673 becomeActive = true;
2674 pw.println("Deep idle mode disabled");
2675 }
2676 }
2677 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
2678 valid = true;
2679 if (mLightEnabled) {
2680 mLightEnabled = false;
2681 becomeActive = true;
2682 pw.println("Light idle mode disabled");
2683 }
2684 }
2685 if (becomeActive) {
2686 becomeActiveLocked((arg == null ? "all" : arg) + "-disabled",
2687 Process.myUid());
2688 }
2689 if (!valid) {
2690 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002691 }
2692 } finally {
2693 Binder.restoreCallingIdentity(token);
2694 }
2695 }
2696 } else if ("enable".equals(cmd)) {
2697 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2698 null);
2699 synchronized (this) {
2700 long token = Binder.clearCallingIdentity();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002701 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002702 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002703 boolean becomeInactive = false;
2704 boolean valid = false;
2705 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
2706 valid = true;
2707 if (!mDeepEnabled) {
2708 mDeepEnabled = true;
2709 becomeInactive = true;
2710 pw.println("Deep idle mode enabled");
2711 }
2712 }
2713 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
2714 valid = true;
2715 if (!mLightEnabled) {
2716 mLightEnabled = true;
2717 becomeInactive = true;
2718 pw.println("Light idle mode enable");
2719 }
2720 }
2721 if (becomeInactive) {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002722 becomeInactiveIfAppropriateLocked();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002723 }
2724 if (!valid) {
2725 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002726 }
2727 } finally {
2728 Binder.restoreCallingIdentity(token);
2729 }
2730 }
2731 } else if ("enabled".equals(cmd)) {
2732 synchronized (this) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002733 String arg = shell.getNextArg();
2734 if (arg == null || "all".equals(arg)) {
2735 pw.println(mDeepEnabled && mLightEnabled ? "1" : 0);
2736 } else if ("deep".equals(arg)) {
2737 pw.println(mDeepEnabled ? "1" : 0);
2738 } else if ("light".equals(arg)) {
2739 pw.println(mLightEnabled ? "1" : 0);
2740 } else {
2741 pw.println("Unknown idle mode: " + arg);
2742 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002743 }
2744 } else if ("whitelist".equals(cmd)) {
Dianne Hackborneb909e32016-09-29 14:35:15 -07002745 String arg = shell.getNextArg();
2746 if (arg != null) {
2747 getContext().enforceCallingOrSelfPermission(
2748 android.Manifest.permission.DEVICE_POWER, null);
2749 long token = Binder.clearCallingIdentity();
2750 try {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002751 do {
2752 if (arg.length() < 1 || (arg.charAt(0) != '-'
Felipe Lemef8a46232016-02-10 13:51:54 -08002753 && arg.charAt(0) != '+' && arg.charAt(0) != '=')) {
2754 pw.println("Package must be prefixed with +, -, or =: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002755 return -1;
2756 }
2757 char op = arg.charAt(0);
2758 String pkg = arg.substring(1);
2759 if (op == '+') {
2760 if (addPowerSaveWhitelistAppInternal(pkg)) {
2761 pw.println("Added: " + pkg);
2762 } else {
2763 pw.println("Unknown package: " + pkg);
2764 }
Felipe Lemef8a46232016-02-10 13:51:54 -08002765 } else if (op == '-') {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002766 if (removePowerSaveWhitelistAppInternal(pkg)) {
2767 pw.println("Removed: " + pkg);
2768 }
Felipe Lemef8a46232016-02-10 13:51:54 -08002769 } else {
2770 pw.println(getPowerSaveWhitelistAppInternal(pkg));
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002771 }
2772 } while ((arg=shell.getNextArg()) != null);
Dianne Hackborneb909e32016-09-29 14:35:15 -07002773 } finally {
2774 Binder.restoreCallingIdentity(token);
2775 }
2776 } else {
2777 synchronized (this) {
2778 for (int j=0; j<mPowerSaveWhitelistAppsExceptIdle.size(); j++) {
2779 pw.print("system-excidle,");
2780 pw.print(mPowerSaveWhitelistAppsExceptIdle.keyAt(j));
2781 pw.print(",");
2782 pw.println(mPowerSaveWhitelistAppsExceptIdle.valueAt(j));
2783 }
2784 for (int j=0; j<mPowerSaveWhitelistApps.size(); j++) {
2785 pw.print("system,");
2786 pw.print(mPowerSaveWhitelistApps.keyAt(j));
2787 pw.print(",");
2788 pw.println(mPowerSaveWhitelistApps.valueAt(j));
2789 }
2790 for (int j=0; j<mPowerSaveWhitelistUserApps.size(); j++) {
2791 pw.print("user,");
2792 pw.print(mPowerSaveWhitelistUserApps.keyAt(j));
2793 pw.print(",");
2794 pw.println(mPowerSaveWhitelistUserApps.valueAt(j));
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002795 }
2796 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002797 }
2798 } else if ("tempwhitelist".equals(cmd)) {
2799 String opt;
2800 while ((opt=shell.getNextOption()) != null) {
2801 if ("-u".equals(opt)) {
2802 opt = shell.getNextArg();
2803 if (opt == null) {
2804 pw.println("-u requires a user number");
2805 return -1;
2806 }
2807 shell.userId = Integer.parseInt(opt);
2808 }
2809 }
2810 String arg = shell.getNextArg();
2811 if (arg != null) {
2812 try {
2813 addPowerSaveTempWhitelistAppChecked(arg, 10000L, shell.userId, "shell");
2814 } catch (RemoteException re) {
2815 pw.println("Failed: " + re);
2816 }
2817 } else {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002818 dumpTempWhitelistSchedule(pw, false);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002819 }
2820 } else {
2821 return shell.handleDefaultCommands(cmd);
2822 }
2823 return 0;
2824 }
2825
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002826 void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2827 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2828 != PackageManager.PERMISSION_GRANTED) {
2829 pw.println("Permission Denial: can't dump DeviceIdleController from from pid="
2830 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2831 + " without permission " + android.Manifest.permission.DUMP);
2832 return;
2833 }
2834
2835 if (args != null) {
Xiaohui Chen7c696362015-09-16 09:56:14 -07002836 int userId = UserHandle.USER_SYSTEM;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002837 for (int i=0; i<args.length; i++) {
2838 String arg = args[i];
2839 if ("-h".equals(arg)) {
2840 dumpHelp(pw);
2841 return;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002842 } else if ("-u".equals(arg)) {
2843 i++;
2844 if (i < args.length) {
2845 arg = args[i];
2846 userId = Integer.parseInt(arg);
2847 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002848 } else if ("-a".equals(arg)) {
2849 // Ignore, we always dump all.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002850 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
2851 pw.println("Unknown option: " + arg);
2852 return;
2853 } else {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002854 Shell shell = new Shell();
2855 shell.userId = userId;
2856 String[] newArgs = new String[args.length-i];
2857 System.arraycopy(args, i, newArgs, 0, args.length-i);
Dianne Hackborn354736e2016-08-22 17:00:05 -07002858 shell.exec(mBinderService, null, fd, null, newArgs, null,
2859 new ResultReceiver(null));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002860 return;
2861 }
2862 }
2863 }
2864
2865 synchronized (this) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002866 mConstants.dump(pw);
2867
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002868 if (mEventCmds[0] != EVENT_NULL) {
2869 pw.println(" Idling history:");
2870 long now = SystemClock.elapsedRealtime();
2871 for (int i=EVENT_BUFFER_SIZE-1; i>=0; i--) {
2872 int cmd = mEventCmds[i];
2873 if (cmd == EVENT_NULL) {
2874 continue;
2875 }
2876 String label;
2877 switch (mEventCmds[i]) {
2878 case EVENT_NORMAL: label = " normal"; break;
2879 case EVENT_LIGHT_IDLE: label = " light-idle"; break;
2880 case EVENT_LIGHT_MAINTENANCE: label = "light-maint"; break;
Dianne Hackbornb6843652016-02-22 12:20:13 -08002881 case EVENT_DEEP_IDLE: label = " deep-idle"; break;
2882 case EVENT_DEEP_MAINTENANCE: label = " deep-maint"; break;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002883 default: label = " ??"; break;
2884 }
2885 pw.print(" ");
2886 pw.print(label);
2887 pw.print(": ");
2888 TimeUtils.formatDuration(mEventTimes[i], now, pw);;
2889 pw.println();
2890 }
2891 }
2892
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002893 int size = mPowerSaveWhitelistAppsExceptIdle.size();
2894 if (size > 0) {
2895 pw.println(" Whitelist (except idle) system apps:");
2896 for (int i = 0; i < size; i++) {
2897 pw.print(" ");
2898 pw.println(mPowerSaveWhitelistAppsExceptIdle.keyAt(i));
2899 }
2900 }
2901 size = mPowerSaveWhitelistApps.size();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002902 if (size > 0) {
2903 pw.println(" Whitelist system apps:");
2904 for (int i = 0; i < size; i++) {
2905 pw.print(" ");
2906 pw.println(mPowerSaveWhitelistApps.keyAt(i));
2907 }
2908 }
2909 size = mPowerSaveWhitelistUserApps.size();
2910 if (size > 0) {
2911 pw.println(" Whitelist user apps:");
2912 for (int i = 0; i < size; i++) {
2913 pw.print(" ");
2914 pw.println(mPowerSaveWhitelistUserApps.keyAt(i));
2915 }
2916 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002917 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2918 if (size > 0) {
2919 pw.println(" Whitelist (except idle) all app ids:");
2920 for (int i = 0; i < size; i++) {
2921 pw.print(" ");
2922 pw.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2923 pw.println();
2924 }
2925 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002926 size = mPowerSaveWhitelistUserAppIds.size();
2927 if (size > 0) {
2928 pw.println(" Whitelist user app ids:");
2929 for (int i = 0; i < size; i++) {
2930 pw.print(" ");
2931 pw.print(mPowerSaveWhitelistUserAppIds.keyAt(i));
2932 pw.println();
2933 }
2934 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002935 size = mPowerSaveWhitelistAllAppIds.size();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002936 if (size > 0) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002937 pw.println(" Whitelist all app ids:");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002938 for (int i = 0; i < size; i++) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002939 pw.print(" ");
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002940 pw.print(mPowerSaveWhitelistAllAppIds.keyAt(i));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002941 pw.println();
2942 }
2943 }
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002944 dumpTempWhitelistSchedule(pw, true);
2945
Dianne Hackborna750a632015-06-16 17:18:23 -07002946 size = mTempWhitelistAppIdArray != null ? mTempWhitelistAppIdArray.length : 0;
2947 if (size > 0) {
2948 pw.println(" Temp whitelist app ids:");
2949 for (int i = 0; i < size; i++) {
2950 pw.print(" ");
2951 pw.print(mTempWhitelistAppIdArray[i]);
2952 pw.println();
2953 }
2954 }
Adam Lesinski31c05d12015-06-09 17:34:04 -07002955
Dianne Hackbornb6843652016-02-22 12:20:13 -08002956 pw.print(" mLightEnabled="); pw.print(mLightEnabled);
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002957 pw.print(" mDeepEnabled="); pw.println(mDeepEnabled);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002958 pw.print(" mForceIdle="); pw.println(mForceIdle);
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002959 pw.print(" mMotionSensor="); pw.println(mMotionSensor);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002960 pw.print(" mCurDisplay="); pw.println(mCurDisplay);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002961 pw.print(" mScreenOn="); pw.println(mScreenOn);
Dianne Hackborn88c41352016-04-07 15:18:58 -07002962 pw.print(" mNetworkConnected="); pw.println(mNetworkConnected);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002963 pw.print(" mCharging="); pw.println(mCharging);
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002964 pw.print(" mMotionActive="); pw.println(mMotionListener.active);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002965 pw.print(" mNotMoving="); pw.println(mNotMoving);
Joe LaPenna23d681b2015-08-27 15:12:11 -07002966 pw.print(" mLocating="); pw.print(mLocating); pw.print(" mHasGps=");
2967 pw.print(mHasGps); pw.print(" mHasNetwork=");
2968 pw.print(mHasNetworkLocation); pw.print(" mLocated="); pw.println(mLocated);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002969 if (mLastGenericLocation != null) {
2970 pw.print(" mLastGenericLocation="); pw.println(mLastGenericLocation);
2971 }
2972 if (mLastGpsLocation != null) {
2973 pw.print(" mLastGpsLocation="); pw.println(mLastGpsLocation);
2974 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002975 pw.print(" mState="); pw.print(stateToString(mState));
2976 pw.print(" mLightState=");
2977 pw.println(lightStateToString(mLightState));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002978 pw.print(" mInactiveTimeout="); TimeUtils.formatDuration(mInactiveTimeout, pw);
2979 pw.println();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002980 if (mActiveIdleOpCount != 0) {
2981 pw.print(" mActiveIdleOpCount="); pw.println(mActiveIdleOpCount);
2982 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002983 if (mNextAlarmTime != 0) {
2984 pw.print(" mNextAlarmTime=");
2985 TimeUtils.formatDuration(mNextAlarmTime, SystemClock.elapsedRealtime(), pw);
2986 pw.println();
2987 }
2988 if (mNextIdlePendingDelay != 0) {
2989 pw.print(" mNextIdlePendingDelay=");
2990 TimeUtils.formatDuration(mNextIdlePendingDelay, pw);
2991 pw.println();
2992 }
2993 if (mNextIdleDelay != 0) {
2994 pw.print(" mNextIdleDelay=");
2995 TimeUtils.formatDuration(mNextIdleDelay, pw);
2996 pw.println();
2997 }
Dianne Hackborn953fc942016-03-29 15:36:24 -07002998 if (mNextLightIdleDelay != 0) {
2999 pw.print(" mNextIdleDelay=");
3000 TimeUtils.formatDuration(mNextLightIdleDelay, pw);
3001 pw.println();
3002 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003003 if (mNextLightAlarmTime != 0) {
3004 pw.print(" mNextLightAlarmTime=");
3005 TimeUtils.formatDuration(mNextLightAlarmTime, SystemClock.elapsedRealtime(), pw);
3006 pw.println();
3007 }
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08003008 if (mCurIdleBudget != 0) {
3009 pw.print(" mCurIdleBudget=");
3010 TimeUtils.formatDuration(mCurIdleBudget, pw);
3011 pw.println();
3012 }
3013 if (mMaintenanceStartTime != 0) {
3014 pw.print(" mMaintenanceStartTime=");
3015 TimeUtils.formatDuration(mMaintenanceStartTime, SystemClock.elapsedRealtime(), pw);
3016 pw.println();
3017 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003018 if (mJobsActive) {
3019 pw.print(" mJobsActive="); pw.println(mJobsActive);
3020 }
3021 if (mAlarmsActive) {
3022 pw.print(" mAlarmsActive="); pw.println(mAlarmsActive);
3023 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003024 }
3025 }
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003026
3027 void dumpTempWhitelistSchedule(PrintWriter pw, boolean printTitle) {
3028 final int size = mTempWhitelistAppIdEndTimes.size();
3029 if (size > 0) {
3030 String prefix = "";
3031 if (printTitle) {
3032 pw.println(" Temp whitelist schedule:");
3033 prefix = " ";
3034 }
3035 final long timeNow = SystemClock.elapsedRealtime();
3036 for (int i = 0; i < size; i++) {
3037 pw.print(prefix);
3038 pw.print("UID=");
3039 pw.print(mTempWhitelistAppIdEndTimes.keyAt(i));
3040 pw.print(": ");
3041 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.valueAt(i);
3042 TimeUtils.formatDuration(entry.first.value, timeNow, pw);
3043 pw.print(" - ");
3044 pw.println(entry.second);
3045 }
3046 }
3047 }
3048 }