blob: b60f3e2f0bc3fa62f14b11c94764bcdc49b9bc54 [file] [log] [blame]
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Amith Yamasaniaf575b92015-05-29 15:35:26 -070019import android.Manifest;
20import android.app.ActivityManagerNative;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070021import android.app.AlarmManager;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070022import android.content.BroadcastReceiver;
Adam Lesinski31c05d12015-06-09 17:34:04 -070023import android.content.ContentResolver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070024import android.content.Context;
25import android.content.Intent;
26import android.content.IntentFilter;
27import android.content.pm.ApplicationInfo;
28import android.content.pm.PackageManager;
Amith Yamasaniaf575b92015-05-29 15:35:26 -070029import android.content.pm.PackageManager.NameNotFoundException;
Adam Lesinski31c05d12015-06-09 17:34:04 -070030import android.database.ContentObserver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070031import android.hardware.Sensor;
32import android.hardware.SensorManager;
Nick Vaccaro20feaea2015-09-17 17:22:44 -070033import android.hardware.SensorEvent;
34import android.hardware.SensorEventListener;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070035import android.hardware.TriggerEvent;
36import android.hardware.TriggerEventListener;
37import android.hardware.display.DisplayManager;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -070038import android.location.LocationRequest;
39import android.location.Location;
40import android.location.LocationListener;
41import android.location.LocationManager;
Dianne 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;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080052import android.os.IBinder;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070053import android.os.IDeviceIdleController;
Yao Chenca5edbb2016-01-13 14:44:36 -080054import android.os.IMaintenanceActivityListener;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070055import android.os.Looper;
56import android.os.Message;
57import android.os.PowerManager;
58import android.os.PowerManagerInternal;
Dianne Hackbornb6683c42015-06-18 17:40:33 -070059import android.os.Process;
Yao Chenca5edbb2016-01-13 14:44:36 -080060import android.os.RemoteCallbackList;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070061import android.os.RemoteException;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -070062import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070063import android.os.ServiceManager;
Dianne 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;
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700214 private PowerManager.WakeLock mActiveIdleWakeLock;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800215 private IBinder mDownloadServiceActive;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800216 private boolean mJobsActive;
217 private boolean mAlarmsActive;
Yao Chenca5edbb2016-01-13 14:44:36 -0800218 private boolean mReportedMaintenanceActivity;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800219
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700220 public final AtomicFile mConfigFile;
221
Yao Chenca5edbb2016-01-13 14:44:36 -0800222 private final RemoteCallbackList<IMaintenanceActivityListener> mMaintenanceActivityListeners =
223 new RemoteCallbackList<IMaintenanceActivityListener>();
224
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700225 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700226 * Package names the system has white-listed to opt out of power save restrictions,
227 * except for device idle mode.
228 */
229 private final ArrayMap<String, Integer> mPowerSaveWhitelistAppsExceptIdle = new ArrayMap<>();
230
231 /**
232 * Package names the system has white-listed to opt out of power save restrictions for
233 * all modes.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700234 */
235 private final ArrayMap<String, Integer> mPowerSaveWhitelistApps = new ArrayMap<>();
236
237 /**
238 * Package names the user has white-listed to opt out of power save restrictions.
239 */
240 private final ArrayMap<String, Integer> mPowerSaveWhitelistUserApps = new ArrayMap<>();
241
242 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700243 * App IDs of built-in system apps that have been white-listed except for idle modes.
244 */
245 private final SparseBooleanArray mPowerSaveWhitelistSystemAppIdsExceptIdle
246 = new SparseBooleanArray();
247
248 /**
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700249 * App IDs of built-in system apps that have been white-listed.
250 */
251 private final SparseBooleanArray mPowerSaveWhitelistSystemAppIds = new SparseBooleanArray();
252
253 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700254 * App IDs that have been white-listed to opt out of power save restrictions, except
255 * for device idle modes.
256 */
257 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
258
259 /**
260 * Current app IDs that are in the complete power save white list, but shouldn't be
261 * excluded from idle modes. This array can be shared with others because it will not be
262 * modified once set.
263 */
264 private int[] mPowerSaveWhitelistExceptIdleAppIdArray = new int[0];
265
266 /**
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700267 * App IDs that have been white-listed to opt out of power save restrictions.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700268 */
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700269 private final SparseBooleanArray mPowerSaveWhitelistAllAppIds = new SparseBooleanArray();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700270
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700271 /**
272 * Current app IDs that are in the complete power save white list. This array can
273 * be shared with others because it will not be modified once set.
274 */
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700275 private int[] mPowerSaveWhitelistAllAppIdArray = new int[0];
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700276
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700277 /**
Dianne Hackborn262ae5c2016-02-10 16:28:29 -0800278 * App IDs that have been white-listed by the user to opt out of power save restrictions.
279 */
280 private final SparseBooleanArray mPowerSaveWhitelistUserAppIds = new SparseBooleanArray();
281
282 /**
283 * Current app IDs that are in the user power save white list. This array can
284 * be shared with others because it will not be modified once set.
285 */
286 private int[] mPowerSaveWhitelistUserAppIdArray = new int[0];
287
288 /**
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700289 * List of end times for UIDs that are temporarily marked as being allowed to access
290 * the network and acquire wakelocks. Times are in milliseconds.
291 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700292 private final SparseArray<Pair<MutableLong, String>> mTempWhitelistAppIdEndTimes
293 = new SparseArray<>();
294
295 /**
296 * Callback to the NetworkPolicyManagerService to tell it that the temp whitelist has changed.
297 */
298 Runnable mNetworkPolicyTempWhitelistCallback;
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700299
300 /**
301 * Current app IDs of temporarily whitelist apps for high-priority messages.
302 */
303 private int[] mTempWhitelistAppIdArray = new int[0];
304
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800305 private static final int EVENT_NULL = 0;
306 private static final int EVENT_NORMAL = 1;
307 private static final int EVENT_LIGHT_IDLE = 2;
308 private static final int EVENT_LIGHT_MAINTENANCE = 3;
Dianne Hackbornb6843652016-02-22 12:20:13 -0800309 private static final int EVENT_DEEP_IDLE = 4;
310 private static final int EVENT_DEEP_MAINTENANCE = 5;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800311
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -0700312 private final int[] mEventCmds = new int[EVENT_BUFFER_SIZE];
313 private final long[] mEventTimes = new long[EVENT_BUFFER_SIZE];
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800314
315 private void addEvent(int cmd) {
316 if (mEventCmds[0] != cmd) {
317 System.arraycopy(mEventCmds, 0, mEventCmds, 1, EVENT_BUFFER_SIZE - 1);
318 System.arraycopy(mEventTimes, 0, mEventTimes, 1, EVENT_BUFFER_SIZE - 1);
319 mEventCmds[0] = cmd;
320 mEventTimes[0] = SystemClock.elapsedRealtime();
321 }
322 }
323
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700324 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
325 @Override public void onReceive(Context context, Intent intent) {
Dianne Hackborn88c41352016-04-07 15:18:58 -0700326 switch (intent.getAction()) {
327 case ConnectivityManager.CONNECTIVITY_ACTION: {
328 synchronized (DeviceIdleController.this) {
329 updateConnectivityStateLocked(intent);
Dianne Hackborn1b79ad72015-10-12 10:59:47 -0700330 }
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";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700547
548 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700549 * This is the time, after becoming inactive, that we go in to the first
550 * light-weight idle mode.
551 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
552 * @see #KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT
553 */
554 public long LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT;
555
556 /**
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700557 * This is amount of time we will wait from the point where we decide we would
558 * like to go idle until we actually do, while waiting for jobs and other current
559 * activity to finish.
560 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
561 * @see #KEY_LIGHT_PRE_IDLE_TIMEOUT
562 */
563 public long LIGHT_PRE_IDLE_TIMEOUT;
564
565 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700566 * This is the initial time that we will run in idle maintenance mode.
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700567 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
568 * @see #KEY_LIGHT_IDLE_TIMEOUT
569 */
570 public long LIGHT_IDLE_TIMEOUT;
571
572 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700573 * Scaling factor to apply to the light idle mode time each time we complete a cycle.
574 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
575 * @see #KEY_LIGHT_IDLE_FACTOR
576 */
577 public float LIGHT_IDLE_FACTOR;
578
579 /**
580 * This is the maximum time we will run in idle maintenence mode.
581 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
582 * @see #KEY_LIGHT_MAX_IDLE_TIMEOUT
583 */
584 public long LIGHT_MAX_IDLE_TIMEOUT;
585
586 /**
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800587 * This is the minimum amount of time we want to make available for maintenance mode
588 * when lightly idling. That is, we will always have at least this amount of time
589 * available maintenance before timing out and cutting off maintenance mode.
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700590 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800591 * @see #KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700592 */
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800593 public long LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
594
595 /**
596 * This is the maximum amount of time we want to make available for maintenance mode
597 * when lightly idling. That is, if the system isn't using up its minimum maintenance
598 * budget and this time is being added to the budget reserve, this is the maximum
599 * reserve size we will allow to grow and thus the maximum amount of time we will
600 * allow for the maintenance window.
601 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
602 * @see #KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET
603 */
604 public long LIGHT_IDLE_MAINTENANCE_MAX_BUDGET;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700605
606 /**
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700607 * This is the minimum amount of time that we will stay in maintenance mode after
608 * a light doze. We have this minimum to allow various things to respond to switching
609 * in to maintenance mode and scheduling their work -- otherwise we may
610 * see there is nothing to do (no jobs or downloads pending) and go out of maintenance
611 * mode immediately.
612 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
613 * @see #KEY_MIN_LIGHT_MAINTENANCE_TIME
614 */
615 public long MIN_LIGHT_MAINTENANCE_TIME;
616
617 /**
618 * This is the minimum amount of time that we will stay in maintenance mode after
619 * a full doze. We have this minimum to allow various things to respond to switching
620 * in to maintenance mode and scheduling their work -- otherwise we may
621 * see there is nothing to do (no jobs or downloads pending) and go out of maintenance
622 * mode immediately.
623 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
624 * @see #KEY_MIN_DEEP_MAINTENANCE_TIME
625 */
626 public long MIN_DEEP_MAINTENANCE_TIME;
627
628 /**
Adam Lesinski31c05d12015-06-09 17:34:04 -0700629 * This is the time, after becoming inactive, at which we start looking at the
630 * motion sensor to determine if the device is being left alone. We don't do this
631 * immediately after going inactive just because we don't want to be continually running
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700632 * the motion sensor whenever the screen is off.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700633 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
634 * @see #KEY_INACTIVE_TIMEOUT
635 */
636 public long INACTIVE_TIMEOUT;
637
638 /**
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700639 * If we don't receive a callback from AnyMotion in this amount of time +
640 * {@link #LOCATING_TIMEOUT}, we will change from
Adam Lesinski31c05d12015-06-09 17:34:04 -0700641 * STATE_SENSING to STATE_INACTIVE, and any AnyMotion callbacks while not in STATE_SENSING
642 * will be ignored.
643 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
644 * @see #KEY_SENSING_TIMEOUT
645 */
646 public long SENSING_TIMEOUT;
647
648 /**
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700649 * This is how long we will wait to try to get a good location fix before going in to
650 * idle mode.
651 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
652 * @see #KEY_LOCATING_TIMEOUT
653 */
654 public long LOCATING_TIMEOUT;
655
656 /**
657 * The desired maximum accuracy (in meters) we consider the location to be good enough to go
658 * on to idle. We will be trying to get an accuracy fix at least this good or until
659 * {@link #LOCATING_TIMEOUT} expires.
660 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
661 * @see #KEY_LOCATION_ACCURACY
662 */
663 public float LOCATION_ACCURACY;
664
665 /**
Adam Lesinski31c05d12015-06-09 17:34:04 -0700666 * This is the time, after seeing motion, that we wait after becoming inactive from
667 * that until we start looking for motion again.
668 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
669 * @see #KEY_MOTION_INACTIVE_TIMEOUT
670 */
671 public long MOTION_INACTIVE_TIMEOUT;
672
673 /**
674 * This is the time, after the inactive timeout elapses, that we will wait looking
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700675 * for motion until we truly consider the device to be idle.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700676 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
677 * @see #KEY_IDLE_AFTER_INACTIVE_TIMEOUT
678 */
679 public long IDLE_AFTER_INACTIVE_TIMEOUT;
680
681 /**
682 * This is the initial time, after being idle, that we will allow ourself to be back
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700683 * in the IDLE_MAINTENANCE state allowing the system to run normally until we return to
684 * idle.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700685 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
686 * @see #KEY_IDLE_PENDING_TIMEOUT
687 */
688 public long IDLE_PENDING_TIMEOUT;
689
690 /**
691 * Maximum pending idle timeout (time spent running) we will be allowed to use.
692 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
693 * @see #KEY_MAX_IDLE_PENDING_TIMEOUT
694 */
695 public long MAX_IDLE_PENDING_TIMEOUT;
696
697 /**
698 * Scaling factor to apply to current pending idle timeout each time we cycle through
699 * that state.
700 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
701 * @see #KEY_IDLE_PENDING_FACTOR
702 */
703 public float IDLE_PENDING_FACTOR;
704
705 /**
706 * This is the initial time that we want to sit in the idle state before waking up
707 * again to return to pending idle and allowing normal work to run.
708 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
709 * @see #KEY_IDLE_TIMEOUT
710 */
711 public long IDLE_TIMEOUT;
712
713 /**
714 * Maximum idle duration we will be allowed to use.
715 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
716 * @see #KEY_MAX_IDLE_TIMEOUT
717 */
718 public long MAX_IDLE_TIMEOUT;
719
720 /**
721 * Scaling factor to apply to current idle timeout each time we cycle through that state.
722 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
723 * @see #KEY_IDLE_FACTOR
724 */
725 public float IDLE_FACTOR;
726
727 /**
728 * This is the minimum time we will allow until the next upcoming alarm for us to
729 * actually go in to idle mode.
730 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
731 * @see #KEY_MIN_TIME_TO_ALARM
732 */
733 public long MIN_TIME_TO_ALARM;
734
735 /**
736 * Max amount of time to temporarily whitelist an app when it receives a high priority
737 * tickle.
738 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
739 * @see #KEY_MAX_TEMP_APP_WHITELIST_DURATION
740 */
741 public long MAX_TEMP_APP_WHITELIST_DURATION;
742
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700743 /**
744 * Amount of time we would like to whitelist an app that is receiving an MMS.
745 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
746 * @see #KEY_MMS_TEMP_APP_WHITELIST_DURATION
747 */
748 public long MMS_TEMP_APP_WHITELIST_DURATION;
749
Dianne Hackborn451c3462015-07-21 17:39:46 -0700750 /**
751 * Amount of time we would like to whitelist an app that is receiving an SMS.
752 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
753 * @see #KEY_SMS_TEMP_APP_WHITELIST_DURATION
754 */
755 public long SMS_TEMP_APP_WHITELIST_DURATION;
756
Adam Lesinski31c05d12015-06-09 17:34:04 -0700757 private final ContentResolver mResolver;
Joe LaPennaf33b5bf2016-03-23 15:19:47 -0700758 private final boolean mHasWatch;
Adam Lesinski31c05d12015-06-09 17:34:04 -0700759 private final KeyValueListParser mParser = new KeyValueListParser(',');
760
761 public Constants(Handler handler, ContentResolver resolver) {
762 super(handler);
763 mResolver = resolver;
Joe LaPennaf33b5bf2016-03-23 15:19:47 -0700764 mHasWatch = getContext().getPackageManager().hasSystemFeature(
765 PackageManager.FEATURE_WATCH);
766 mResolver.registerContentObserver(Settings.Global.getUriFor(
767 mHasWatch ? Settings.Global.DEVICE_IDLE_CONSTANTS_WATCH
768 : Settings.Global.DEVICE_IDLE_CONSTANTS),
769 false, this);
Adam Lesinski31c05d12015-06-09 17:34:04 -0700770 updateConstants();
771 }
772
773 @Override
774 public void onChange(boolean selfChange, Uri uri) {
775 updateConstants();
776 }
777
778 private void updateConstants() {
779 synchronized (DeviceIdleController.this) {
780 try {
781 mParser.setString(Settings.Global.getString(mResolver,
Joe LaPennaf33b5bf2016-03-23 15:19:47 -0700782 mHasWatch ? Settings.Global.DEVICE_IDLE_CONSTANTS_WATCH
783 : Settings.Global.DEVICE_IDLE_CONSTANTS));
Adam Lesinski31c05d12015-06-09 17:34:04 -0700784 } catch (IllegalArgumentException e) {
785 // Failed to parse the settings string, log this and move on
786 // with defaults.
787 Slog.e(TAG, "Bad device idle settings", e);
788 }
789
Dianne Hackborn953fc942016-03-29 15:36:24 -0700790 LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT = mParser.getLong(
791 KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT,
792 !COMPRESS_TIME ? 5 * 60 * 1000L : 15 * 1000L);
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700793 LIGHT_PRE_IDLE_TIMEOUT = mParser.getLong(KEY_LIGHT_PRE_IDLE_TIMEOUT,
794 !COMPRESS_TIME ? 10 * 60 * 1000L : 30 * 1000L);
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700795 LIGHT_IDLE_TIMEOUT = mParser.getLong(KEY_LIGHT_IDLE_TIMEOUT,
Dianne Hackborn953fc942016-03-29 15:36:24 -0700796 !COMPRESS_TIME ? 5 * 60 * 1000L : 15 * 1000L);
797 LIGHT_IDLE_FACTOR = mParser.getFloat(KEY_LIGHT_IDLE_FACTOR,
798 2f);
799 LIGHT_MAX_IDLE_TIMEOUT = mParser.getLong(KEY_LIGHT_MAX_IDLE_TIMEOUT,
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700800 !COMPRESS_TIME ? 15 * 60 * 1000L : 60 * 1000L);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800801 LIGHT_IDLE_MAINTENANCE_MIN_BUDGET = mParser.getLong(
802 KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET,
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700803 !COMPRESS_TIME ? 1 * 60 * 1000L : 15 * 1000L);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800804 LIGHT_IDLE_MAINTENANCE_MAX_BUDGET = mParser.getLong(
805 KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET,
806 !COMPRESS_TIME ? 5 * 60 * 1000L : 30 * 1000L);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700807 MIN_LIGHT_MAINTENANCE_TIME = mParser.getLong(
808 KEY_MIN_LIGHT_MAINTENANCE_TIME,
809 !COMPRESS_TIME ? 5 * 1000L : 1 * 1000L);
810 MIN_DEEP_MAINTENANCE_TIME = mParser.getLong(
811 KEY_MIN_DEEP_MAINTENANCE_TIME,
812 !COMPRESS_TIME ? 30 * 1000L : 5 * 1000L);
Joe LaPenna0c5d3e92016-03-24 13:29:56 -0700813 long inactiveTimeoutDefault = (mHasWatch ? 15 : 30) * 60 * 1000L;
Adam Lesinski31c05d12015-06-09 17:34:04 -0700814 INACTIVE_TIMEOUT = mParser.getLong(KEY_INACTIVE_TIMEOUT,
Joe LaPenna0c5d3e92016-03-24 13:29:56 -0700815 !COMPRESS_TIME ? inactiveTimeoutDefault : (inactiveTimeoutDefault / 10));
Adam Lesinski31c05d12015-06-09 17:34:04 -0700816 SENSING_TIMEOUT = mParser.getLong(KEY_SENSING_TIMEOUT,
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700817 !DEBUG ? 4 * 60 * 1000L : 60 * 1000L);
818 LOCATING_TIMEOUT = mParser.getLong(KEY_LOCATING_TIMEOUT,
819 !DEBUG ? 30 * 1000L : 15 * 1000L);
820 LOCATION_ACCURACY = mParser.getFloat(KEY_LOCATION_ACCURACY, 20);
Adam Lesinski31c05d12015-06-09 17:34:04 -0700821 MOTION_INACTIVE_TIMEOUT = mParser.getLong(KEY_MOTION_INACTIVE_TIMEOUT,
822 !COMPRESS_TIME ? 10 * 60 * 1000L : 60 * 1000L);
Joe LaPenna0c5d3e92016-03-24 13:29:56 -0700823 long idleAfterInactiveTimeout = (mHasWatch ? 15 : 30) * 60 * 1000L;
Adam Lesinski31c05d12015-06-09 17:34:04 -0700824 IDLE_AFTER_INACTIVE_TIMEOUT = mParser.getLong(KEY_IDLE_AFTER_INACTIVE_TIMEOUT,
Joe LaPenna0c5d3e92016-03-24 13:29:56 -0700825 !COMPRESS_TIME ? idleAfterInactiveTimeout
826 : (idleAfterInactiveTimeout / 10));
Adam Lesinski31c05d12015-06-09 17:34:04 -0700827 IDLE_PENDING_TIMEOUT = mParser.getLong(KEY_IDLE_PENDING_TIMEOUT,
828 !COMPRESS_TIME ? 5 * 60 * 1000L : 30 * 1000L);
829 MAX_IDLE_PENDING_TIMEOUT = mParser.getLong(KEY_MAX_IDLE_PENDING_TIMEOUT,
830 !COMPRESS_TIME ? 10 * 60 * 1000L : 60 * 1000L);
831 IDLE_PENDING_FACTOR = mParser.getFloat(KEY_IDLE_PENDING_FACTOR,
832 2f);
833 IDLE_TIMEOUT = mParser.getLong(KEY_IDLE_TIMEOUT,
834 !COMPRESS_TIME ? 60 * 60 * 1000L : 6 * 60 * 1000L);
835 MAX_IDLE_TIMEOUT = mParser.getLong(KEY_MAX_IDLE_TIMEOUT,
836 !COMPRESS_TIME ? 6 * 60 * 60 * 1000L : 30 * 60 * 1000L);
837 IDLE_FACTOR = mParser.getFloat(KEY_IDLE_FACTOR,
838 2f);
839 MIN_TIME_TO_ALARM = mParser.getLong(KEY_MIN_TIME_TO_ALARM,
840 !COMPRESS_TIME ? 60 * 60 * 1000L : 6 * 60 * 1000L);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700841 MAX_TEMP_APP_WHITELIST_DURATION = mParser.getLong(
842 KEY_MAX_TEMP_APP_WHITELIST_DURATION, 5 * 60 * 1000L);
843 MMS_TEMP_APP_WHITELIST_DURATION = mParser.getLong(
Dianne Hackborn0b6134b2015-07-14 18:48:07 -0700844 KEY_MMS_TEMP_APP_WHITELIST_DURATION, 60 * 1000L);
Dianne Hackborn451c3462015-07-21 17:39:46 -0700845 SMS_TEMP_APP_WHITELIST_DURATION = mParser.getLong(
846 KEY_SMS_TEMP_APP_WHITELIST_DURATION, 20 * 1000L);
Adam Lesinski31c05d12015-06-09 17:34:04 -0700847 }
848 }
849
850 void dump(PrintWriter pw) {
851 pw.println(" Settings:");
852
Dianne Hackborn953fc942016-03-29 15:36:24 -0700853 pw.print(" "); pw.print(KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT); pw.print("=");
854 TimeUtils.formatDuration(LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT, pw);
855 pw.println();
856
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700857 pw.print(" "); pw.print(KEY_LIGHT_PRE_IDLE_TIMEOUT); pw.print("=");
858 TimeUtils.formatDuration(LIGHT_PRE_IDLE_TIMEOUT, pw);
859 pw.println();
860
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700861 pw.print(" "); pw.print(KEY_LIGHT_IDLE_TIMEOUT); pw.print("=");
862 TimeUtils.formatDuration(LIGHT_IDLE_TIMEOUT, pw);
863 pw.println();
864
Dianne Hackborn953fc942016-03-29 15:36:24 -0700865 pw.print(" "); pw.print(KEY_LIGHT_IDLE_FACTOR); pw.print("=");
866 pw.print(LIGHT_IDLE_FACTOR);
867 pw.println();
868
869 pw.print(" "); pw.print(KEY_LIGHT_MAX_IDLE_TIMEOUT); pw.print("=");
870 TimeUtils.formatDuration(LIGHT_MAX_IDLE_TIMEOUT, pw);
871 pw.println();
872
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800873 pw.print(" "); pw.print(KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET); pw.print("=");
874 TimeUtils.formatDuration(LIGHT_IDLE_MAINTENANCE_MIN_BUDGET, pw);
875 pw.println();
876
877 pw.print(" "); pw.print(KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET); pw.print("=");
878 TimeUtils.formatDuration(LIGHT_IDLE_MAINTENANCE_MAX_BUDGET, pw);
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700879 pw.println();
880
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700881 pw.print(" "); pw.print(KEY_MIN_LIGHT_MAINTENANCE_TIME); pw.print("=");
882 TimeUtils.formatDuration(MIN_LIGHT_MAINTENANCE_TIME, pw);
883 pw.println();
884
885 pw.print(" "); pw.print(KEY_MIN_DEEP_MAINTENANCE_TIME); pw.print("=");
886 TimeUtils.formatDuration(MIN_DEEP_MAINTENANCE_TIME, pw);
887 pw.println();
888
Dianne Hackborna750a632015-06-16 17:18:23 -0700889 pw.print(" "); pw.print(KEY_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700890 TimeUtils.formatDuration(INACTIVE_TIMEOUT, pw);
891 pw.println();
892
Dianne Hackborna750a632015-06-16 17:18:23 -0700893 pw.print(" "); pw.print(KEY_SENSING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700894 TimeUtils.formatDuration(SENSING_TIMEOUT, pw);
895 pw.println();
896
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700897 pw.print(" "); pw.print(KEY_LOCATING_TIMEOUT); pw.print("=");
898 TimeUtils.formatDuration(LOCATING_TIMEOUT, pw);
899 pw.println();
900
901 pw.print(" "); pw.print(KEY_LOCATION_ACCURACY); pw.print("=");
902 pw.print(LOCATION_ACCURACY); pw.print("m");
903 pw.println();
904
Dianne Hackborna750a632015-06-16 17:18:23 -0700905 pw.print(" "); pw.print(KEY_MOTION_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700906 TimeUtils.formatDuration(MOTION_INACTIVE_TIMEOUT, pw);
907 pw.println();
908
Dianne Hackborna750a632015-06-16 17:18:23 -0700909 pw.print(" "); pw.print(KEY_IDLE_AFTER_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700910 TimeUtils.formatDuration(IDLE_AFTER_INACTIVE_TIMEOUT, pw);
911 pw.println();
912
Dianne Hackborna750a632015-06-16 17:18:23 -0700913 pw.print(" "); pw.print(KEY_IDLE_PENDING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700914 TimeUtils.formatDuration(IDLE_PENDING_TIMEOUT, pw);
915 pw.println();
916
Dianne Hackborna750a632015-06-16 17:18:23 -0700917 pw.print(" "); pw.print(KEY_MAX_IDLE_PENDING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700918 TimeUtils.formatDuration(MAX_IDLE_PENDING_TIMEOUT, pw);
919 pw.println();
920
Dianne Hackborna750a632015-06-16 17:18:23 -0700921 pw.print(" "); pw.print(KEY_IDLE_PENDING_FACTOR); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700922 pw.println(IDLE_PENDING_FACTOR);
923
Dianne Hackborna750a632015-06-16 17:18:23 -0700924 pw.print(" "); pw.print(KEY_IDLE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700925 TimeUtils.formatDuration(IDLE_TIMEOUT, pw);
926 pw.println();
927
Dianne Hackborna750a632015-06-16 17:18:23 -0700928 pw.print(" "); pw.print(KEY_MAX_IDLE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700929 TimeUtils.formatDuration(MAX_IDLE_TIMEOUT, pw);
930 pw.println();
931
Dianne Hackborna750a632015-06-16 17:18:23 -0700932 pw.print(" "); pw.print(KEY_IDLE_FACTOR); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700933 pw.println(IDLE_FACTOR);
934
Dianne Hackborna750a632015-06-16 17:18:23 -0700935 pw.print(" "); pw.print(KEY_MIN_TIME_TO_ALARM); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700936 TimeUtils.formatDuration(MIN_TIME_TO_ALARM, pw);
937 pw.println();
938
Dianne Hackborna750a632015-06-16 17:18:23 -0700939 pw.print(" "); pw.print(KEY_MAX_TEMP_APP_WHITELIST_DURATION); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700940 TimeUtils.formatDuration(MAX_TEMP_APP_WHITELIST_DURATION, pw);
941 pw.println();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700942
943 pw.print(" "); pw.print(KEY_MMS_TEMP_APP_WHITELIST_DURATION); pw.print("=");
944 TimeUtils.formatDuration(MMS_TEMP_APP_WHITELIST_DURATION, pw);
945 pw.println();
Dianne Hackborn451c3462015-07-21 17:39:46 -0700946
947 pw.print(" "); pw.print(KEY_SMS_TEMP_APP_WHITELIST_DURATION); pw.print("=");
948 TimeUtils.formatDuration(SMS_TEMP_APP_WHITELIST_DURATION, pw);
949 pw.println();
Adam Lesinski31c05d12015-06-09 17:34:04 -0700950 }
951 }
952
953 private Constants mConstants;
954
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700955 @Override
956 public void onAnyMotionResult(int result) {
957 if (DEBUG) Slog.d(TAG, "onAnyMotionResult(" + result + ")");
Kevin Gabayan92f15e62016-04-04 17:52:22 -0700958 if (result != AnyMotionDetector.RESULT_UNKNOWN) {
959 synchronized (this) {
960 cancelSensingTimeoutAlarmLocked();
961 }
962 }
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700963 if (result == AnyMotionDetector.RESULT_MOVED) {
964 if (DEBUG) Slog.d(TAG, "RESULT_MOVED received.");
965 synchronized (this) {
966 handleMotionDetectedLocked(mConstants.INACTIVE_TIMEOUT, "sense_motion");
967 }
968 } else if (result == AnyMotionDetector.RESULT_STATIONARY) {
969 if (DEBUG) Slog.d(TAG, "RESULT_STATIONARY received.");
970 if (mState == STATE_SENSING) {
971 // If we are currently sensing, it is time to move to locating.
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700972 synchronized (this) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700973 mNotMoving = true;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800974 stepIdleStateLocked("s:stationary");
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700975 }
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700976 } else if (mState == STATE_LOCATING) {
977 // If we are currently locating, note that we are not moving and step
978 // if we have located the position.
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700979 synchronized (this) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700980 mNotMoving = true;
981 if (mLocated) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800982 stepIdleStateLocked("s:stationary");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700983 }
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700984 }
985 }
986 }
987 }
988
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700989 static final int MSG_WRITE_CONFIG = 1;
990 static final int MSG_REPORT_IDLE_ON = 2;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700991 static final int MSG_REPORT_IDLE_ON_LIGHT = 3;
992 static final int MSG_REPORT_IDLE_OFF = 4;
993 static final int MSG_REPORT_ACTIVE = 5;
994 static final int MSG_TEMP_APP_WHITELIST_TIMEOUT = 6;
Yao Chenca5edbb2016-01-13 14:44:36 -0800995 static final int MSG_REPORT_MAINTENANCE_ACTIVITY = 7;
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700996 static final int MSG_FINISH_IDLE_OP = 8;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700997
998 final class MyHandler extends Handler {
999 MyHandler(Looper looper) {
1000 super(looper);
1001 }
1002
1003 @Override public void handleMessage(Message msg) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001004 if (DEBUG) Slog.d(TAG, "handleMessage(" + msg.what + ")");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001005 switch (msg.what) {
1006 case MSG_WRITE_CONFIG: {
1007 handleWriteConfigFile();
1008 } break;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001009 case MSG_REPORT_IDLE_ON:
1010 case MSG_REPORT_IDLE_ON_LIGHT: {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001011 EventLogTags.writeDeviceIdleOnStart();
Dianne Hackbornb6843652016-02-22 12:20:13 -08001012 final boolean deepChanged;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001013 final boolean lightChanged;
1014 if (msg.what == MSG_REPORT_IDLE_ON) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001015 deepChanged = mLocalPowerManager.setDeviceIdleMode(true);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001016 lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
1017 } else {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001018 deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001019 lightChanged = mLocalPowerManager.setLightDeviceIdleMode(true);
1020 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001021 try {
1022 mNetworkPolicyManager.setDeviceIdleMode(true);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001023 mBatteryStats.noteDeviceIdleMode(msg.what == MSG_REPORT_IDLE_ON
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07001024 ? BatteryStats.DEVICE_IDLE_MODE_DEEP
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001025 : BatteryStats.DEVICE_IDLE_MODE_LIGHT, null, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001026 } catch (RemoteException e) {
1027 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001028 if (deepChanged) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001029 getContext().sendBroadcastAsUser(mIdleIntent, UserHandle.ALL);
1030 }
1031 if (lightChanged) {
1032 getContext().sendBroadcastAsUser(mLightIdleIntent, UserHandle.ALL);
1033 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001034 EventLogTags.writeDeviceIdleOnComplete();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001035 } break;
1036 case MSG_REPORT_IDLE_OFF: {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001037 EventLogTags.writeDeviceIdleOffStart("unknown");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001038 final boolean deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001039 final boolean lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001040 try {
1041 mNetworkPolicyManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001042 mBatteryStats.noteDeviceIdleMode(BatteryStats.DEVICE_IDLE_MODE_OFF,
1043 null, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001044 } catch (RemoteException e) {
1045 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001046 if (deepChanged) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001047 incActiveIdleOps();
1048 getContext().sendOrderedBroadcastAsUser(mIdleIntent, UserHandle.ALL,
1049 null, mIdleStartedDoneReceiver, null, 0, null, null);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001050 }
1051 if (lightChanged) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001052 incActiveIdleOps();
1053 getContext().sendOrderedBroadcastAsUser(mLightIdleIntent, UserHandle.ALL,
1054 null, mIdleStartedDoneReceiver, null, 0, null, null);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001055 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001056 // Always start with one active op for the message being sent here.
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001057 // Now we are done!
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001058 decActiveIdleOps();
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001059 EventLogTags.writeDeviceIdleOffComplete();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001060 } break;
1061 case MSG_REPORT_ACTIVE: {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001062 String activeReason = (String)msg.obj;
1063 int activeUid = msg.arg1;
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001064 EventLogTags.writeDeviceIdleOffStart(
1065 activeReason != null ? activeReason : "unknown");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001066 final boolean deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001067 final boolean lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001068 try {
1069 mNetworkPolicyManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001070 mBatteryStats.noteDeviceIdleMode(BatteryStats.DEVICE_IDLE_MODE_OFF,
1071 activeReason, activeUid);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001072 } catch (RemoteException e) {
1073 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001074 if (deepChanged) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001075 getContext().sendBroadcastAsUser(mIdleIntent, UserHandle.ALL);
1076 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001077 if (lightChanged) {
1078 getContext().sendBroadcastAsUser(mLightIdleIntent, UserHandle.ALL);
1079 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001080 EventLogTags.writeDeviceIdleOffComplete();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001081 } break;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001082 case MSG_TEMP_APP_WHITELIST_TIMEOUT: {
1083 int uid = msg.arg1;
1084 checkTempAppWhitelistTimeout(uid);
1085 } break;
Yao Chenca5edbb2016-01-13 14:44:36 -08001086 case MSG_REPORT_MAINTENANCE_ACTIVITY: {
1087 boolean active = (msg.arg1 == 1);
1088 final int size = mMaintenanceActivityListeners.beginBroadcast();
1089 try {
1090 for (int i = 0; i < size; i++) {
1091 try {
1092 mMaintenanceActivityListeners.getBroadcastItem(i)
1093 .onMaintenanceActivityChanged(active);
1094 } catch (RemoteException ignored) {
1095 }
1096 }
1097 } finally {
1098 mMaintenanceActivityListeners.finishBroadcast();
1099 }
1100 } break;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001101 case MSG_FINISH_IDLE_OP: {
1102 decActiveIdleOps();
1103 } break;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001104 }
1105 }
1106 }
1107
1108 final MyHandler mHandler;
1109
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001110 BinderService mBinderService;
1111
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001112 private final class BinderService extends IDeviceIdleController.Stub {
1113 @Override public void addPowerSaveWhitelistApp(String name) {
1114 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1115 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001116 long ident = Binder.clearCallingIdentity();
1117 try {
1118 addPowerSaveWhitelistAppInternal(name);
1119 } finally {
1120 Binder.restoreCallingIdentity(ident);
1121 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001122 }
1123
1124 @Override public void removePowerSaveWhitelistApp(String name) {
1125 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1126 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001127 long ident = Binder.clearCallingIdentity();
1128 try {
1129 removePowerSaveWhitelistAppInternal(name);
1130 } finally {
1131 Binder.restoreCallingIdentity(ident);
1132 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001133 }
1134
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001135 @Override public String[] getSystemPowerWhitelistExceptIdle() {
1136 return getSystemPowerWhitelistExceptIdleInternal();
1137 }
1138
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001139 @Override public String[] getSystemPowerWhitelist() {
1140 return getSystemPowerWhitelistInternal();
1141 }
1142
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001143 @Override public String[] getUserPowerWhitelist() {
1144 return getUserPowerWhitelistInternal();
1145 }
1146
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001147 @Override public String[] getFullPowerWhitelistExceptIdle() {
1148 return getFullPowerWhitelistExceptIdleInternal();
1149 }
1150
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001151 @Override public String[] getFullPowerWhitelist() {
1152 return getFullPowerWhitelistInternal();
1153 }
1154
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001155 @Override public int[] getAppIdWhitelistExceptIdle() {
1156 return getAppIdWhitelistExceptIdleInternal();
1157 }
1158
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001159 @Override public int[] getAppIdWhitelist() {
1160 return getAppIdWhitelistInternal();
1161 }
1162
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001163 @Override public int[] getAppIdUserWhitelist() {
1164 return getAppIdUserWhitelistInternal();
1165 }
1166
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001167 @Override public int[] getAppIdTempWhitelist() {
1168 return getAppIdTempWhitelistInternal();
1169 }
1170
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001171 @Override public boolean isPowerSaveWhitelistExceptIdleApp(String name) {
1172 return isPowerSaveWhitelistExceptIdleAppInternal(name);
1173 }
1174
Amith Yamasani06bf8242015-05-08 16:36:21 -07001175 @Override public boolean isPowerSaveWhitelistApp(String name) {
1176 return isPowerSaveWhitelistAppInternal(name);
1177 }
1178
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001179 @Override public void addPowerSaveTempWhitelistApp(String packageName, long duration,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001180 int userId, String reason) throws RemoteException {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001181 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001182 }
1183
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001184 @Override public long addPowerSaveTempWhitelistAppForMms(String packageName,
1185 int userId, String reason) throws RemoteException {
1186 long duration = mConstants.MMS_TEMP_APP_WHITELIST_DURATION;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001187 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001188 return duration;
1189 }
1190
Dianne Hackborn451c3462015-07-21 17:39:46 -07001191 @Override public long addPowerSaveTempWhitelistAppForSms(String packageName,
1192 int userId, String reason) throws RemoteException {
1193 long duration = mConstants.SMS_TEMP_APP_WHITELIST_DURATION;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001194 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Dianne Hackborn451c3462015-07-21 17:39:46 -07001195 return duration;
1196 }
1197
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001198 @Override public void exitIdle(String reason) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001199 getContext().enforceCallingOrSelfPermission(Manifest.permission.DEVICE_POWER,
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001200 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001201 long ident = Binder.clearCallingIdentity();
1202 try {
1203 exitIdleInternal(reason);
1204 } finally {
1205 Binder.restoreCallingIdentity(ident);
1206 }
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001207 }
1208
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001209 @Override public void downloadServiceActive(IBinder token) {
1210 getContext().enforceCallingOrSelfPermission(
1211 "android.permission.SEND_DOWNLOAD_COMPLETED_INTENTS", null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001212 long ident = Binder.clearCallingIdentity();
1213 try {
1214 DeviceIdleController.this.downloadServiceActive(token);
1215 } finally {
1216 Binder.restoreCallingIdentity(ident);
1217 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001218 }
1219
1220 @Override public void downloadServiceInactive() {
1221 getContext().enforceCallingOrSelfPermission(
1222 "android.permission.SEND_DOWNLOAD_COMPLETED_INTENTS", null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001223 long ident = Binder.clearCallingIdentity();
1224 try {
1225 DeviceIdleController.this.downloadServiceInactive();
1226 } finally {
1227 Binder.restoreCallingIdentity(ident);
1228 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001229 }
1230
Yao Chenca5edbb2016-01-13 14:44:36 -08001231 @Override public boolean registerMaintenanceActivityListener(
1232 IMaintenanceActivityListener listener) {
1233 return DeviceIdleController.this.registerMaintenanceActivityListener(listener);
1234 }
1235
1236 @Override public void unregisterMaintenanceActivityListener(
1237 IMaintenanceActivityListener listener) {
1238 DeviceIdleController.this.unregisterMaintenanceActivityListener(listener);
1239 }
1240
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001241 @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1242 DeviceIdleController.this.dump(fd, pw, args);
1243 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001244
1245 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
1246 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
1247 (new Shell()).exec(this, in, out, err, args, resultReceiver);
1248 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001249 }
1250
Dianne Hackborna750a632015-06-16 17:18:23 -07001251 public final class LocalService {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001252 public void addPowerSaveTempWhitelistAppDirect(int appId, long duration, boolean sync,
1253 String reason) {
1254 addPowerSaveTempWhitelistAppDirectInternal(0, appId, duration, sync, reason);
1255 }
1256
1257 public void setNetworkPolicyTempWhitelistCallback(Runnable callback) {
1258 setNetworkPolicyTempWhitelistCallbackInternal(callback);
Dianne Hackborna750a632015-06-16 17:18:23 -07001259 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001260
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001261 public void setJobsActive(boolean active) {
1262 DeviceIdleController.this.setJobsActive(active);
1263 }
1264
1265 // Up-call from alarm manager.
1266 public void setAlarmsActive(boolean active) {
1267 DeviceIdleController.this.setAlarmsActive(active);
1268 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001269
1270 /**
1271 * Returns the array of app ids whitelisted by user. Take care not to
1272 * modify this, as it is a reference to the original copy. But the reference
1273 * can change when the list changes, so it needs to be re-acquired when
1274 * {@link PowerManager#ACTION_POWER_SAVE_WHITELIST_CHANGED} is sent.
1275 */
1276 public int[] getPowerSaveWhitelistUserAppIds() {
1277 return DeviceIdleController.this.getPowerSaveWhitelistUserAppIds();
1278 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001279 }
1280
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001281 public DeviceIdleController(Context context) {
1282 super(context);
1283 mConfigFile = new AtomicFile(new File(getSystemDir(), "deviceidle.xml"));
1284 mHandler = new MyHandler(BackgroundThread.getHandler().getLooper());
1285 }
1286
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001287 int[] getPowerSaveWhitelistUserAppIds() {
1288 synchronized (this) {
1289 return mPowerSaveWhitelistUserAppIdArray;
1290 }
1291 }
1292
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001293 private static File getSystemDir() {
1294 return new File(Environment.getDataDirectory(), "system");
1295 }
1296
1297 @Override
1298 public void onStart() {
1299 final PackageManager pm = getContext().getPackageManager();
1300
1301 synchronized (this) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001302 mLightEnabled = mDeepEnabled = getContext().getResources().getBoolean(
Dianne Hackborn92617032015-06-19 15:32:19 -07001303 com.android.internal.R.bool.config_enableAutoPowerModes);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001304 SystemConfig sysConfig = SystemConfig.getInstance();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001305 ArraySet<String> allowPowerExceptIdle = sysConfig.getAllowInPowerSaveExceptIdle();
1306 for (int i=0; i<allowPowerExceptIdle.size(); i++) {
1307 String pkg = allowPowerExceptIdle.valueAt(i);
1308 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001309 ApplicationInfo ai = pm.getApplicationInfo(pkg,
1310 PackageManager.MATCH_SYSTEM_ONLY);
1311 int appid = UserHandle.getAppId(ai.uid);
1312 mPowerSaveWhitelistAppsExceptIdle.put(ai.packageName, appid);
1313 mPowerSaveWhitelistSystemAppIdsExceptIdle.put(appid, true);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001314 } catch (PackageManager.NameNotFoundException e) {
1315 }
1316 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001317 ArraySet<String> allowPower = sysConfig.getAllowInPowerSave();
1318 for (int i=0; i<allowPower.size(); i++) {
1319 String pkg = allowPower.valueAt(i);
1320 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001321 ApplicationInfo ai = pm.getApplicationInfo(pkg,
1322 PackageManager.MATCH_SYSTEM_ONLY);
1323 int appid = UserHandle.getAppId(ai.uid);
1324 // These apps are on both the whitelist-except-idle as well
1325 // as the full whitelist, so they apply in all cases.
1326 mPowerSaveWhitelistAppsExceptIdle.put(ai.packageName, appid);
1327 mPowerSaveWhitelistSystemAppIdsExceptIdle.put(appid, true);
1328 mPowerSaveWhitelistApps.put(ai.packageName, appid);
1329 mPowerSaveWhitelistSystemAppIds.put(appid, true);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001330 } catch (PackageManager.NameNotFoundException e) {
1331 }
1332 }
1333
Adam Lesinski31c05d12015-06-09 17:34:04 -07001334 mConstants = new Constants(mHandler, getContext().getContentResolver());
1335
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001336 readConfigFileLocked();
1337 updateWhitelistAppIdsLocked();
1338
Dianne Hackborn88c41352016-04-07 15:18:58 -07001339 mNetworkConnected = true;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001340 mScreenOn = true;
1341 // Start out assuming we are charging. If we aren't, we will at least get
1342 // a battery update the next time the level drops.
1343 mCharging = true;
1344 mState = STATE_ACTIVE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001345 mLightState = LIGHT_STATE_ACTIVE;
Adam Lesinski31c05d12015-06-09 17:34:04 -07001346 mInactiveTimeout = mConstants.INACTIVE_TIMEOUT;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001347 }
1348
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001349 mBinderService = new BinderService();
1350 publishBinderService(Context.DEVICE_IDLE_CONTROLLER, mBinderService);
Dianne Hackborna750a632015-06-16 17:18:23 -07001351 publishLocalService(LocalService.class, new LocalService());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001352 }
1353
1354 @Override
1355 public void onBootPhase(int phase) {
1356 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1357 synchronized (this) {
1358 mAlarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
1359 mBatteryStats = BatteryStatsService.getService();
1360 mLocalPowerManager = getLocalService(PowerManagerInternal.class);
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001361 mPowerManager = getContext().getSystemService(PowerManager.class);
1362 mActiveIdleWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
1363 "deviceidle_maint");
1364 mActiveIdleWakeLock.setReferenceCounted(false);
Dianne Hackborn88c41352016-04-07 15:18:58 -07001365 mConnectivityService = (ConnectivityService)ServiceManager.getService(
1366 Context.CONNECTIVITY_SERVICE);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001367 mLocalAlarmManager = getLocalService(AlarmManagerService.LocalService.class);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001368 mNetworkPolicyManager = INetworkPolicyManager.Stub.asInterface(
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001369 ServiceManager.getService(Context.NETWORK_POLICY_SERVICE));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001370 mDisplayManager = (DisplayManager) getContext().getSystemService(
1371 Context.DISPLAY_SERVICE);
1372 mSensorManager = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001373 int sigMotionSensorId = getContext().getResources().getInteger(
1374 com.android.internal.R.integer.config_autoPowerModeAnyMotionSensor);
1375 if (sigMotionSensorId > 0) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001376 mMotionSensor = mSensorManager.getDefaultSensor(sigMotionSensorId, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001377 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001378 if (mMotionSensor == null && getContext().getResources().getBoolean(
Joe LaPenna23d681b2015-08-27 15:12:11 -07001379 com.android.internal.R.bool.config_autoPowerModePreferWristTilt)) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001380 mMotionSensor = mSensorManager.getDefaultSensor(
1381 Sensor.TYPE_WRIST_TILT_GESTURE, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001382 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001383 if (mMotionSensor == null) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07001384 // As a last ditch, fall back to SMD.
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001385 mMotionSensor = mSensorManager.getDefaultSensor(
1386 Sensor.TYPE_SIGNIFICANT_MOTION, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001387 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001388
Joe LaPenna23d681b2015-08-27 15:12:11 -07001389 if (getContext().getResources().getBoolean(
1390 com.android.internal.R.bool.config_autoPowerModePrefetchLocation)) {
1391 mLocationManager = (LocationManager) getContext().getSystemService(
1392 Context.LOCATION_SERVICE);
1393 mLocationRequest = new LocationRequest()
1394 .setQuality(LocationRequest.ACCURACY_FINE)
1395 .setInterval(0)
1396 .setFastestInterval(0)
1397 .setNumUpdates(1);
1398 }
1399
1400 float angleThreshold = getContext().getResources().getInteger(
1401 com.android.internal.R.integer.config_autoPowerModeThresholdAngle) / 100f;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001402 mAnyMotionDetector = new AnyMotionDetector(
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001403 (PowerManager) getContext().getSystemService(Context.POWER_SERVICE),
Joe LaPenna23d681b2015-08-27 15:12:11 -07001404 mHandler, mSensorManager, this, angleThreshold);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001405
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001406 mIdleIntent = new Intent(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001407 mIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1408 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001409 mLightIdleIntent = new Intent(PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED);
1410 mLightIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1411 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001412
1413 IntentFilter filter = new IntentFilter();
1414 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001415 getContext().registerReceiver(mReceiver, filter);
Amith Yamasaniac59f75e2016-05-05 12:38:17 -07001416
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001417 filter = new IntentFilter();
1418 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1419 filter.addDataScheme("package");
Amith Yamasaniac59f75e2016-05-05 12:38:17 -07001420 getContext().registerReceiver(mReceiver, filter);
1421
Dianne Hackborn88c41352016-04-07 15:18:58 -07001422 filter = new IntentFilter();
1423 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001424 getContext().registerReceiver(mReceiver, filter);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001425
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001426 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001427 mLocalAlarmManager.setDeviceIdleUserWhitelist(mPowerSaveWhitelistUserAppIdArray);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001428 mDisplayManager.registerDisplayListener(mDisplayListener, null);
Dianne Hackborn88c41352016-04-07 15:18:58 -07001429 updateConnectivityStateLocked(null);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001430 updateDisplayLocked();
1431 }
1432 }
1433 }
1434
1435 public boolean addPowerSaveWhitelistAppInternal(String name) {
1436 synchronized (this) {
1437 try {
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001438 ApplicationInfo ai = getContext().getPackageManager().getApplicationInfo(name,
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001439 PackageManager.MATCH_UNINSTALLED_PACKAGES);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001440 if (mPowerSaveWhitelistUserApps.put(name, UserHandle.getAppId(ai.uid)) == null) {
1441 reportPowerSaveWhitelistChangedLocked();
1442 updateWhitelistAppIdsLocked();
1443 writeConfigFileLocked();
1444 }
1445 return true;
1446 } catch (PackageManager.NameNotFoundException e) {
1447 return false;
1448 }
1449 }
1450 }
1451
1452 public boolean removePowerSaveWhitelistAppInternal(String name) {
1453 synchronized (this) {
1454 if (mPowerSaveWhitelistUserApps.remove(name) != null) {
1455 reportPowerSaveWhitelistChangedLocked();
1456 updateWhitelistAppIdsLocked();
1457 writeConfigFileLocked();
1458 return true;
1459 }
1460 }
1461 return false;
1462 }
1463
Felipe Lemef8a46232016-02-10 13:51:54 -08001464 public boolean getPowerSaveWhitelistAppInternal(String name) {
1465 synchronized (this) {
1466 return mPowerSaveWhitelistUserApps.containsKey(name);
1467 }
1468 }
1469
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001470 public String[] getSystemPowerWhitelistExceptIdleInternal() {
1471 synchronized (this) {
1472 int size = mPowerSaveWhitelistAppsExceptIdle.size();
1473 String[] apps = new String[size];
1474 for (int i = 0; i < size; i++) {
1475 apps[i] = mPowerSaveWhitelistAppsExceptIdle.keyAt(i);
1476 }
1477 return apps;
1478 }
1479 }
1480
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001481 public String[] getSystemPowerWhitelistInternal() {
1482 synchronized (this) {
1483 int size = mPowerSaveWhitelistApps.size();
1484 String[] apps = new String[size];
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001485 for (int i = 0; i < size; i++) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001486 apps[i] = mPowerSaveWhitelistApps.keyAt(i);
1487 }
1488 return apps;
1489 }
1490 }
1491
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001492 public String[] getUserPowerWhitelistInternal() {
1493 synchronized (this) {
1494 int size = mPowerSaveWhitelistUserApps.size();
1495 String[] apps = new String[size];
1496 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1497 apps[i] = mPowerSaveWhitelistUserApps.keyAt(i);
1498 }
1499 return apps;
1500 }
1501 }
1502
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001503 public String[] getFullPowerWhitelistExceptIdleInternal() {
1504 synchronized (this) {
1505 int size = mPowerSaveWhitelistAppsExceptIdle.size() + mPowerSaveWhitelistUserApps.size();
1506 String[] apps = new String[size];
1507 int cur = 0;
1508 for (int i = 0; i < mPowerSaveWhitelistAppsExceptIdle.size(); i++) {
1509 apps[cur] = mPowerSaveWhitelistAppsExceptIdle.keyAt(i);
1510 cur++;
1511 }
1512 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1513 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
1514 cur++;
1515 }
1516 return apps;
1517 }
1518 }
1519
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001520 public String[] getFullPowerWhitelistInternal() {
1521 synchronized (this) {
1522 int size = mPowerSaveWhitelistApps.size() + mPowerSaveWhitelistUserApps.size();
1523 String[] apps = new String[size];
1524 int cur = 0;
1525 for (int i = 0; i < mPowerSaveWhitelistApps.size(); i++) {
1526 apps[cur] = mPowerSaveWhitelistApps.keyAt(i);
1527 cur++;
1528 }
1529 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1530 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
1531 cur++;
1532 }
1533 return apps;
1534 }
1535 }
1536
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001537 public boolean isPowerSaveWhitelistExceptIdleAppInternal(String packageName) {
1538 synchronized (this) {
1539 return mPowerSaveWhitelistAppsExceptIdle.containsKey(packageName)
1540 || mPowerSaveWhitelistUserApps.containsKey(packageName);
1541 }
1542 }
1543
Amith Yamasani06bf8242015-05-08 16:36:21 -07001544 public boolean isPowerSaveWhitelistAppInternal(String packageName) {
1545 synchronized (this) {
1546 return mPowerSaveWhitelistApps.containsKey(packageName)
1547 || mPowerSaveWhitelistUserApps.containsKey(packageName);
1548 }
1549 }
1550
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001551 public int[] getAppIdWhitelistExceptIdleInternal() {
1552 synchronized (this) {
1553 return mPowerSaveWhitelistExceptIdleAppIdArray;
1554 }
1555 }
1556
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001557 public int[] getAppIdWhitelistInternal() {
1558 synchronized (this) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001559 return mPowerSaveWhitelistAllAppIdArray;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001560 }
1561 }
1562
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001563 public int[] getAppIdUserWhitelistInternal() {
1564 synchronized (this) {
1565 return mPowerSaveWhitelistUserAppIdArray;
1566 }
1567 }
1568
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001569 public int[] getAppIdTempWhitelistInternal() {
1570 synchronized (this) {
1571 return mTempWhitelistAppIdArray;
1572 }
1573 }
1574
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001575 void addPowerSaveTempWhitelistAppChecked(String packageName, long duration,
1576 int userId, String reason) throws RemoteException {
1577 getContext().enforceCallingPermission(
1578 Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
1579 "No permission to change device idle whitelist");
1580 final int callingUid = Binder.getCallingUid();
1581 userId = ActivityManagerNative.getDefault().handleIncomingUser(
1582 Binder.getCallingPid(),
1583 callingUid,
1584 userId,
1585 /*allowAll=*/ false,
1586 /*requireFull=*/ false,
1587 "addPowerSaveTempWhitelistApp", null);
1588 final long token = Binder.clearCallingIdentity();
1589 try {
1590 addPowerSaveTempWhitelistAppInternal(callingUid,
1591 packageName, duration, userId, true, reason);
1592 } finally {
1593 Binder.restoreCallingIdentity(token);
1594 }
1595 }
1596
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001597 /**
1598 * Adds an app to the temporary whitelist and resets the endTime for granting the
1599 * app an exemption to access network and acquire wakelocks.
1600 */
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001601 void addPowerSaveTempWhitelistAppInternal(int callingUid, String packageName,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001602 long duration, int userId, boolean sync, String reason) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001603 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001604 int uid = getContext().getPackageManager().getPackageUidAsUser(packageName, userId);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001605 int appId = UserHandle.getAppId(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001606 addPowerSaveTempWhitelistAppDirectInternal(callingUid, appId, duration, sync, reason);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001607 } catch (NameNotFoundException e) {
1608 }
1609 }
1610
Dianne Hackborna750a632015-06-16 17:18:23 -07001611 /**
1612 * Adds an app to the temporary whitelist and resets the endTime for granting the
1613 * app an exemption to access network and acquire wakelocks.
1614 */
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001615 void addPowerSaveTempWhitelistAppDirectInternal(int callingUid, int appId,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001616 long duration, boolean sync, String reason) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001617 final long timeNow = SystemClock.elapsedRealtime();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001618 Runnable networkPolicyTempWhitelistCallback = null;
Dianne Hackborna750a632015-06-16 17:18:23 -07001619 synchronized (this) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001620 int callingAppId = UserHandle.getAppId(callingUid);
1621 if (callingAppId >= Process.FIRST_APPLICATION_UID) {
1622 if (!mPowerSaveWhitelistSystemAppIds.get(callingAppId)) {
1623 throw new SecurityException("Calling app " + UserHandle.formatUid(callingUid)
1624 + " is not on whitelist");
1625 }
1626 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001627 duration = Math.min(duration, mConstants.MAX_TEMP_APP_WHITELIST_DURATION);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001628 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.get(appId);
1629 final boolean newEntry = entry == null;
Dianne Hackborna750a632015-06-16 17:18:23 -07001630 // Set the new end time
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001631 if (newEntry) {
1632 entry = new Pair<>(new MutableLong(0), reason);
1633 mTempWhitelistAppIdEndTimes.put(appId, entry);
1634 }
1635 entry.first.value = timeNow + duration;
Dianne Hackborna750a632015-06-16 17:18:23 -07001636 if (DEBUG) {
1637 Slog.d(TAG, "Adding AppId " + appId + " to temp whitelist");
1638 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001639 if (newEntry) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001640 // No pending timeout for the app id, post a delayed message
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001641 try {
1642 mBatteryStats.noteEvent(BatteryStats.HistoryItem.EVENT_TEMP_WHITELIST_START,
1643 reason, appId);
1644 } catch (RemoteException e) {
1645 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001646 postTempActiveTimeoutMessage(appId, duration);
1647 updateTempWhitelistAppIdsLocked();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001648 if (mNetworkPolicyTempWhitelistCallback != null) {
1649 if (!sync) {
1650 mHandler.post(mNetworkPolicyTempWhitelistCallback);
1651 } else {
1652 networkPolicyTempWhitelistCallback = mNetworkPolicyTempWhitelistCallback;
1653 }
1654 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001655 reportTempWhitelistChangedLocked();
1656 }
1657 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001658 if (networkPolicyTempWhitelistCallback != null) {
1659 networkPolicyTempWhitelistCallback.run();
1660 }
1661 }
1662
1663 public void setNetworkPolicyTempWhitelistCallbackInternal(Runnable callback) {
1664 synchronized (this) {
1665 mNetworkPolicyTempWhitelistCallback = callback;
1666 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001667 }
1668
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001669 private void postTempActiveTimeoutMessage(int uid, long delay) {
1670 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_TEMP_APP_WHITELIST_TIMEOUT, uid, 0),
1671 delay);
1672 }
1673
1674 void checkTempAppWhitelistTimeout(int uid) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001675 final long timeNow = SystemClock.elapsedRealtime();
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001676 synchronized (this) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001677 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.get(uid);
1678 if (entry == null) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001679 // Nothing to do
1680 return;
1681 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001682 if (timeNow >= entry.first.value) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001683 mTempWhitelistAppIdEndTimes.delete(uid);
1684 if (DEBUG) {
1685 Slog.d(TAG, "Removing UID " + uid + " from temp whitelist");
1686 }
1687 updateTempWhitelistAppIdsLocked();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001688 if (mNetworkPolicyTempWhitelistCallback != null) {
1689 mHandler.post(mNetworkPolicyTempWhitelistCallback);
1690 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001691 reportTempWhitelistChangedLocked();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001692 try {
1693 mBatteryStats.noteEvent(BatteryStats.HistoryItem.EVENT_TEMP_WHITELIST_FINISH,
1694 entry.second, uid);
1695 } catch (RemoteException e) {
1696 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001697 } else {
1698 // Need more time
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001699 postTempActiveTimeoutMessage(uid, entry.first.value - timeNow);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001700 }
1701 }
1702 }
1703
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001704 public void exitIdleInternal(String reason) {
1705 synchronized (this) {
1706 becomeActiveLocked(reason, Binder.getCallingUid());
1707 }
1708 }
1709
Dianne Hackborn88c41352016-04-07 15:18:58 -07001710 void updateConnectivityStateLocked(Intent connIntent) {
1711 if (mConnectivityService != null) {
1712 NetworkInfo ni = mConnectivityService.getActiveNetworkInfo();
1713 boolean conn;
1714 if (ni == null) {
1715 conn = false;
1716 } else {
1717 if (connIntent == null) {
1718 conn = ni.isConnected();
1719 } else {
1720 final int networkType =
1721 connIntent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1722 ConnectivityManager.TYPE_NONE);
1723 if (ni.getType() != networkType) {
1724 return;
1725 }
1726 conn = !connIntent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,
1727 false);
1728 }
1729 }
1730 if (conn != mNetworkConnected) {
1731 mNetworkConnected = conn;
1732 if (conn && mLightState == LIGHT_STATE_WAITING_FOR_NETWORK) {
1733 stepLightIdleStateLocked("network");
1734 }
1735 }
1736 }
1737 }
1738
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001739 void updateDisplayLocked() {
1740 mCurDisplay = mDisplayManager.getDisplay(Display.DEFAULT_DISPLAY);
1741 // We consider any situation where the display is showing something to be it on,
1742 // because if there is anything shown we are going to be updating it at some
1743 // frequency so can't be allowed to go into deep sleeps.
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001744 boolean screenOn = mCurDisplay.getState() == Display.STATE_ON;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001745 if (DEBUG) Slog.d(TAG, "updateDisplayLocked: screenOn=" + screenOn);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001746 if (!screenOn && mScreenOn) {
1747 mScreenOn = false;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001748 if (!mForceIdle) {
1749 becomeInactiveIfAppropriateLocked();
1750 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001751 } else if (screenOn) {
1752 mScreenOn = true;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001753 if (!mForceIdle) {
1754 becomeActiveLocked("screen", Process.myUid());
1755 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001756 }
1757 }
1758
1759 void updateChargingLocked(boolean charging) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001760 if (DEBUG) Slog.i(TAG, "updateChargingLocked: charging=" + charging);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001761 if (!charging && mCharging) {
1762 mCharging = false;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001763 if (!mForceIdle) {
1764 becomeInactiveIfAppropriateLocked();
1765 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001766 } else if (charging) {
1767 mCharging = charging;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001768 if (!mForceIdle) {
1769 becomeActiveLocked("charging", Process.myUid());
1770 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001771 }
1772 }
1773
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001774 void scheduleReportActiveLocked(String activeReason, int activeUid) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001775 Message msg = mHandler.obtainMessage(MSG_REPORT_ACTIVE, activeUid, 0, activeReason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001776 mHandler.sendMessage(msg);
1777 }
1778
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001779 void becomeActiveLocked(String activeReason, int activeUid) {
1780 if (DEBUG) Slog.i(TAG, "becomeActiveLocked, reason = " + activeReason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001781 if (mState != STATE_ACTIVE || mLightState != STATE_ACTIVE) {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001782 EventLogTags.writeDeviceIdle(STATE_ACTIVE, activeReason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001783 EventLogTags.writeDeviceIdleLight(LIGHT_STATE_ACTIVE, activeReason);
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001784 scheduleReportActiveLocked(activeReason, activeUid);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001785 mState = STATE_ACTIVE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001786 mLightState = LIGHT_STATE_ACTIVE;
Adam Lesinski31c05d12015-06-09 17:34:04 -07001787 mInactiveTimeout = mConstants.INACTIVE_TIMEOUT;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001788 mCurIdleBudget = 0;
1789 mMaintenanceStartTime = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001790 resetIdleManagementLocked();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001791 resetLightIdleManagementLocked();
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001792 addEvent(EVENT_NORMAL);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001793 }
1794 }
1795
1796 void becomeInactiveIfAppropriateLocked() {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001797 if (DEBUG) Slog.d(TAG, "becomeInactiveIfAppropriateLocked()");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001798 if ((!mScreenOn && !mCharging) || mForceIdle) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001799 // Screen has turned off; we are now going to become inactive and start
1800 // waiting to see if we will ultimately go idle.
Dianne Hackbornb6843652016-02-22 12:20:13 -08001801 if (mState == STATE_ACTIVE && mDeepEnabled) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001802 mState = STATE_INACTIVE;
1803 if (DEBUG) Slog.d(TAG, "Moved from STATE_ACTIVE to STATE_INACTIVE");
1804 resetIdleManagementLocked();
1805 scheduleAlarmLocked(mInactiveTimeout, false);
1806 EventLogTags.writeDeviceIdle(mState, "no activity");
1807 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001808 if (mLightState == LIGHT_STATE_ACTIVE && mLightEnabled) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001809 mLightState = LIGHT_STATE_INACTIVE;
1810 if (DEBUG) Slog.d(TAG, "Moved from LIGHT_STATE_ACTIVE to LIGHT_STATE_INACTIVE");
1811 resetLightIdleManagementLocked();
Dianne Hackborn953fc942016-03-29 15:36:24 -07001812 scheduleLightAlarmLocked(mConstants.LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001813 EventLogTags.writeDeviceIdleLight(mLightState, "no activity");
1814 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001815 }
1816 }
1817
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001818 void resetIdleManagementLocked() {
1819 mNextIdlePendingDelay = 0;
1820 mNextIdleDelay = 0;
Dianne Hackborn953fc942016-03-29 15:36:24 -07001821 mNextLightIdleDelay = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001822 cancelAlarmLocked();
Kevin Gabayan92f15e62016-04-04 17:52:22 -07001823 cancelSensingTimeoutAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001824 cancelLocatingLocked();
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001825 stopMonitoringMotionLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001826 mAnyMotionDetector.stop();
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001827 }
1828
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001829 void resetLightIdleManagementLocked() {
1830 cancelLightAlarmLocked();
1831 }
1832
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001833 void exitForceIdleLocked() {
1834 if (mForceIdle) {
1835 mForceIdle = false;
1836 if (mScreenOn || mCharging) {
Dianne Hackborn88c41352016-04-07 15:18:58 -07001837 becomeActiveLocked("exit-force", Process.myUid());
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001838 }
1839 }
1840 }
1841
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001842 void stepLightIdleStateLocked(String reason) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001843 if (mLightState == LIGHT_STATE_OVERRIDE) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001844 // If we are already in deep device idle mode, then
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001845 // there is nothing left to do for light mode.
1846 return;
1847 }
1848
1849 if (DEBUG) Slog.d(TAG, "stepLightIdleStateLocked: mLightState=" + mLightState);
1850 EventLogTags.writeDeviceIdleLightStep();
1851
1852 switch (mLightState) {
1853 case LIGHT_STATE_INACTIVE:
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001854 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
Dianne Hackborn953fc942016-03-29 15:36:24 -07001855 // Reset the upcoming idle delays.
1856 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001857 mMaintenanceStartTime = 0;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001858 if (!isOpsInactiveLocked()) {
1859 // We have some active ops going on... give them a chance to finish
1860 // before going in to our first idle.
1861 mLightState = LIGHT_STATE_PRE_IDLE;
1862 EventLogTags.writeDeviceIdleLight(mLightState, reason);
1863 scheduleLightAlarmLocked(mConstants.LIGHT_PRE_IDLE_TIMEOUT);
1864 break;
1865 }
1866 // Nothing active, fall through to immediately idle.
1867 case LIGHT_STATE_PRE_IDLE:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001868 case LIGHT_STATE_IDLE_MAINTENANCE:
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001869 if (mMaintenanceStartTime != 0) {
1870 long duration = SystemClock.elapsedRealtime() - mMaintenanceStartTime;
1871 if (duration < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
1872 // We didn't use up all of our minimum budget; add this to the reserve.
1873 mCurIdleBudget += (mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET-duration);
1874 } else {
1875 // We used more than our minimum budget; this comes out of the reserve.
1876 mCurIdleBudget -= (duration-mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET);
1877 }
1878 }
1879 mMaintenanceStartTime = 0;
Dianne Hackborn953fc942016-03-29 15:36:24 -07001880 scheduleLightAlarmLocked(mNextLightIdleDelay);
1881 mNextLightIdleDelay = Math.min(mConstants.LIGHT_MAX_IDLE_TIMEOUT,
1882 (long)(mNextLightIdleDelay * mConstants.LIGHT_IDLE_FACTOR));
1883 if (mNextLightIdleDelay < mConstants.LIGHT_IDLE_TIMEOUT) {
1884 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
1885 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001886 if (DEBUG) Slog.d(TAG, "Moved to LIGHT_STATE_IDLE.");
1887 mLightState = LIGHT_STATE_IDLE;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001888 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001889 addEvent(EVENT_LIGHT_IDLE);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001890 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON_LIGHT);
1891 break;
1892 case LIGHT_STATE_IDLE:
Dianne Hackborn88c41352016-04-07 15:18:58 -07001893 case LIGHT_STATE_WAITING_FOR_NETWORK:
1894 if (mNetworkConnected || mLightState == LIGHT_STATE_WAITING_FOR_NETWORK) {
1895 // We have been idling long enough, now it is time to do some work.
1896 mActiveIdleOpCount = 1;
1897 mActiveIdleWakeLock.acquire();
1898 mMaintenanceStartTime = SystemClock.elapsedRealtime();
1899 if (mCurIdleBudget < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
1900 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
1901 } else if (mCurIdleBudget > mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET) {
1902 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET;
1903 }
1904 scheduleLightAlarmLocked(mCurIdleBudget);
1905 if (DEBUG) Slog.d(TAG,
1906 "Moved from LIGHT_STATE_IDLE to LIGHT_STATE_IDLE_MAINTENANCE.");
1907 mLightState = LIGHT_STATE_IDLE_MAINTENANCE;
1908 EventLogTags.writeDeviceIdleLight(mLightState, reason);
1909 addEvent(EVENT_LIGHT_MAINTENANCE);
1910 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
1911 } else {
1912 // We'd like to do maintenance, but currently don't have network
1913 // connectivity... let's try to wait until the network comes back.
1914 // We'll only wait for another full idle period, however, and then give up.
1915 scheduleLightAlarmLocked(mNextLightIdleDelay);
1916 if (DEBUG) Slog.d(TAG, "Moved to LIGHT_WAITING_FOR_NETWORK.");
1917 mLightState = LIGHT_STATE_WAITING_FOR_NETWORK;
1918 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001919 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001920 break;
1921 }
1922 }
1923
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001924 void stepIdleStateLocked(String reason) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001925 if (DEBUG) Slog.d(TAG, "stepIdleStateLocked: mState=" + mState);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001926 EventLogTags.writeDeviceIdleStep();
1927
1928 final long now = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07001929 if ((now+mConstants.MIN_TIME_TO_ALARM) > mAlarmManager.getNextWakeFromIdleTime()) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001930 // Whoops, there is an upcoming alarm. We don't actually want to go idle.
1931 if (mState != STATE_ACTIVE) {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001932 becomeActiveLocked("alarm", Process.myUid());
Koji Fukui27b33302015-12-16 19:43:01 +09001933 becomeInactiveIfAppropriateLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001934 }
1935 return;
1936 }
1937
1938 switch (mState) {
1939 case STATE_INACTIVE:
1940 // We have now been inactive long enough, it is time to start looking
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001941 // for motion and sleep some more while doing so.
1942 startMonitoringMotionLocked();
Adam Lesinski31c05d12015-06-09 17:34:04 -07001943 scheduleAlarmLocked(mConstants.IDLE_AFTER_INACTIVE_TIMEOUT, false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001944 // Reset the upcoming idle delays.
Adam Lesinski31c05d12015-06-09 17:34:04 -07001945 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
1946 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001947 mState = STATE_IDLE_PENDING;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001948 if (DEBUG) Slog.d(TAG, "Moved from STATE_INACTIVE to STATE_IDLE_PENDING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001949 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001950 break;
1951 case STATE_IDLE_PENDING:
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001952 mState = STATE_SENSING;
1953 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE_PENDING to STATE_SENSING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001954 EventLogTags.writeDeviceIdle(mState, reason);
Kevin Gabayan92f15e62016-04-04 17:52:22 -07001955 scheduleSensingTimeoutAlarmLocked(mConstants.SENSING_TIMEOUT);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001956 cancelLocatingLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001957 mNotMoving = false;
1958 mLocated = false;
1959 mLastGenericLocation = null;
1960 mLastGpsLocation = null;
Kevin Gabayan92f15e62016-04-04 17:52:22 -07001961 mAnyMotionDetector.checkForAnyMotion();
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001962 break;
1963 case STATE_SENSING:
Kevin Gabayan92f15e62016-04-04 17:52:22 -07001964 cancelSensingTimeoutAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001965 mState = STATE_LOCATING;
1966 if (DEBUG) Slog.d(TAG, "Moved from STATE_SENSING to STATE_LOCATING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001967 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001968 scheduleAlarmLocked(mConstants.LOCATING_TIMEOUT, false);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001969 if (mLocationManager != null
1970 && mLocationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
1971 mLocationManager.requestLocationUpdates(mLocationRequest,
1972 mGenericLocationListener, mHandler.getLooper());
1973 mLocating = true;
1974 } else {
1975 mHasNetworkLocation = false;
1976 }
1977 if (mLocationManager != null
1978 && mLocationManager.getProvider(LocationManager.GPS_PROVIDER) != null) {
1979 mHasGps = true;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001980 mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 5,
1981 mGpsLocationListener, mHandler.getLooper());
Joe LaPenna23d681b2015-08-27 15:12:11 -07001982 mLocating = true;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001983 } else {
Joe LaPenna23d681b2015-08-27 15:12:11 -07001984 mHasGps = false;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001985 }
Joe LaPenna23d681b2015-08-27 15:12:11 -07001986 // If we have a location provider, we're all set, the listeners will move state
1987 // forward.
1988 if (mLocating) {
1989 break;
1990 }
1991
1992 // Otherwise, we have to move from locating into idle maintenance.
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001993 case STATE_LOCATING:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001994 cancelAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001995 cancelLocatingLocked();
1996 mAnyMotionDetector.stop();
Dianne Hackborn953fc942016-03-29 15:36:24 -07001997
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001998 case STATE_IDLE_MAINTENANCE:
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001999 scheduleAlarmLocked(mNextIdleDelay, true);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002000 if (DEBUG) Slog.d(TAG, "Moved to STATE_IDLE. Next alarm in " + mNextIdleDelay +
2001 " ms.");
Adam Lesinski31c05d12015-06-09 17:34:04 -07002002 mNextIdleDelay = (long)(mNextIdleDelay * mConstants.IDLE_FACTOR);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002003 if (DEBUG) Slog.d(TAG, "Setting mNextIdleDelay = " + mNextIdleDelay);
Adam Lesinski31c05d12015-06-09 17:34:04 -07002004 mNextIdleDelay = Math.min(mNextIdleDelay, mConstants.MAX_IDLE_TIMEOUT);
Dianne Hackborn953fc942016-03-29 15:36:24 -07002005 if (mNextIdleDelay < mConstants.IDLE_TIMEOUT) {
2006 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
2007 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002008 mState = STATE_IDLE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002009 if (mLightState != LIGHT_STATE_OVERRIDE) {
2010 mLightState = LIGHT_STATE_OVERRIDE;
2011 cancelLightAlarmLocked();
2012 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002013 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackbornb6843652016-02-22 12:20:13 -08002014 addEvent(EVENT_DEEP_IDLE);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002015 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON);
2016 break;
2017 case STATE_IDLE:
2018 // We have been idling long enough, now it is time to do some work.
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002019 mActiveIdleOpCount = 1;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002020 mActiveIdleWakeLock.acquire();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002021 scheduleAlarmLocked(mNextIdlePendingDelay, false);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002022 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE to STATE_IDLE_MAINTENANCE. " +
2023 "Next alarm in " + mNextIdlePendingDelay + " ms.");
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002024 mMaintenanceStartTime = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07002025 mNextIdlePendingDelay = Math.min(mConstants.MAX_IDLE_PENDING_TIMEOUT,
2026 (long)(mNextIdlePendingDelay * mConstants.IDLE_PENDING_FACTOR));
Dianne Hackborn953fc942016-03-29 15:36:24 -07002027 if (mNextIdlePendingDelay < mConstants.IDLE_PENDING_TIMEOUT) {
2028 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
2029 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002030 mState = STATE_IDLE_MAINTENANCE;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002031 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackbornb6843652016-02-22 12:20:13 -08002032 addEvent(EVENT_DEEP_MAINTENANCE);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002033 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
2034 break;
2035 }
2036 }
2037
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002038 void incActiveIdleOps() {
2039 synchronized (this) {
2040 mActiveIdleOpCount++;
2041 }
2042 }
2043
2044 void decActiveIdleOps() {
2045 synchronized (this) {
2046 mActiveIdleOpCount--;
2047 if (mActiveIdleOpCount <= 0) {
2048 exitMaintenanceEarlyIfNeededLocked();
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002049 mActiveIdleWakeLock.release();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002050 }
2051 }
2052 }
2053
2054 void downloadServiceActive(IBinder token) {
2055 synchronized (this) {
2056 mDownloadServiceActive = token;
Yao Chenca5edbb2016-01-13 14:44:36 -08002057 reportMaintenanceActivityIfNeededLocked();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002058 try {
2059 token.linkToDeath(new IBinder.DeathRecipient() {
2060 @Override public void binderDied() {
2061 downloadServiceInactive();
2062 }
2063 }, 0);
2064 } catch (RemoteException e) {
2065 mDownloadServiceActive = null;
2066 }
2067 }
2068 }
2069
2070 void downloadServiceInactive() {
2071 synchronized (this) {
2072 mDownloadServiceActive = null;
Yao Chenca5edbb2016-01-13 14:44:36 -08002073 reportMaintenanceActivityIfNeededLocked();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002074 exitMaintenanceEarlyIfNeededLocked();
2075 }
2076 }
2077
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002078 void setJobsActive(boolean active) {
2079 synchronized (this) {
2080 mJobsActive = active;
Yao Chenca5edbb2016-01-13 14:44:36 -08002081 reportMaintenanceActivityIfNeededLocked();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002082 if (!active) {
2083 exitMaintenanceEarlyIfNeededLocked();
2084 }
2085 }
2086 }
2087
2088 void setAlarmsActive(boolean active) {
2089 synchronized (this) {
2090 mAlarmsActive = active;
2091 if (!active) {
2092 exitMaintenanceEarlyIfNeededLocked();
2093 }
2094 }
2095 }
2096
Yao Chenca5edbb2016-01-13 14:44:36 -08002097 boolean registerMaintenanceActivityListener(IMaintenanceActivityListener listener) {
2098 synchronized (this) {
2099 mMaintenanceActivityListeners.register(listener);
2100 return mReportedMaintenanceActivity;
2101 }
2102 }
2103
2104 void unregisterMaintenanceActivityListener(IMaintenanceActivityListener listener) {
2105 synchronized (this) {
2106 mMaintenanceActivityListeners.unregister(listener);
2107 }
2108 }
2109
2110 void reportMaintenanceActivityIfNeededLocked() {
Amith Yamasanicb926fc2016-03-14 17:15:20 -07002111 boolean active = mJobsActive | (mDownloadServiceActive != null);
Yao Chenca5edbb2016-01-13 14:44:36 -08002112 if (active == mReportedMaintenanceActivity) {
2113 return;
2114 }
2115 mReportedMaintenanceActivity = active;
2116 Message msg = mHandler.obtainMessage(MSG_REPORT_MAINTENANCE_ACTIVITY,
2117 mReportedMaintenanceActivity ? 1 : 0, 0);
2118 mHandler.sendMessage(msg);
2119 }
2120
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002121 boolean isOpsInactiveLocked() {
2122 return mActiveIdleOpCount <= 0 && mDownloadServiceActive == null
2123 && !mJobsActive && !mAlarmsActive;
2124 }
2125
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002126 void exitMaintenanceEarlyIfNeededLocked() {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002127 if (mState == STATE_IDLE_MAINTENANCE || mLightState == LIGHT_STATE_IDLE_MAINTENANCE
2128 || mLightState == LIGHT_STATE_PRE_IDLE) {
2129 if (isOpsInactiveLocked()) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002130 final long now = SystemClock.elapsedRealtime();
2131 if (DEBUG) {
2132 StringBuilder sb = new StringBuilder();
2133 sb.append("Exit: start=");
2134 TimeUtils.formatDuration(mMaintenanceStartTime, sb);
2135 sb.append(" now=");
2136 TimeUtils.formatDuration(now, sb);
2137 Slog.d(TAG, sb.toString());
2138 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002139 if (mState == STATE_IDLE_MAINTENANCE) {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002140 stepIdleStateLocked("s:early");
2141 } else if (mLightState == LIGHT_STATE_PRE_IDLE) {
2142 stepLightIdleStateLocked("s:predone");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002143 } else {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002144 stepLightIdleStateLocked("s:early");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002145 }
2146 }
2147 }
2148 }
2149
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002150 void motionLocked() {
2151 if (DEBUG) Slog.d(TAG, "motionLocked()");
2152 // The motion sensor will have been disabled at this point
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002153 handleMotionDetectedLocked(mConstants.MOTION_INACTIVE_TIMEOUT, "motion");
2154 }
2155
2156 void handleMotionDetectedLocked(long timeout, String type) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002157 // The device is not yet active, so we want to go back to the pending idle
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002158 // state to wait again for no motion. Note that we only monitor for motion
2159 // after moving out of the inactive state, so no need to worry about that.
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002160 boolean becomeInactive = false;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002161 if (mState != STATE_ACTIVE) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002162 scheduleReportActiveLocked(type, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002163 mState = STATE_ACTIVE;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002164 mInactiveTimeout = timeout;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002165 mCurIdleBudget = 0;
2166 mMaintenanceStartTime = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002167 EventLogTags.writeDeviceIdle(mState, type);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002168 addEvent(EVENT_NORMAL);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002169 becomeInactive = true;
2170 }
2171 if (mLightState == LIGHT_STATE_OVERRIDE) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002172 // We went out of light idle mode because we had started deep idle mode... let's
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002173 // now go back and reset things so we resume light idling if appropriate.
2174 mLightState = STATE_ACTIVE;
2175 EventLogTags.writeDeviceIdleLight(mLightState, type);
2176 becomeInactive = true;
2177 }
2178 if (becomeInactive) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002179 becomeInactiveIfAppropriateLocked();
2180 }
2181 }
2182
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002183 void receivedGenericLocationLocked(Location location) {
2184 if (mState != STATE_LOCATING) {
2185 cancelLocatingLocked();
2186 return;
2187 }
2188 if (DEBUG) Slog.d(TAG, "Generic location: " + location);
2189 mLastGenericLocation = new Location(location);
Joe LaPenna23d681b2015-08-27 15:12:11 -07002190 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY && mHasGps) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002191 return;
2192 }
2193 mLocated = true;
2194 if (mNotMoving) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002195 stepIdleStateLocked("s:location");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002196 }
2197 }
2198
2199 void receivedGpsLocationLocked(Location location) {
2200 if (mState != STATE_LOCATING) {
2201 cancelLocatingLocked();
2202 return;
2203 }
2204 if (DEBUG) Slog.d(TAG, "GPS location: " + location);
2205 mLastGpsLocation = new Location(location);
2206 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY) {
2207 return;
2208 }
2209 mLocated = true;
2210 if (mNotMoving) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002211 stepIdleStateLocked("s:gps");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002212 }
2213 }
2214
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002215 void startMonitoringMotionLocked() {
2216 if (DEBUG) Slog.d(TAG, "startMonitoringMotionLocked()");
2217 if (mMotionSensor != null && !mMotionListener.active) {
2218 mMotionListener.registerLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002219 }
2220 }
2221
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002222 void stopMonitoringMotionLocked() {
2223 if (DEBUG) Slog.d(TAG, "stopMonitoringMotionLocked()");
2224 if (mMotionSensor != null && mMotionListener.active) {
2225 mMotionListener.unregisterLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002226 }
2227 }
2228
2229 void cancelAlarmLocked() {
2230 if (mNextAlarmTime != 0) {
2231 mNextAlarmTime = 0;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002232 mAlarmManager.cancel(mDeepAlarmListener);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002233 }
2234 }
2235
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002236 void cancelLightAlarmLocked() {
2237 if (mNextLightAlarmTime != 0) {
2238 mNextLightAlarmTime = 0;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002239 mAlarmManager.cancel(mLightAlarmListener);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002240 }
2241 }
2242
2243 void cancelLocatingLocked() {
2244 if (mLocating) {
2245 mLocationManager.removeUpdates(mGenericLocationListener);
2246 mLocationManager.removeUpdates(mGpsLocationListener);
2247 mLocating = false;
2248 }
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002249 }
2250
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002251 void cancelSensingTimeoutAlarmLocked() {
2252 if (mNextSensingTimeoutAlarmTime != 0) {
2253 mNextSensingTimeoutAlarmTime = 0;
2254 mAlarmManager.cancel(mSensingTimeoutAlarmListener);
2255 }
2256 }
2257
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002258 void scheduleAlarmLocked(long delay, boolean idleUntil) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002259 if (DEBUG) Slog.d(TAG, "scheduleAlarmLocked(" + delay + ", " + idleUntil + ")");
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002260 if (mMotionSensor == null) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07002261 // If there is no motion sensor on this device, then we won't schedule
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002262 // alarms, because we can't determine if the device is not moving. This effectively
Joe LaPenna23d681b2015-08-27 15:12:11 -07002263 // turns off normal execution of device idling, although it is still possible to
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002264 // manually poke it by pretending like the alarm is going off.
2265 return;
2266 }
2267 mNextAlarmTime = SystemClock.elapsedRealtime() + delay;
2268 if (idleUntil) {
2269 mAlarmManager.setIdleUntil(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002270 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002271 } else {
2272 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002273 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002274 }
2275 }
2276
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002277 void scheduleLightAlarmLocked(long delay) {
2278 if (DEBUG) Slog.d(TAG, "scheduleLightAlarmLocked(" + delay + ")");
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002279 mNextLightAlarmTime = SystemClock.elapsedRealtime() + delay;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002280 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002281 mNextLightAlarmTime, "DeviceIdleController.light", mLightAlarmListener, mHandler);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002282 }
2283
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002284 void scheduleSensingTimeoutAlarmLocked(long delay) {
2285 if (DEBUG) Slog.d(TAG, "scheduleSensingAlarmLocked(" + delay + ")");
2286 mNextSensingTimeoutAlarmTime = SystemClock.elapsedRealtime() + delay;
2287 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, mNextSensingTimeoutAlarmTime,
2288 "DeviceIdleController.sensing", mSensingTimeoutAlarmListener, mHandler);
2289 }
2290
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002291 private static int[] buildAppIdArray(ArrayMap<String, Integer> systemApps,
2292 ArrayMap<String, Integer> userApps, SparseBooleanArray outAppIds) {
2293 outAppIds.clear();
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002294 if (systemApps != null) {
2295 for (int i = 0; i < systemApps.size(); i++) {
2296 outAppIds.put(systemApps.valueAt(i), true);
2297 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002298 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002299 if (userApps != null) {
2300 for (int i = 0; i < userApps.size(); i++) {
2301 outAppIds.put(userApps.valueAt(i), true);
2302 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002303 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002304 int size = outAppIds.size();
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002305 int[] appids = new int[size];
2306 for (int i = 0; i < size; i++) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002307 appids[i] = outAppIds.keyAt(i);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002308 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002309 return appids;
2310 }
2311
2312 private void updateWhitelistAppIdsLocked() {
2313 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(mPowerSaveWhitelistAppsExceptIdle,
2314 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistExceptIdleAppIds);
2315 mPowerSaveWhitelistAllAppIdArray = buildAppIdArray(mPowerSaveWhitelistApps,
2316 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistAllAppIds);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002317 mPowerSaveWhitelistUserAppIdArray = buildAppIdArray(null,
2318 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistUserAppIds);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002319 if (mLocalPowerManager != null) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002320 if (DEBUG) {
2321 Slog.d(TAG, "Setting wakelock whitelist to "
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002322 + Arrays.toString(mPowerSaveWhitelistAllAppIdArray));
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002323 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002324 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002325 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002326 if (mLocalAlarmManager != null) {
2327 if (DEBUG) {
2328 Slog.d(TAG, "Setting alarm whitelist to "
2329 + Arrays.toString(mPowerSaveWhitelistUserAppIdArray));
2330 }
2331 mLocalAlarmManager.setDeviceIdleUserWhitelist(mPowerSaveWhitelistUserAppIdArray);
2332 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002333 }
2334
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002335 private void updateTempWhitelistAppIdsLocked() {
2336 final int size = mTempWhitelistAppIdEndTimes.size();
2337 if (mTempWhitelistAppIdArray.length != size) {
2338 mTempWhitelistAppIdArray = new int[size];
2339 }
2340 for (int i = 0; i < size; i++) {
2341 mTempWhitelistAppIdArray[i] = mTempWhitelistAppIdEndTimes.keyAt(i);
2342 }
2343 if (mLocalPowerManager != null) {
2344 if (DEBUG) {
2345 Slog.d(TAG, "Setting wakelock temp whitelist to "
2346 + Arrays.toString(mTempWhitelistAppIdArray));
2347 }
2348 mLocalPowerManager.setDeviceIdleTempWhitelist(mTempWhitelistAppIdArray);
2349 }
2350 }
2351
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002352 private void reportPowerSaveWhitelistChangedLocked() {
2353 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
2354 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Xiaohui Chene4de5a02015-09-22 15:33:31 -07002355 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002356 }
2357
2358 private void reportTempWhitelistChangedLocked() {
2359 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_TEMP_WHITELIST_CHANGED);
2360 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Xiaohui Chene4de5a02015-09-22 15:33:31 -07002361 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002362 }
2363
2364 void readConfigFileLocked() {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002365 if (DEBUG) Slog.d(TAG, "Reading config from " + mConfigFile.getBaseFile());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002366 mPowerSaveWhitelistUserApps.clear();
2367 FileInputStream stream;
2368 try {
2369 stream = mConfigFile.openRead();
2370 } catch (FileNotFoundException e) {
2371 return;
2372 }
2373 try {
2374 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002375 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002376 readConfigFileLocked(parser);
2377 } catch (XmlPullParserException e) {
2378 } finally {
2379 try {
2380 stream.close();
2381 } catch (IOException e) {
2382 }
2383 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002384 }
2385
2386 private void readConfigFileLocked(XmlPullParser parser) {
2387 final PackageManager pm = getContext().getPackageManager();
2388
2389 try {
2390 int type;
2391 while ((type = parser.next()) != XmlPullParser.START_TAG
2392 && type != XmlPullParser.END_DOCUMENT) {
2393 ;
2394 }
2395
2396 if (type != XmlPullParser.START_TAG) {
2397 throw new IllegalStateException("no start tag found");
2398 }
2399
2400 int outerDepth = parser.getDepth();
2401 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2402 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2403 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2404 continue;
2405 }
2406
2407 String tagName = parser.getName();
2408 if (tagName.equals("wl")) {
2409 String name = parser.getAttributeValue(null, "n");
2410 if (name != null) {
2411 try {
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07002412 ApplicationInfo ai = pm.getApplicationInfo(name,
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07002413 PackageManager.MATCH_UNINSTALLED_PACKAGES);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002414 mPowerSaveWhitelistUserApps.put(ai.packageName,
2415 UserHandle.getAppId(ai.uid));
2416 } catch (PackageManager.NameNotFoundException e) {
2417 }
2418 }
2419 } else {
2420 Slog.w(TAG, "Unknown element under <config>: "
2421 + parser.getName());
2422 XmlUtils.skipCurrentTag(parser);
2423 }
2424 }
2425
2426 } catch (IllegalStateException e) {
2427 Slog.w(TAG, "Failed parsing config " + e);
2428 } catch (NullPointerException e) {
2429 Slog.w(TAG, "Failed parsing config " + e);
2430 } catch (NumberFormatException e) {
2431 Slog.w(TAG, "Failed parsing config " + e);
2432 } catch (XmlPullParserException e) {
2433 Slog.w(TAG, "Failed parsing config " + e);
2434 } catch (IOException e) {
2435 Slog.w(TAG, "Failed parsing config " + e);
2436 } catch (IndexOutOfBoundsException e) {
2437 Slog.w(TAG, "Failed parsing config " + e);
2438 }
2439 }
2440
2441 void writeConfigFileLocked() {
2442 mHandler.removeMessages(MSG_WRITE_CONFIG);
2443 mHandler.sendEmptyMessageDelayed(MSG_WRITE_CONFIG, 5000);
2444 }
2445
2446 void handleWriteConfigFile() {
2447 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
2448
2449 try {
2450 synchronized (this) {
2451 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002452 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002453 writeConfigFileLocked(out);
2454 }
2455 } catch (IOException e) {
2456 }
2457
2458 synchronized (mConfigFile) {
2459 FileOutputStream stream = null;
2460 try {
2461 stream = mConfigFile.startWrite();
2462 memStream.writeTo(stream);
2463 stream.flush();
2464 FileUtils.sync(stream);
2465 stream.close();
2466 mConfigFile.finishWrite(stream);
2467 } catch (IOException e) {
2468 Slog.w(TAG, "Error writing config file", e);
2469 mConfigFile.failWrite(stream);
2470 }
2471 }
2472 }
2473
2474 void writeConfigFileLocked(XmlSerializer out) throws IOException {
2475 out.startDocument(null, true);
2476 out.startTag(null, "config");
2477 for (int i=0; i<mPowerSaveWhitelistUserApps.size(); i++) {
2478 String name = mPowerSaveWhitelistUserApps.keyAt(i);
2479 out.startTag(null, "wl");
2480 out.attribute(null, "n", name);
2481 out.endTag(null, "wl");
2482 }
2483 out.endTag(null, "config");
2484 out.endDocument();
2485 }
2486
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002487 static void dumpHelp(PrintWriter pw) {
2488 pw.println("Device idle controller (deviceidle) commands:");
2489 pw.println(" help");
2490 pw.println(" Print this help text.");
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002491 pw.println(" step [light|deep]");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002492 pw.println(" Immediately step to next state, without waiting for alarm.");
Dianne Hackborn88c41352016-04-07 15:18:58 -07002493 pw.println(" force-idle [light|deep]");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002494 pw.println(" Force directly into idle mode, regardless of other device state.");
Dianne Hackborn88c41352016-04-07 15:18:58 -07002495 pw.println(" force-inactive");
2496 pw.println(" Force to be inactive, ready to freely step idle states.");
2497 pw.println(" unforce");
2498 pw.println(" Resume normal functioning after force-idle or force-inactive.");
2499 pw.println(" get [light|deep|force|screen|charging|network]");
2500 pw.println(" Retrieve the current given state.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002501 pw.println(" disable [light|deep|all]");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002502 pw.println(" Completely disable device idle mode.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002503 pw.println(" enable [light|deep|all]");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002504 pw.println(" Re-enable device idle mode after it had previously been disabled.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002505 pw.println(" enabled [light|deep|all]");
Dianne Hackborn92617032015-06-19 15:32:19 -07002506 pw.println(" Print 1 if device idle mode is currently enabled, else 0.");
Dianne Hackborn1b139682015-07-06 15:13:37 -07002507 pw.println(" whitelist");
2508 pw.println(" Print currently whitelisted apps.");
Dianne Hackborn92617032015-06-19 15:32:19 -07002509 pw.println(" whitelist [package ...]");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002510 pw.println(" Add (prefix with +) or remove (prefix with -) packages.");
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002511 pw.println(" tempwhitelist [-u] [package ..]");
Dianne Hackborn92617032015-06-19 15:32:19 -07002512 pw.println(" Temporarily place packages in whitelist for 10 seconds.");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002513 }
2514
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002515 class Shell extends ShellCommand {
2516 int userId = UserHandle.USER_SYSTEM;
2517
2518 @Override
2519 public int onCommand(String cmd) {
2520 return onShellCommand(this, cmd);
2521 }
2522
2523 @Override
2524 public void onHelp() {
2525 PrintWriter pw = getOutPrintWriter();
2526 dumpHelp(pw);
2527 }
2528 }
2529
2530 int onShellCommand(Shell shell, String cmd) {
2531 PrintWriter pw = shell.getOutPrintWriter();
2532 if ("step".equals(cmd)) {
2533 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2534 null);
2535 synchronized (this) {
2536 long token = Binder.clearCallingIdentity();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002537 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002538 try {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002539 if (arg == null || "deep".equals(arg)) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002540 stepIdleStateLocked("s:shell");
2541 pw.print("Stepped to deep: ");
2542 pw.println(stateToString(mState));
2543 } else if ("light".equals(arg)) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002544 stepLightIdleStateLocked("s:shell");
2545 pw.print("Stepped to light: "); pw.println(lightStateToString(mLightState));
2546 } else {
2547 pw.println("Unknown idle mode: " + arg);
2548 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002549 } finally {
2550 Binder.restoreCallingIdentity(token);
2551 }
2552 }
2553 } else if ("force-idle".equals(cmd)) {
2554 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2555 null);
2556 synchronized (this) {
2557 long token = Binder.clearCallingIdentity();
Dianne Hackborn88c41352016-04-07 15:18:58 -07002558 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002559 try {
Dianne Hackborn88c41352016-04-07 15:18:58 -07002560 if (arg == null || "deep".equals(arg)) {
2561 if (!mDeepEnabled) {
2562 pw.println("Unable to go deep idle; not enabled");
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002563 return -1;
2564 }
Dianne Hackborn88c41352016-04-07 15:18:58 -07002565 mForceIdle = true;
2566 becomeInactiveIfAppropriateLocked();
2567 int curState = mState;
2568 while (curState != STATE_IDLE) {
2569 stepIdleStateLocked("s:shell");
2570 if (curState == mState) {
2571 pw.print("Unable to go deep idle; stopped at ");
2572 pw.println(stateToString(mState));
2573 exitForceIdleLocked();
2574 return -1;
2575 }
2576 curState = mState;
2577 }
2578 pw.println("Now forced in to deep idle mode");
2579 } else if ("light".equals(arg)) {
2580 mForceIdle = true;
2581 becomeInactiveIfAppropriateLocked();
2582 int curLightState = mLightState;
2583 while (curLightState != LIGHT_STATE_IDLE) {
2584 stepIdleStateLocked("s:shell");
2585 if (curLightState == mLightState) {
2586 pw.print("Unable to go light idle; stopped at ");
2587 pw.println(lightStateToString(mLightState));
2588 exitForceIdleLocked();
2589 return -1;
2590 }
2591 curLightState = mLightState;
2592 }
2593 pw.println("Now forced in to light idle mode");
2594 } else {
2595 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002596 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002597 } finally {
2598 Binder.restoreCallingIdentity(token);
2599 }
2600 }
Dianne Hackborn88c41352016-04-07 15:18:58 -07002601 } else if ("force-inactive".equals(cmd)) {
2602 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2603 null);
2604 synchronized (this) {
2605 long token = Binder.clearCallingIdentity();
2606 try {
2607 mForceIdle = true;
2608 becomeInactiveIfAppropriateLocked();
2609 pw.print("Light state: ");
2610 pw.print(lightStateToString(mLightState));
2611 pw.print(", deep state: ");
2612 pw.println(stateToString(mState));
2613 } finally {
2614 Binder.restoreCallingIdentity(token);
2615 }
2616 }
2617 } else if ("unforce".equals(cmd)) {
2618 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2619 null);
2620 synchronized (this) {
2621 long token = Binder.clearCallingIdentity();
2622 try {
2623 exitForceIdleLocked();
2624 pw.print("Light state: ");
2625 pw.print(lightStateToString(mLightState));
2626 pw.print(", deep state: ");
2627 pw.println(stateToString(mState));
2628 } finally {
2629 Binder.restoreCallingIdentity(token);
2630 }
2631 }
2632 } else if ("get".equals(cmd)) {
2633 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2634 null);
2635 synchronized (this) {
2636 String arg = shell.getNextArg();
2637 if (arg != null) {
2638 long token = Binder.clearCallingIdentity();
2639 try {
2640 switch (arg) {
2641 case "light": pw.println(lightStateToString(mLightState)); break;
2642 case "deep": pw.println(stateToString(mState)); break;
2643 case "force": pw.println(mForceIdle); break;
2644 case "screen": pw.println(mScreenOn); break;
2645 case "charging": pw.println(mCharging); break;
2646 case "network": pw.println(mNetworkConnected); break;
2647 default: pw.println("Unknown get option: " + arg); break;
2648 }
2649 } finally {
2650 Binder.restoreCallingIdentity(token);
2651 }
2652 } else {
2653 pw.println("Argument required");
2654 }
2655 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002656 } else if ("disable".equals(cmd)) {
2657 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2658 null);
2659 synchronized (this) {
2660 long token = Binder.clearCallingIdentity();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002661 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002662 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002663 boolean becomeActive = false;
2664 boolean valid = false;
2665 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
2666 valid = true;
2667 if (mDeepEnabled) {
2668 mDeepEnabled = false;
2669 becomeActive = true;
2670 pw.println("Deep idle mode disabled");
2671 }
2672 }
2673 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
2674 valid = true;
2675 if (mLightEnabled) {
2676 mLightEnabled = false;
2677 becomeActive = true;
2678 pw.println("Light idle mode disabled");
2679 }
2680 }
2681 if (becomeActive) {
2682 becomeActiveLocked((arg == null ? "all" : arg) + "-disabled",
2683 Process.myUid());
2684 }
2685 if (!valid) {
2686 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002687 }
2688 } finally {
2689 Binder.restoreCallingIdentity(token);
2690 }
2691 }
2692 } else if ("enable".equals(cmd)) {
2693 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2694 null);
2695 synchronized (this) {
2696 long token = Binder.clearCallingIdentity();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002697 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002698 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002699 boolean becomeInactive = false;
2700 boolean valid = false;
2701 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
2702 valid = true;
2703 if (!mDeepEnabled) {
2704 mDeepEnabled = true;
2705 becomeInactive = true;
2706 pw.println("Deep idle mode enabled");
2707 }
2708 }
2709 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
2710 valid = true;
2711 if (!mLightEnabled) {
2712 mLightEnabled = true;
2713 becomeInactive = true;
2714 pw.println("Light idle mode enable");
2715 }
2716 }
2717 if (becomeInactive) {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002718 becomeInactiveIfAppropriateLocked();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002719 }
2720 if (!valid) {
2721 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002722 }
2723 } finally {
2724 Binder.restoreCallingIdentity(token);
2725 }
2726 }
2727 } else if ("enabled".equals(cmd)) {
2728 synchronized (this) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002729 String arg = shell.getNextArg();
2730 if (arg == null || "all".equals(arg)) {
2731 pw.println(mDeepEnabled && mLightEnabled ? "1" : 0);
2732 } else if ("deep".equals(arg)) {
2733 pw.println(mDeepEnabled ? "1" : 0);
2734 } else if ("light".equals(arg)) {
2735 pw.println(mLightEnabled ? "1" : 0);
2736 } else {
2737 pw.println("Unknown idle mode: " + arg);
2738 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002739 }
2740 } else if ("whitelist".equals(cmd)) {
2741 long token = Binder.clearCallingIdentity();
2742 try {
2743 String arg = shell.getNextArg();
2744 if (arg != null) {
2745 getContext().enforceCallingOrSelfPermission(
2746 android.Manifest.permission.DEVICE_POWER, null);
2747 do {
2748 if (arg.length() < 1 || (arg.charAt(0) != '-'
Felipe Lemef8a46232016-02-10 13:51:54 -08002749 && arg.charAt(0) != '+' && arg.charAt(0) != '=')) {
2750 pw.println("Package must be prefixed with +, -, or =: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002751 return -1;
2752 }
2753 char op = arg.charAt(0);
2754 String pkg = arg.substring(1);
2755 if (op == '+') {
2756 if (addPowerSaveWhitelistAppInternal(pkg)) {
2757 pw.println("Added: " + pkg);
2758 } else {
2759 pw.println("Unknown package: " + pkg);
2760 }
Felipe Lemef8a46232016-02-10 13:51:54 -08002761 } else if (op == '-') {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002762 if (removePowerSaveWhitelistAppInternal(pkg)) {
2763 pw.println("Removed: " + pkg);
2764 }
Felipe Lemef8a46232016-02-10 13:51:54 -08002765 } else {
2766 pw.println(getPowerSaveWhitelistAppInternal(pkg));
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002767 }
2768 } while ((arg=shell.getNextArg()) != null);
2769 } else {
2770 synchronized (this) {
2771 for (int j=0; j<mPowerSaveWhitelistAppsExceptIdle.size(); j++) {
2772 pw.print("system-excidle,");
2773 pw.print(mPowerSaveWhitelistAppsExceptIdle.keyAt(j));
2774 pw.print(",");
2775 pw.println(mPowerSaveWhitelistAppsExceptIdle.valueAt(j));
2776 }
2777 for (int j=0; j<mPowerSaveWhitelistApps.size(); j++) {
2778 pw.print("system,");
2779 pw.print(mPowerSaveWhitelistApps.keyAt(j));
2780 pw.print(",");
2781 pw.println(mPowerSaveWhitelistApps.valueAt(j));
2782 }
2783 for (int j=0; j<mPowerSaveWhitelistUserApps.size(); j++) {
2784 pw.print("user,");
2785 pw.print(mPowerSaveWhitelistUserApps.keyAt(j));
2786 pw.print(",");
2787 pw.println(mPowerSaveWhitelistUserApps.valueAt(j));
2788 }
2789 }
2790 }
2791 } finally {
2792 Binder.restoreCallingIdentity(token);
2793 }
2794 } else if ("tempwhitelist".equals(cmd)) {
2795 String opt;
2796 while ((opt=shell.getNextOption()) != null) {
2797 if ("-u".equals(opt)) {
2798 opt = shell.getNextArg();
2799 if (opt == null) {
2800 pw.println("-u requires a user number");
2801 return -1;
2802 }
2803 shell.userId = Integer.parseInt(opt);
2804 }
2805 }
2806 String arg = shell.getNextArg();
2807 if (arg != null) {
2808 try {
2809 addPowerSaveTempWhitelistAppChecked(arg, 10000L, shell.userId, "shell");
2810 } catch (RemoteException re) {
2811 pw.println("Failed: " + re);
2812 }
2813 } else {
2814 pw.println("At least one package name must be specified");
2815 return -1;
2816 }
2817 } else {
2818 return shell.handleDefaultCommands(cmd);
2819 }
2820 return 0;
2821 }
2822
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002823 void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2824 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2825 != PackageManager.PERMISSION_GRANTED) {
2826 pw.println("Permission Denial: can't dump DeviceIdleController from from pid="
2827 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2828 + " without permission " + android.Manifest.permission.DUMP);
2829 return;
2830 }
2831
2832 if (args != null) {
Xiaohui Chen7c696362015-09-16 09:56:14 -07002833 int userId = UserHandle.USER_SYSTEM;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002834 for (int i=0; i<args.length; i++) {
2835 String arg = args[i];
2836 if ("-h".equals(arg)) {
2837 dumpHelp(pw);
2838 return;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002839 } else if ("-u".equals(arg)) {
2840 i++;
2841 if (i < args.length) {
2842 arg = args[i];
2843 userId = Integer.parseInt(arg);
2844 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002845 } else if ("-a".equals(arg)) {
2846 // Ignore, we always dump all.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002847 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
2848 pw.println("Unknown option: " + arg);
2849 return;
2850 } else {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002851 Shell shell = new Shell();
2852 shell.userId = userId;
2853 String[] newArgs = new String[args.length-i];
2854 System.arraycopy(args, i, newArgs, 0, args.length-i);
2855 shell.exec(mBinderService, null, fd, null, newArgs, new ResultReceiver(null));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002856 return;
2857 }
2858 }
2859 }
2860
2861 synchronized (this) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002862 mConstants.dump(pw);
2863
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002864 if (mEventCmds[0] != EVENT_NULL) {
2865 pw.println(" Idling history:");
2866 long now = SystemClock.elapsedRealtime();
2867 for (int i=EVENT_BUFFER_SIZE-1; i>=0; i--) {
2868 int cmd = mEventCmds[i];
2869 if (cmd == EVENT_NULL) {
2870 continue;
2871 }
2872 String label;
2873 switch (mEventCmds[i]) {
2874 case EVENT_NORMAL: label = " normal"; break;
2875 case EVENT_LIGHT_IDLE: label = " light-idle"; break;
2876 case EVENT_LIGHT_MAINTENANCE: label = "light-maint"; break;
Dianne Hackbornb6843652016-02-22 12:20:13 -08002877 case EVENT_DEEP_IDLE: label = " deep-idle"; break;
2878 case EVENT_DEEP_MAINTENANCE: label = " deep-maint"; break;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002879 default: label = " ??"; break;
2880 }
2881 pw.print(" ");
2882 pw.print(label);
2883 pw.print(": ");
2884 TimeUtils.formatDuration(mEventTimes[i], now, pw);;
2885 pw.println();
2886 }
2887 }
2888
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002889 int size = mPowerSaveWhitelistAppsExceptIdle.size();
2890 if (size > 0) {
2891 pw.println(" Whitelist (except idle) system apps:");
2892 for (int i = 0; i < size; i++) {
2893 pw.print(" ");
2894 pw.println(mPowerSaveWhitelistAppsExceptIdle.keyAt(i));
2895 }
2896 }
2897 size = mPowerSaveWhitelistApps.size();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002898 if (size > 0) {
2899 pw.println(" Whitelist system apps:");
2900 for (int i = 0; i < size; i++) {
2901 pw.print(" ");
2902 pw.println(mPowerSaveWhitelistApps.keyAt(i));
2903 }
2904 }
2905 size = mPowerSaveWhitelistUserApps.size();
2906 if (size > 0) {
2907 pw.println(" Whitelist user apps:");
2908 for (int i = 0; i < size; i++) {
2909 pw.print(" ");
2910 pw.println(mPowerSaveWhitelistUserApps.keyAt(i));
2911 }
2912 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002913 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2914 if (size > 0) {
2915 pw.println(" Whitelist (except idle) all app ids:");
2916 for (int i = 0; i < size; i++) {
2917 pw.print(" ");
2918 pw.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2919 pw.println();
2920 }
2921 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002922 size = mPowerSaveWhitelistUserAppIds.size();
2923 if (size > 0) {
2924 pw.println(" Whitelist user app ids:");
2925 for (int i = 0; i < size; i++) {
2926 pw.print(" ");
2927 pw.print(mPowerSaveWhitelistUserAppIds.keyAt(i));
2928 pw.println();
2929 }
2930 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002931 size = mPowerSaveWhitelistAllAppIds.size();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002932 if (size > 0) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002933 pw.println(" Whitelist all app ids:");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002934 for (int i = 0; i < size; i++) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002935 pw.print(" ");
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002936 pw.print(mPowerSaveWhitelistAllAppIds.keyAt(i));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002937 pw.println();
2938 }
2939 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002940 size = mTempWhitelistAppIdEndTimes.size();
2941 if (size > 0) {
2942 pw.println(" Temp whitelist schedule:");
2943 final long timeNow = SystemClock.elapsedRealtime();
2944 for (int i = 0; i < size; i++) {
2945 pw.print(" UID=");
2946 pw.print(mTempWhitelistAppIdEndTimes.keyAt(i));
2947 pw.print(": ");
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002948 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.valueAt(i);
2949 TimeUtils.formatDuration(entry.first.value, timeNow, pw);
2950 pw.print(" - ");
2951 pw.println(entry.second);
Dianne Hackborna750a632015-06-16 17:18:23 -07002952 }
2953 }
2954 size = mTempWhitelistAppIdArray != null ? mTempWhitelistAppIdArray.length : 0;
2955 if (size > 0) {
2956 pw.println(" Temp whitelist app ids:");
2957 for (int i = 0; i < size; i++) {
2958 pw.print(" ");
2959 pw.print(mTempWhitelistAppIdArray[i]);
2960 pw.println();
2961 }
2962 }
Adam Lesinski31c05d12015-06-09 17:34:04 -07002963
Dianne Hackbornb6843652016-02-22 12:20:13 -08002964 pw.print(" mLightEnabled="); pw.print(mLightEnabled);
2965 pw.print(" mDeepEnabled="); pw.println(mDeepEnabled);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002966 pw.print(" mForceIdle="); pw.println(mForceIdle);
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002967 pw.print(" mMotionSensor="); pw.println(mMotionSensor);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002968 pw.print(" mCurDisplay="); pw.println(mCurDisplay);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002969 pw.print(" mScreenOn="); pw.println(mScreenOn);
Dianne Hackborn88c41352016-04-07 15:18:58 -07002970 pw.print(" mNetworkConnected="); pw.println(mNetworkConnected);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002971 pw.print(" mCharging="); pw.println(mCharging);
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002972 pw.print(" mMotionActive="); pw.println(mMotionListener.active);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002973 pw.print(" mNotMoving="); pw.println(mNotMoving);
Joe LaPenna23d681b2015-08-27 15:12:11 -07002974 pw.print(" mLocating="); pw.print(mLocating); pw.print(" mHasGps=");
2975 pw.print(mHasGps); pw.print(" mHasNetwork=");
2976 pw.print(mHasNetworkLocation); pw.print(" mLocated="); pw.println(mLocated);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002977 if (mLastGenericLocation != null) {
2978 pw.print(" mLastGenericLocation="); pw.println(mLastGenericLocation);
2979 }
2980 if (mLastGpsLocation != null) {
2981 pw.print(" mLastGpsLocation="); pw.println(mLastGpsLocation);
2982 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002983 pw.print(" mState="); pw.print(stateToString(mState));
2984 pw.print(" mLightState=");
2985 pw.println(lightStateToString(mLightState));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002986 pw.print(" mInactiveTimeout="); TimeUtils.formatDuration(mInactiveTimeout, pw);
2987 pw.println();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002988 if (mActiveIdleOpCount != 0) {
2989 pw.print(" mActiveIdleOpCount="); pw.println(mActiveIdleOpCount);
2990 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002991 if (mNextAlarmTime != 0) {
2992 pw.print(" mNextAlarmTime=");
2993 TimeUtils.formatDuration(mNextAlarmTime, SystemClock.elapsedRealtime(), pw);
2994 pw.println();
2995 }
2996 if (mNextIdlePendingDelay != 0) {
2997 pw.print(" mNextIdlePendingDelay=");
2998 TimeUtils.formatDuration(mNextIdlePendingDelay, pw);
2999 pw.println();
3000 }
3001 if (mNextIdleDelay != 0) {
3002 pw.print(" mNextIdleDelay=");
3003 TimeUtils.formatDuration(mNextIdleDelay, pw);
3004 pw.println();
3005 }
Dianne Hackborn953fc942016-03-29 15:36:24 -07003006 if (mNextLightIdleDelay != 0) {
3007 pw.print(" mNextIdleDelay=");
3008 TimeUtils.formatDuration(mNextLightIdleDelay, pw);
3009 pw.println();
3010 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003011 if (mNextLightAlarmTime != 0) {
3012 pw.print(" mNextLightAlarmTime=");
3013 TimeUtils.formatDuration(mNextLightAlarmTime, SystemClock.elapsedRealtime(), pw);
3014 pw.println();
3015 }
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08003016 if (mCurIdleBudget != 0) {
3017 pw.print(" mCurIdleBudget=");
3018 TimeUtils.formatDuration(mCurIdleBudget, pw);
3019 pw.println();
3020 }
3021 if (mMaintenanceStartTime != 0) {
3022 pw.print(" mMaintenanceStartTime=");
3023 TimeUtils.formatDuration(mMaintenanceStartTime, SystemClock.elapsedRealtime(), pw);
3024 pw.println();
3025 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003026 if (mJobsActive) {
3027 pw.print(" mJobsActive="); pw.println(mJobsActive);
3028 }
3029 if (mAlarmsActive) {
3030 pw.print(" mAlarmsActive="); pw.println(mAlarmsActive);
3031 }
3032 if (mDownloadServiceActive != null) {
3033 pw.print(" mDownloadServiceActive="); pw.println(mDownloadServiceActive);
3034 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003035 }
3036 }
3037}