blob: 488f0e793c9a8d68b579955752f87aa3592911e3 [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 boolean mJobsActive;
216 private boolean mAlarmsActive;
Yao Chenca5edbb2016-01-13 14:44:36 -0800217 private boolean mReportedMaintenanceActivity;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800218
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700219 public final AtomicFile mConfigFile;
220
Yao Chenca5edbb2016-01-13 14:44:36 -0800221 private final RemoteCallbackList<IMaintenanceActivityListener> mMaintenanceActivityListeners =
222 new RemoteCallbackList<IMaintenanceActivityListener>();
223
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700224 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700225 * Package names the system has white-listed to opt out of power save restrictions,
226 * except for device idle mode.
227 */
228 private final ArrayMap<String, Integer> mPowerSaveWhitelistAppsExceptIdle = new ArrayMap<>();
229
230 /**
231 * Package names the system has white-listed to opt out of power save restrictions for
232 * all modes.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700233 */
234 private final ArrayMap<String, Integer> mPowerSaveWhitelistApps = new ArrayMap<>();
235
236 /**
237 * Package names the user has white-listed to opt out of power save restrictions.
238 */
239 private final ArrayMap<String, Integer> mPowerSaveWhitelistUserApps = new ArrayMap<>();
240
241 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700242 * App IDs of built-in system apps that have been white-listed except for idle modes.
243 */
244 private final SparseBooleanArray mPowerSaveWhitelistSystemAppIdsExceptIdle
245 = new SparseBooleanArray();
246
247 /**
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700248 * App IDs of built-in system apps that have been white-listed.
249 */
250 private final SparseBooleanArray mPowerSaveWhitelistSystemAppIds = new SparseBooleanArray();
251
252 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700253 * App IDs that have been white-listed to opt out of power save restrictions, except
254 * for device idle modes.
255 */
256 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
257
258 /**
259 * Current app IDs that are in the complete power save white list, but shouldn't be
260 * excluded from idle modes. This array can be shared with others because it will not be
261 * modified once set.
262 */
263 private int[] mPowerSaveWhitelistExceptIdleAppIdArray = new int[0];
264
265 /**
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700266 * App IDs that have been white-listed to opt out of power save restrictions.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700267 */
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700268 private final SparseBooleanArray mPowerSaveWhitelistAllAppIds = new SparseBooleanArray();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700269
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700270 /**
271 * Current app IDs that are in the complete power save white list. This array can
272 * be shared with others because it will not be modified once set.
273 */
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700274 private int[] mPowerSaveWhitelistAllAppIdArray = new int[0];
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700275
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700276 /**
Dianne Hackborn262ae5c2016-02-10 16:28:29 -0800277 * App IDs that have been white-listed by the user to opt out of power save restrictions.
278 */
279 private final SparseBooleanArray mPowerSaveWhitelistUserAppIds = new SparseBooleanArray();
280
281 /**
282 * Current app IDs that are in the user power save white list. This array can
283 * be shared with others because it will not be modified once set.
284 */
285 private int[] mPowerSaveWhitelistUserAppIdArray = new int[0];
286
287 /**
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700288 * List of end times for UIDs that are temporarily marked as being allowed to access
289 * the network and acquire wakelocks. Times are in milliseconds.
290 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700291 private final SparseArray<Pair<MutableLong, String>> mTempWhitelistAppIdEndTimes
292 = new SparseArray<>();
293
294 /**
295 * Callback to the NetworkPolicyManagerService to tell it that the temp whitelist has changed.
296 */
297 Runnable mNetworkPolicyTempWhitelistCallback;
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700298
299 /**
300 * Current app IDs of temporarily whitelist apps for high-priority messages.
301 */
302 private int[] mTempWhitelistAppIdArray = new int[0];
303
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800304 private static final int EVENT_NULL = 0;
305 private static final int EVENT_NORMAL = 1;
306 private static final int EVENT_LIGHT_IDLE = 2;
307 private static final int EVENT_LIGHT_MAINTENANCE = 3;
Dianne Hackbornb6843652016-02-22 12:20:13 -0800308 private static final int EVENT_DEEP_IDLE = 4;
309 private static final int EVENT_DEEP_MAINTENANCE = 5;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800310
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -0700311 private final int[] mEventCmds = new int[EVENT_BUFFER_SIZE];
312 private final long[] mEventTimes = new long[EVENT_BUFFER_SIZE];
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800313
314 private void addEvent(int cmd) {
315 if (mEventCmds[0] != cmd) {
316 System.arraycopy(mEventCmds, 0, mEventCmds, 1, EVENT_BUFFER_SIZE - 1);
317 System.arraycopy(mEventTimes, 0, mEventTimes, 1, EVENT_BUFFER_SIZE - 1);
318 mEventCmds[0] = cmd;
319 mEventTimes[0] = SystemClock.elapsedRealtime();
320 }
321 }
322
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700323 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
324 @Override public void onReceive(Context context, Intent intent) {
Dianne Hackborn88c41352016-04-07 15:18:58 -0700325 switch (intent.getAction()) {
326 case ConnectivityManager.CONNECTIVITY_ACTION: {
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -0700327 updateConnectivityState(intent);
Dianne Hackborn88c41352016-04-07 15:18:58 -0700328 } break;
329 case Intent.ACTION_BATTERY_CHANGED: {
330 synchronized (DeviceIdleController.this) {
331 int plugged = intent.getIntExtra("plugged", 0);
332 updateChargingLocked(plugged != 0);
333 }
334 } break;
335 case Intent.ACTION_PACKAGE_REMOVED: {
336 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
337 Uri data = intent.getData();
338 String ssp;
339 if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
340 removePowerSaveWhitelistAppInternal(ssp);
341 }
342 }
343 } break;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700344 }
345 }
346 };
347
348 private final AlarmManager.OnAlarmListener mLightAlarmListener
349 = new AlarmManager.OnAlarmListener() {
350 @Override
351 public void onAlarm() {
352 synchronized (DeviceIdleController.this) {
353 stepLightIdleStateLocked("s:alarm");
354 }
355 }
356 };
357
Kevin Gabayan92f15e62016-04-04 17:52:22 -0700358 private final AlarmManager.OnAlarmListener mSensingTimeoutAlarmListener
359 = new AlarmManager.OnAlarmListener() {
360 @Override
361 public void onAlarm() {
362 if (mState == STATE_SENSING) {
363 synchronized (DeviceIdleController.this) {
364 becomeInactiveIfAppropriateLocked();
365 }
366 }
367 }
368 };
369
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700370 private final AlarmManager.OnAlarmListener mDeepAlarmListener
371 = new AlarmManager.OnAlarmListener() {
372 @Override
373 public void onAlarm() {
374 synchronized (DeviceIdleController.this) {
375 stepIdleStateLocked("s:alarm");
376 }
377 }
378 };
379
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800380 private final BroadcastReceiver mIdleStartedDoneReceiver = new BroadcastReceiver() {
381 @Override public void onReceive(Context context, Intent intent) {
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700382 // When coming out of a deep idle, we will add in some delay before we allow
383 // the system to settle down and finish the maintenance window. This is
384 // to give a chance for any pending work to be scheduled.
385 if (PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED.equals(intent.getAction())) {
386 mHandler.sendEmptyMessageDelayed(MSG_FINISH_IDLE_OP,
387 mConstants.MIN_DEEP_MAINTENANCE_TIME);
388 } else {
389 mHandler.sendEmptyMessageDelayed(MSG_FINISH_IDLE_OP,
390 mConstants.MIN_LIGHT_MAINTENANCE_TIME);
391 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800392 }
393 };
394
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700395 private final DisplayManager.DisplayListener mDisplayListener
396 = new DisplayManager.DisplayListener() {
397 @Override public void onDisplayAdded(int displayId) {
398 }
399
400 @Override public void onDisplayRemoved(int displayId) {
401 }
402
403 @Override public void onDisplayChanged(int displayId) {
404 if (displayId == Display.DEFAULT_DISPLAY) {
405 synchronized (DeviceIdleController.this) {
406 updateDisplayLocked();
407 }
408 }
409 }
410 };
411
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700412 private final class MotionListener extends TriggerEventListener
413 implements SensorEventListener {
414
415 boolean active = false;
416
417 @Override
418 public void onTrigger(TriggerEvent event) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700419 synchronized (DeviceIdleController.this) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700420 active = false;
421 motionLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700422 }
423 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700424
425 @Override
426 public void onSensorChanged(SensorEvent event) {
427 synchronized (DeviceIdleController.this) {
428 mSensorManager.unregisterListener(this, mMotionSensor);
429 active = false;
430 motionLocked();
431 }
432 }
433
434 @Override
435 public void onAccuracyChanged(Sensor sensor, int accuracy) {}
436
437 public boolean registerLocked() {
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700438 boolean success;
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700439 if (mMotionSensor.getReportingMode() == Sensor.REPORTING_MODE_ONE_SHOT) {
440 success = mSensorManager.requestTriggerSensor(mMotionListener, mMotionSensor);
441 } else {
442 success = mSensorManager.registerListener(
443 mMotionListener, mMotionSensor, SensorManager.SENSOR_DELAY_NORMAL);
444 }
445 if (success) {
446 active = true;
447 } else {
448 Slog.e(TAG, "Unable to register for " + mMotionSensor);
449 }
450 return success;
451 }
452
453 public void unregisterLocked() {
454 if (mMotionSensor.getReportingMode() == Sensor.REPORTING_MODE_ONE_SHOT) {
455 mSensorManager.cancelTriggerSensor(mMotionListener, mMotionSensor);
456 } else {
457 mSensorManager.unregisterListener(mMotionListener);
458 }
459 active = false;
460 }
461 }
462 private final MotionListener mMotionListener = new MotionListener();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700463
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700464 private final LocationListener mGenericLocationListener = new LocationListener() {
465 @Override
466 public void onLocationChanged(Location location) {
467 synchronized (DeviceIdleController.this) {
468 receivedGenericLocationLocked(location);
469 }
470 }
471
472 @Override
473 public void onStatusChanged(String provider, int status, Bundle extras) {
474 }
475
476 @Override
477 public void onProviderEnabled(String provider) {
478 }
479
480 @Override
481 public void onProviderDisabled(String provider) {
482 }
483 };
484
485 private final LocationListener mGpsLocationListener = new LocationListener() {
486 @Override
487 public void onLocationChanged(Location location) {
488 synchronized (DeviceIdleController.this) {
489 receivedGpsLocationLocked(location);
490 }
491 }
492
493 @Override
494 public void onStatusChanged(String provider, int status, Bundle extras) {
495 }
496
497 @Override
498 public void onProviderEnabled(String provider) {
499 }
500
501 @Override
502 public void onProviderDisabled(String provider) {
503 }
504 };
505
Adam Lesinski31c05d12015-06-09 17:34:04 -0700506 /**
507 * All times are in milliseconds. These constants are kept synchronized with the system
508 * global Settings. Any access to this class or its fields should be done while
509 * holding the DeviceIdleController lock.
510 */
Dianne Hackborna750a632015-06-16 17:18:23 -0700511 private final class Constants extends ContentObserver {
Adam Lesinski31c05d12015-06-09 17:34:04 -0700512 // Key names stored in the settings value.
Dianne Hackborn953fc942016-03-29 15:36:24 -0700513 private static final String KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT
514 = "light_after_inactive_to";
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700515 private static final String KEY_LIGHT_PRE_IDLE_TIMEOUT = "light_pre_idle_to";
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700516 private static final String KEY_LIGHT_IDLE_TIMEOUT = "light_idle_to";
Dianne Hackborn953fc942016-03-29 15:36:24 -0700517 private static final String KEY_LIGHT_IDLE_FACTOR = "light_idle_factor";
518 private static final String KEY_LIGHT_MAX_IDLE_TIMEOUT = "light_max_idle_to";
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800519 private static final String KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET
520 = "light_idle_maintenance_min_budget";
521 private static final String KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET
522 = "light_idle_maintenance_max_budget";
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700523 private static final String KEY_MIN_LIGHT_MAINTENANCE_TIME = "min_light_maintenance_time";
524 private static final String KEY_MIN_DEEP_MAINTENANCE_TIME = "min_deep_maintenance_time";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700525 private static final String KEY_INACTIVE_TIMEOUT = "inactive_to";
526 private static final String KEY_SENSING_TIMEOUT = "sensing_to";
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700527 private static final String KEY_LOCATING_TIMEOUT = "locating_to";
528 private static final String KEY_LOCATION_ACCURACY = "location_accuracy";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700529 private static final String KEY_MOTION_INACTIVE_TIMEOUT = "motion_inactive_to";
530 private static final String KEY_IDLE_AFTER_INACTIVE_TIMEOUT = "idle_after_inactive_to";
531 private static final String KEY_IDLE_PENDING_TIMEOUT = "idle_pending_to";
532 private static final String KEY_MAX_IDLE_PENDING_TIMEOUT = "max_idle_pending_to";
533 private static final String KEY_IDLE_PENDING_FACTOR = "idle_pending_factor";
534 private static final String KEY_IDLE_TIMEOUT = "idle_to";
535 private static final String KEY_MAX_IDLE_TIMEOUT = "max_idle_to";
536 private static final String KEY_IDLE_FACTOR = "idle_factor";
537 private static final String KEY_MIN_TIME_TO_ALARM = "min_time_to_alarm";
538 private static final String KEY_MAX_TEMP_APP_WHITELIST_DURATION =
539 "max_temp_app_whitelist_duration";
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700540 private static final String KEY_MMS_TEMP_APP_WHITELIST_DURATION =
541 "mms_temp_app_whitelist_duration";
Dianne Hackborn451c3462015-07-21 17:39:46 -0700542 private static final String KEY_SMS_TEMP_APP_WHITELIST_DURATION =
543 "sms_temp_app_whitelist_duration";
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700544 private static final String KEY_NOTIFICATION_WHITELIST_DURATION =
545 "notification_whitelist_duration";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700546
547 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700548 * This is the time, after becoming inactive, that we go in to the first
549 * light-weight idle mode.
550 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
551 * @see #KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT
552 */
553 public long LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT;
554
555 /**
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700556 * This is amount of time we will wait from the point where we decide we would
557 * like to go idle until we actually do, while waiting for jobs and other current
558 * activity to finish.
559 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
560 * @see #KEY_LIGHT_PRE_IDLE_TIMEOUT
561 */
562 public long LIGHT_PRE_IDLE_TIMEOUT;
563
564 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700565 * This is the initial time that we will run in idle maintenance mode.
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700566 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
567 * @see #KEY_LIGHT_IDLE_TIMEOUT
568 */
569 public long LIGHT_IDLE_TIMEOUT;
570
571 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700572 * Scaling factor to apply to the light idle mode time each time we complete a cycle.
573 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
574 * @see #KEY_LIGHT_IDLE_FACTOR
575 */
576 public float LIGHT_IDLE_FACTOR;
577
578 /**
579 * This is the maximum time we will run in idle maintenence mode.
580 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
581 * @see #KEY_LIGHT_MAX_IDLE_TIMEOUT
582 */
583 public long LIGHT_MAX_IDLE_TIMEOUT;
584
585 /**
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800586 * This is the minimum amount of time we want to make available for maintenance mode
587 * when lightly idling. That is, we will always have at least this amount of time
588 * available maintenance before timing out and cutting off maintenance mode.
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700589 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800590 * @see #KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700591 */
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800592 public long LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
593
594 /**
595 * This is the maximum amount of time we want to make available for maintenance mode
596 * when lightly idling. That is, if the system isn't using up its minimum maintenance
597 * budget and this time is being added to the budget reserve, this is the maximum
598 * reserve size we will allow to grow and thus the maximum amount of time we will
599 * allow for the maintenance window.
600 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
601 * @see #KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET
602 */
603 public long LIGHT_IDLE_MAINTENANCE_MAX_BUDGET;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700604
605 /**
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700606 * This is the minimum amount of time that we will stay in maintenance mode after
607 * a light doze. We have this minimum to allow various things to respond to switching
608 * in to maintenance mode and scheduling their work -- otherwise we may
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700609 * see there is nothing to do (no jobs pending) and go out of maintenance
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700610 * mode immediately.
611 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
612 * @see #KEY_MIN_LIGHT_MAINTENANCE_TIME
613 */
614 public long MIN_LIGHT_MAINTENANCE_TIME;
615
616 /**
617 * This is the minimum amount of time that we will stay in maintenance mode after
618 * a full doze. We have this minimum to allow various things to respond to switching
619 * in to maintenance mode and scheduling their work -- otherwise we may
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700620 * see there is nothing to do (no jobs pending) and go out of maintenance
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700621 * mode immediately.
622 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
623 * @see #KEY_MIN_DEEP_MAINTENANCE_TIME
624 */
625 public long MIN_DEEP_MAINTENANCE_TIME;
626
627 /**
Adam Lesinski31c05d12015-06-09 17:34:04 -0700628 * This is the time, after becoming inactive, at which we start looking at the
629 * motion sensor to determine if the device is being left alone. We don't do this
630 * immediately after going inactive just because we don't want to be continually running
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700631 * the motion sensor whenever the screen is off.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700632 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
633 * @see #KEY_INACTIVE_TIMEOUT
634 */
635 public long INACTIVE_TIMEOUT;
636
637 /**
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700638 * If we don't receive a callback from AnyMotion in this amount of time +
639 * {@link #LOCATING_TIMEOUT}, we will change from
Adam Lesinski31c05d12015-06-09 17:34:04 -0700640 * STATE_SENSING to STATE_INACTIVE, and any AnyMotion callbacks while not in STATE_SENSING
641 * will be ignored.
642 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
643 * @see #KEY_SENSING_TIMEOUT
644 */
645 public long SENSING_TIMEOUT;
646
647 /**
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700648 * This is how long we will wait to try to get a good location fix before going in to
649 * idle mode.
650 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
651 * @see #KEY_LOCATING_TIMEOUT
652 */
653 public long LOCATING_TIMEOUT;
654
655 /**
656 * The desired maximum accuracy (in meters) we consider the location to be good enough to go
657 * on to idle. We will be trying to get an accuracy fix at least this good or until
658 * {@link #LOCATING_TIMEOUT} expires.
659 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
660 * @see #KEY_LOCATION_ACCURACY
661 */
662 public float LOCATION_ACCURACY;
663
664 /**
Adam Lesinski31c05d12015-06-09 17:34:04 -0700665 * This is the time, after seeing motion, that we wait after becoming inactive from
666 * that until we start looking for motion again.
667 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
668 * @see #KEY_MOTION_INACTIVE_TIMEOUT
669 */
670 public long MOTION_INACTIVE_TIMEOUT;
671
672 /**
673 * This is the time, after the inactive timeout elapses, that we will wait looking
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700674 * for motion until we truly consider the device to be idle.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700675 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
676 * @see #KEY_IDLE_AFTER_INACTIVE_TIMEOUT
677 */
678 public long IDLE_AFTER_INACTIVE_TIMEOUT;
679
680 /**
681 * This is the initial time, after being idle, that we will allow ourself to be back
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700682 * in the IDLE_MAINTENANCE state allowing the system to run normally until we return to
683 * idle.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700684 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
685 * @see #KEY_IDLE_PENDING_TIMEOUT
686 */
687 public long IDLE_PENDING_TIMEOUT;
688
689 /**
690 * Maximum pending idle timeout (time spent running) we will be allowed to use.
691 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
692 * @see #KEY_MAX_IDLE_PENDING_TIMEOUT
693 */
694 public long MAX_IDLE_PENDING_TIMEOUT;
695
696 /**
697 * Scaling factor to apply to current pending idle timeout each time we cycle through
698 * that state.
699 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
700 * @see #KEY_IDLE_PENDING_FACTOR
701 */
702 public float IDLE_PENDING_FACTOR;
703
704 /**
705 * This is the initial time that we want to sit in the idle state before waking up
706 * again to return to pending idle and allowing normal work to run.
707 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
708 * @see #KEY_IDLE_TIMEOUT
709 */
710 public long IDLE_TIMEOUT;
711
712 /**
713 * Maximum idle duration we will be allowed to use.
714 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
715 * @see #KEY_MAX_IDLE_TIMEOUT
716 */
717 public long MAX_IDLE_TIMEOUT;
718
719 /**
720 * Scaling factor to apply to current idle timeout each time we cycle through that state.
721 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
722 * @see #KEY_IDLE_FACTOR
723 */
724 public float IDLE_FACTOR;
725
726 /**
727 * This is the minimum time we will allow until the next upcoming alarm for us to
728 * actually go in to idle mode.
729 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
730 * @see #KEY_MIN_TIME_TO_ALARM
731 */
732 public long MIN_TIME_TO_ALARM;
733
734 /**
735 * Max amount of time to temporarily whitelist an app when it receives a high priority
736 * tickle.
737 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
738 * @see #KEY_MAX_TEMP_APP_WHITELIST_DURATION
739 */
740 public long MAX_TEMP_APP_WHITELIST_DURATION;
741
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700742 /**
743 * Amount of time we would like to whitelist an app that is receiving an MMS.
744 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
745 * @see #KEY_MMS_TEMP_APP_WHITELIST_DURATION
746 */
747 public long MMS_TEMP_APP_WHITELIST_DURATION;
748
Dianne Hackborn451c3462015-07-21 17:39:46 -0700749 /**
750 * Amount of time we would like to whitelist an app that is receiving an SMS.
751 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
752 * @see #KEY_SMS_TEMP_APP_WHITELIST_DURATION
753 */
754 public long SMS_TEMP_APP_WHITELIST_DURATION;
755
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700756 /**
757 * Amount of time we would like to whitelist an app that is handling a
758 * {@link android.app.PendingIntent} triggered by a {@link android.app.Notification}.
759 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
760 * @see #KEY_NOTIFICATION_WHITELIST_DURATION
761 */
762 public long NOTIFICATION_WHITELIST_DURATION;
763
Adam Lesinski31c05d12015-06-09 17:34:04 -0700764 private final ContentResolver mResolver;
Joe LaPennaf33b5bf2016-03-23 15:19:47 -0700765 private final boolean mHasWatch;
Adam Lesinski31c05d12015-06-09 17:34:04 -0700766 private final KeyValueListParser mParser = new KeyValueListParser(',');
767
768 public Constants(Handler handler, ContentResolver resolver) {
769 super(handler);
770 mResolver = resolver;
Joe LaPennaf33b5bf2016-03-23 15:19:47 -0700771 mHasWatch = getContext().getPackageManager().hasSystemFeature(
772 PackageManager.FEATURE_WATCH);
773 mResolver.registerContentObserver(Settings.Global.getUriFor(
774 mHasWatch ? Settings.Global.DEVICE_IDLE_CONSTANTS_WATCH
775 : Settings.Global.DEVICE_IDLE_CONSTANTS),
776 false, this);
Adam Lesinski31c05d12015-06-09 17:34:04 -0700777 updateConstants();
778 }
779
780 @Override
781 public void onChange(boolean selfChange, Uri uri) {
782 updateConstants();
783 }
784
785 private void updateConstants() {
786 synchronized (DeviceIdleController.this) {
787 try {
788 mParser.setString(Settings.Global.getString(mResolver,
Joe LaPennaf33b5bf2016-03-23 15:19:47 -0700789 mHasWatch ? Settings.Global.DEVICE_IDLE_CONSTANTS_WATCH
790 : Settings.Global.DEVICE_IDLE_CONSTANTS));
Adam Lesinski31c05d12015-06-09 17:34:04 -0700791 } catch (IllegalArgumentException e) {
792 // Failed to parse the settings string, log this and move on
793 // with defaults.
794 Slog.e(TAG, "Bad device idle settings", e);
795 }
796
Dianne Hackborn953fc942016-03-29 15:36:24 -0700797 LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT = mParser.getLong(
798 KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT,
799 !COMPRESS_TIME ? 5 * 60 * 1000L : 15 * 1000L);
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700800 LIGHT_PRE_IDLE_TIMEOUT = mParser.getLong(KEY_LIGHT_PRE_IDLE_TIMEOUT,
801 !COMPRESS_TIME ? 10 * 60 * 1000L : 30 * 1000L);
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700802 LIGHT_IDLE_TIMEOUT = mParser.getLong(KEY_LIGHT_IDLE_TIMEOUT,
Dianne Hackborn953fc942016-03-29 15:36:24 -0700803 !COMPRESS_TIME ? 5 * 60 * 1000L : 15 * 1000L);
804 LIGHT_IDLE_FACTOR = mParser.getFloat(KEY_LIGHT_IDLE_FACTOR,
805 2f);
806 LIGHT_MAX_IDLE_TIMEOUT = mParser.getLong(KEY_LIGHT_MAX_IDLE_TIMEOUT,
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700807 !COMPRESS_TIME ? 15 * 60 * 1000L : 60 * 1000L);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800808 LIGHT_IDLE_MAINTENANCE_MIN_BUDGET = mParser.getLong(
809 KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET,
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700810 !COMPRESS_TIME ? 1 * 60 * 1000L : 15 * 1000L);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800811 LIGHT_IDLE_MAINTENANCE_MAX_BUDGET = mParser.getLong(
812 KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET,
813 !COMPRESS_TIME ? 5 * 60 * 1000L : 30 * 1000L);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700814 MIN_LIGHT_MAINTENANCE_TIME = mParser.getLong(
815 KEY_MIN_LIGHT_MAINTENANCE_TIME,
816 !COMPRESS_TIME ? 5 * 1000L : 1 * 1000L);
817 MIN_DEEP_MAINTENANCE_TIME = mParser.getLong(
818 KEY_MIN_DEEP_MAINTENANCE_TIME,
819 !COMPRESS_TIME ? 30 * 1000L : 5 * 1000L);
Joe LaPenna0c5d3e92016-03-24 13:29:56 -0700820 long inactiveTimeoutDefault = (mHasWatch ? 15 : 30) * 60 * 1000L;
Adam Lesinski31c05d12015-06-09 17:34:04 -0700821 INACTIVE_TIMEOUT = mParser.getLong(KEY_INACTIVE_TIMEOUT,
Joe LaPenna0c5d3e92016-03-24 13:29:56 -0700822 !COMPRESS_TIME ? inactiveTimeoutDefault : (inactiveTimeoutDefault / 10));
Adam Lesinski31c05d12015-06-09 17:34:04 -0700823 SENSING_TIMEOUT = mParser.getLong(KEY_SENSING_TIMEOUT,
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700824 !DEBUG ? 4 * 60 * 1000L : 60 * 1000L);
825 LOCATING_TIMEOUT = mParser.getLong(KEY_LOCATING_TIMEOUT,
826 !DEBUG ? 30 * 1000L : 15 * 1000L);
827 LOCATION_ACCURACY = mParser.getFloat(KEY_LOCATION_ACCURACY, 20);
Adam Lesinski31c05d12015-06-09 17:34:04 -0700828 MOTION_INACTIVE_TIMEOUT = mParser.getLong(KEY_MOTION_INACTIVE_TIMEOUT,
829 !COMPRESS_TIME ? 10 * 60 * 1000L : 60 * 1000L);
Joe LaPenna0c5d3e92016-03-24 13:29:56 -0700830 long idleAfterInactiveTimeout = (mHasWatch ? 15 : 30) * 60 * 1000L;
Adam Lesinski31c05d12015-06-09 17:34:04 -0700831 IDLE_AFTER_INACTIVE_TIMEOUT = mParser.getLong(KEY_IDLE_AFTER_INACTIVE_TIMEOUT,
Joe LaPenna0c5d3e92016-03-24 13:29:56 -0700832 !COMPRESS_TIME ? idleAfterInactiveTimeout
833 : (idleAfterInactiveTimeout / 10));
Adam Lesinski31c05d12015-06-09 17:34:04 -0700834 IDLE_PENDING_TIMEOUT = mParser.getLong(KEY_IDLE_PENDING_TIMEOUT,
835 !COMPRESS_TIME ? 5 * 60 * 1000L : 30 * 1000L);
836 MAX_IDLE_PENDING_TIMEOUT = mParser.getLong(KEY_MAX_IDLE_PENDING_TIMEOUT,
837 !COMPRESS_TIME ? 10 * 60 * 1000L : 60 * 1000L);
838 IDLE_PENDING_FACTOR = mParser.getFloat(KEY_IDLE_PENDING_FACTOR,
839 2f);
840 IDLE_TIMEOUT = mParser.getLong(KEY_IDLE_TIMEOUT,
841 !COMPRESS_TIME ? 60 * 60 * 1000L : 6 * 60 * 1000L);
842 MAX_IDLE_TIMEOUT = mParser.getLong(KEY_MAX_IDLE_TIMEOUT,
843 !COMPRESS_TIME ? 6 * 60 * 60 * 1000L : 30 * 60 * 1000L);
844 IDLE_FACTOR = mParser.getFloat(KEY_IDLE_FACTOR,
845 2f);
846 MIN_TIME_TO_ALARM = mParser.getLong(KEY_MIN_TIME_TO_ALARM,
847 !COMPRESS_TIME ? 60 * 60 * 1000L : 6 * 60 * 1000L);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700848 MAX_TEMP_APP_WHITELIST_DURATION = mParser.getLong(
849 KEY_MAX_TEMP_APP_WHITELIST_DURATION, 5 * 60 * 1000L);
850 MMS_TEMP_APP_WHITELIST_DURATION = mParser.getLong(
Dianne Hackborn0b6134b2015-07-14 18:48:07 -0700851 KEY_MMS_TEMP_APP_WHITELIST_DURATION, 60 * 1000L);
Dianne Hackborn451c3462015-07-21 17:39:46 -0700852 SMS_TEMP_APP_WHITELIST_DURATION = mParser.getLong(
853 KEY_SMS_TEMP_APP_WHITELIST_DURATION, 20 * 1000L);
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700854 NOTIFICATION_WHITELIST_DURATION = mParser.getLong(
855 KEY_NOTIFICATION_WHITELIST_DURATION, 30 * 1000L);
Adam Lesinski31c05d12015-06-09 17:34:04 -0700856 }
857 }
858
859 void dump(PrintWriter pw) {
860 pw.println(" Settings:");
861
Dianne Hackborn953fc942016-03-29 15:36:24 -0700862 pw.print(" "); pw.print(KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT); pw.print("=");
863 TimeUtils.formatDuration(LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT, pw);
864 pw.println();
865
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700866 pw.print(" "); pw.print(KEY_LIGHT_PRE_IDLE_TIMEOUT); pw.print("=");
867 TimeUtils.formatDuration(LIGHT_PRE_IDLE_TIMEOUT, pw);
868 pw.println();
869
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700870 pw.print(" "); pw.print(KEY_LIGHT_IDLE_TIMEOUT); pw.print("=");
871 TimeUtils.formatDuration(LIGHT_IDLE_TIMEOUT, pw);
872 pw.println();
873
Dianne Hackborn953fc942016-03-29 15:36:24 -0700874 pw.print(" "); pw.print(KEY_LIGHT_IDLE_FACTOR); pw.print("=");
875 pw.print(LIGHT_IDLE_FACTOR);
876 pw.println();
877
878 pw.print(" "); pw.print(KEY_LIGHT_MAX_IDLE_TIMEOUT); pw.print("=");
879 TimeUtils.formatDuration(LIGHT_MAX_IDLE_TIMEOUT, pw);
880 pw.println();
881
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800882 pw.print(" "); pw.print(KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET); pw.print("=");
883 TimeUtils.formatDuration(LIGHT_IDLE_MAINTENANCE_MIN_BUDGET, pw);
884 pw.println();
885
886 pw.print(" "); pw.print(KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET); pw.print("=");
887 TimeUtils.formatDuration(LIGHT_IDLE_MAINTENANCE_MAX_BUDGET, pw);
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700888 pw.println();
889
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700890 pw.print(" "); pw.print(KEY_MIN_LIGHT_MAINTENANCE_TIME); pw.print("=");
891 TimeUtils.formatDuration(MIN_LIGHT_MAINTENANCE_TIME, pw);
892 pw.println();
893
894 pw.print(" "); pw.print(KEY_MIN_DEEP_MAINTENANCE_TIME); pw.print("=");
895 TimeUtils.formatDuration(MIN_DEEP_MAINTENANCE_TIME, pw);
896 pw.println();
897
Dianne Hackborna750a632015-06-16 17:18:23 -0700898 pw.print(" "); pw.print(KEY_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700899 TimeUtils.formatDuration(INACTIVE_TIMEOUT, pw);
900 pw.println();
901
Dianne Hackborna750a632015-06-16 17:18:23 -0700902 pw.print(" "); pw.print(KEY_SENSING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700903 TimeUtils.formatDuration(SENSING_TIMEOUT, pw);
904 pw.println();
905
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700906 pw.print(" "); pw.print(KEY_LOCATING_TIMEOUT); pw.print("=");
907 TimeUtils.formatDuration(LOCATING_TIMEOUT, pw);
908 pw.println();
909
910 pw.print(" "); pw.print(KEY_LOCATION_ACCURACY); pw.print("=");
911 pw.print(LOCATION_ACCURACY); pw.print("m");
912 pw.println();
913
Dianne Hackborna750a632015-06-16 17:18:23 -0700914 pw.print(" "); pw.print(KEY_MOTION_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700915 TimeUtils.formatDuration(MOTION_INACTIVE_TIMEOUT, pw);
916 pw.println();
917
Dianne Hackborna750a632015-06-16 17:18:23 -0700918 pw.print(" "); pw.print(KEY_IDLE_AFTER_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700919 TimeUtils.formatDuration(IDLE_AFTER_INACTIVE_TIMEOUT, pw);
920 pw.println();
921
Dianne Hackborna750a632015-06-16 17:18:23 -0700922 pw.print(" "); pw.print(KEY_IDLE_PENDING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700923 TimeUtils.formatDuration(IDLE_PENDING_TIMEOUT, pw);
924 pw.println();
925
Dianne Hackborna750a632015-06-16 17:18:23 -0700926 pw.print(" "); pw.print(KEY_MAX_IDLE_PENDING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700927 TimeUtils.formatDuration(MAX_IDLE_PENDING_TIMEOUT, pw);
928 pw.println();
929
Dianne Hackborna750a632015-06-16 17:18:23 -0700930 pw.print(" "); pw.print(KEY_IDLE_PENDING_FACTOR); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700931 pw.println(IDLE_PENDING_FACTOR);
932
Dianne Hackborna750a632015-06-16 17:18:23 -0700933 pw.print(" "); pw.print(KEY_IDLE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700934 TimeUtils.formatDuration(IDLE_TIMEOUT, pw);
935 pw.println();
936
Dianne Hackborna750a632015-06-16 17:18:23 -0700937 pw.print(" "); pw.print(KEY_MAX_IDLE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700938 TimeUtils.formatDuration(MAX_IDLE_TIMEOUT, pw);
939 pw.println();
940
Dianne Hackborna750a632015-06-16 17:18:23 -0700941 pw.print(" "); pw.print(KEY_IDLE_FACTOR); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700942 pw.println(IDLE_FACTOR);
943
Dianne Hackborna750a632015-06-16 17:18:23 -0700944 pw.print(" "); pw.print(KEY_MIN_TIME_TO_ALARM); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700945 TimeUtils.formatDuration(MIN_TIME_TO_ALARM, pw);
946 pw.println();
947
Dianne Hackborna750a632015-06-16 17:18:23 -0700948 pw.print(" "); pw.print(KEY_MAX_TEMP_APP_WHITELIST_DURATION); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700949 TimeUtils.formatDuration(MAX_TEMP_APP_WHITELIST_DURATION, pw);
950 pw.println();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700951
952 pw.print(" "); pw.print(KEY_MMS_TEMP_APP_WHITELIST_DURATION); pw.print("=");
953 TimeUtils.formatDuration(MMS_TEMP_APP_WHITELIST_DURATION, pw);
954 pw.println();
Dianne Hackborn451c3462015-07-21 17:39:46 -0700955
956 pw.print(" "); pw.print(KEY_SMS_TEMP_APP_WHITELIST_DURATION); pw.print("=");
957 TimeUtils.formatDuration(SMS_TEMP_APP_WHITELIST_DURATION, pw);
958 pw.println();
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700959
960 pw.print(" "); pw.print(KEY_NOTIFICATION_WHITELIST_DURATION); pw.print("=");
961 TimeUtils.formatDuration(NOTIFICATION_WHITELIST_DURATION, pw);
962 pw.println();
Adam Lesinski31c05d12015-06-09 17:34:04 -0700963 }
964 }
965
966 private Constants mConstants;
967
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700968 @Override
969 public void onAnyMotionResult(int result) {
970 if (DEBUG) Slog.d(TAG, "onAnyMotionResult(" + result + ")");
Kevin Gabayan92f15e62016-04-04 17:52:22 -0700971 if (result != AnyMotionDetector.RESULT_UNKNOWN) {
972 synchronized (this) {
973 cancelSensingTimeoutAlarmLocked();
974 }
975 }
Kevin Gabayandcf47012016-07-08 10:41:24 -0700976 if ((result == AnyMotionDetector.RESULT_MOVED) ||
977 (result == AnyMotionDetector.RESULT_UNKNOWN)) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700978 synchronized (this) {
Kevin Gabayandcf47012016-07-08 10:41:24 -0700979 handleMotionDetectedLocked(mConstants.INACTIVE_TIMEOUT, "non_stationary");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700980 }
981 } else if (result == AnyMotionDetector.RESULT_STATIONARY) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700982 if (mState == STATE_SENSING) {
983 // If we are currently sensing, it is time to move to locating.
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700984 synchronized (this) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700985 mNotMoving = true;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800986 stepIdleStateLocked("s:stationary");
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700987 }
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700988 } else if (mState == STATE_LOCATING) {
989 // If we are currently locating, note that we are not moving and step
990 // if we have located the position.
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700991 synchronized (this) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700992 mNotMoving = true;
993 if (mLocated) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800994 stepIdleStateLocked("s:stationary");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700995 }
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700996 }
997 }
998 }
999 }
1000
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001001 static final int MSG_WRITE_CONFIG = 1;
1002 static final int MSG_REPORT_IDLE_ON = 2;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001003 static final int MSG_REPORT_IDLE_ON_LIGHT = 3;
1004 static final int MSG_REPORT_IDLE_OFF = 4;
1005 static final int MSG_REPORT_ACTIVE = 5;
1006 static final int MSG_TEMP_APP_WHITELIST_TIMEOUT = 6;
Yao Chenca5edbb2016-01-13 14:44:36 -08001007 static final int MSG_REPORT_MAINTENANCE_ACTIVITY = 7;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001008 static final int MSG_FINISH_IDLE_OP = 8;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001009
1010 final class MyHandler extends Handler {
1011 MyHandler(Looper looper) {
1012 super(looper);
1013 }
1014
1015 @Override public void handleMessage(Message msg) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001016 if (DEBUG) Slog.d(TAG, "handleMessage(" + msg.what + ")");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001017 switch (msg.what) {
1018 case MSG_WRITE_CONFIG: {
1019 handleWriteConfigFile();
1020 } break;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001021 case MSG_REPORT_IDLE_ON:
1022 case MSG_REPORT_IDLE_ON_LIGHT: {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001023 EventLogTags.writeDeviceIdleOnStart();
Dianne Hackbornb6843652016-02-22 12:20:13 -08001024 final boolean deepChanged;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001025 final boolean lightChanged;
1026 if (msg.what == MSG_REPORT_IDLE_ON) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001027 deepChanged = mLocalPowerManager.setDeviceIdleMode(true);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001028 lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
1029 } else {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001030 deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001031 lightChanged = mLocalPowerManager.setLightDeviceIdleMode(true);
1032 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001033 try {
1034 mNetworkPolicyManager.setDeviceIdleMode(true);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001035 mBatteryStats.noteDeviceIdleMode(msg.what == MSG_REPORT_IDLE_ON
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07001036 ? BatteryStats.DEVICE_IDLE_MODE_DEEP
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001037 : BatteryStats.DEVICE_IDLE_MODE_LIGHT, null, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001038 } catch (RemoteException e) {
1039 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001040 if (deepChanged) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001041 getContext().sendBroadcastAsUser(mIdleIntent, UserHandle.ALL);
1042 }
1043 if (lightChanged) {
1044 getContext().sendBroadcastAsUser(mLightIdleIntent, UserHandle.ALL);
1045 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001046 EventLogTags.writeDeviceIdleOnComplete();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001047 } break;
1048 case MSG_REPORT_IDLE_OFF: {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001049 EventLogTags.writeDeviceIdleOffStart("unknown");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001050 final boolean deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001051 final boolean lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001052 try {
1053 mNetworkPolicyManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001054 mBatteryStats.noteDeviceIdleMode(BatteryStats.DEVICE_IDLE_MODE_OFF,
1055 null, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001056 } catch (RemoteException e) {
1057 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001058 if (deepChanged) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001059 incActiveIdleOps();
1060 getContext().sendOrderedBroadcastAsUser(mIdleIntent, UserHandle.ALL,
1061 null, mIdleStartedDoneReceiver, null, 0, null, null);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001062 }
1063 if (lightChanged) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001064 incActiveIdleOps();
1065 getContext().sendOrderedBroadcastAsUser(mLightIdleIntent, UserHandle.ALL,
1066 null, mIdleStartedDoneReceiver, null, 0, null, null);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001067 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001068 // Always start with one active op for the message being sent here.
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001069 // Now we are done!
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001070 decActiveIdleOps();
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001071 EventLogTags.writeDeviceIdleOffComplete();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001072 } break;
1073 case MSG_REPORT_ACTIVE: {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001074 String activeReason = (String)msg.obj;
1075 int activeUid = msg.arg1;
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001076 EventLogTags.writeDeviceIdleOffStart(
1077 activeReason != null ? activeReason : "unknown");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001078 final boolean deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001079 final boolean lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001080 try {
1081 mNetworkPolicyManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001082 mBatteryStats.noteDeviceIdleMode(BatteryStats.DEVICE_IDLE_MODE_OFF,
1083 activeReason, activeUid);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001084 } catch (RemoteException e) {
1085 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001086 if (deepChanged) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001087 getContext().sendBroadcastAsUser(mIdleIntent, UserHandle.ALL);
1088 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001089 if (lightChanged) {
1090 getContext().sendBroadcastAsUser(mLightIdleIntent, UserHandle.ALL);
1091 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001092 EventLogTags.writeDeviceIdleOffComplete();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001093 } break;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001094 case MSG_TEMP_APP_WHITELIST_TIMEOUT: {
1095 int uid = msg.arg1;
1096 checkTempAppWhitelistTimeout(uid);
1097 } break;
Yao Chenca5edbb2016-01-13 14:44:36 -08001098 case MSG_REPORT_MAINTENANCE_ACTIVITY: {
1099 boolean active = (msg.arg1 == 1);
1100 final int size = mMaintenanceActivityListeners.beginBroadcast();
1101 try {
1102 for (int i = 0; i < size; i++) {
1103 try {
1104 mMaintenanceActivityListeners.getBroadcastItem(i)
1105 .onMaintenanceActivityChanged(active);
1106 } catch (RemoteException ignored) {
1107 }
1108 }
1109 } finally {
1110 mMaintenanceActivityListeners.finishBroadcast();
1111 }
1112 } break;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001113 case MSG_FINISH_IDLE_OP: {
1114 decActiveIdleOps();
1115 } break;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001116 }
1117 }
1118 }
1119
1120 final MyHandler mHandler;
1121
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001122 BinderService mBinderService;
1123
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001124 private final class BinderService extends IDeviceIdleController.Stub {
1125 @Override public void addPowerSaveWhitelistApp(String name) {
1126 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1127 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001128 long ident = Binder.clearCallingIdentity();
1129 try {
1130 addPowerSaveWhitelistAppInternal(name);
1131 } finally {
1132 Binder.restoreCallingIdentity(ident);
1133 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001134 }
1135
1136 @Override public void removePowerSaveWhitelistApp(String name) {
1137 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1138 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001139 long ident = Binder.clearCallingIdentity();
1140 try {
1141 removePowerSaveWhitelistAppInternal(name);
1142 } finally {
1143 Binder.restoreCallingIdentity(ident);
1144 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001145 }
1146
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001147 @Override public String[] getSystemPowerWhitelistExceptIdle() {
1148 return getSystemPowerWhitelistExceptIdleInternal();
1149 }
1150
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001151 @Override public String[] getSystemPowerWhitelist() {
1152 return getSystemPowerWhitelistInternal();
1153 }
1154
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001155 @Override public String[] getUserPowerWhitelist() {
1156 return getUserPowerWhitelistInternal();
1157 }
1158
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001159 @Override public String[] getFullPowerWhitelistExceptIdle() {
1160 return getFullPowerWhitelistExceptIdleInternal();
1161 }
1162
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001163 @Override public String[] getFullPowerWhitelist() {
1164 return getFullPowerWhitelistInternal();
1165 }
1166
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001167 @Override public int[] getAppIdWhitelistExceptIdle() {
1168 return getAppIdWhitelistExceptIdleInternal();
1169 }
1170
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001171 @Override public int[] getAppIdWhitelist() {
1172 return getAppIdWhitelistInternal();
1173 }
1174
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001175 @Override public int[] getAppIdUserWhitelist() {
1176 return getAppIdUserWhitelistInternal();
1177 }
1178
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001179 @Override public int[] getAppIdTempWhitelist() {
1180 return getAppIdTempWhitelistInternal();
1181 }
1182
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001183 @Override public boolean isPowerSaveWhitelistExceptIdleApp(String name) {
1184 return isPowerSaveWhitelistExceptIdleAppInternal(name);
1185 }
1186
Amith Yamasani06bf8242015-05-08 16:36:21 -07001187 @Override public boolean isPowerSaveWhitelistApp(String name) {
1188 return isPowerSaveWhitelistAppInternal(name);
1189 }
1190
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001191 @Override public void addPowerSaveTempWhitelistApp(String packageName, long duration,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001192 int userId, String reason) throws RemoteException {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001193 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001194 }
1195
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001196 @Override public long addPowerSaveTempWhitelistAppForMms(String packageName,
1197 int userId, String reason) throws RemoteException {
1198 long duration = mConstants.MMS_TEMP_APP_WHITELIST_DURATION;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001199 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001200 return duration;
1201 }
1202
Dianne Hackborn451c3462015-07-21 17:39:46 -07001203 @Override public long addPowerSaveTempWhitelistAppForSms(String packageName,
1204 int userId, String reason) throws RemoteException {
1205 long duration = mConstants.SMS_TEMP_APP_WHITELIST_DURATION;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001206 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Dianne Hackborn451c3462015-07-21 17:39:46 -07001207 return duration;
1208 }
1209
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001210 @Override public void exitIdle(String reason) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001211 getContext().enforceCallingOrSelfPermission(Manifest.permission.DEVICE_POWER,
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001212 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001213 long ident = Binder.clearCallingIdentity();
1214 try {
1215 exitIdleInternal(reason);
1216 } finally {
1217 Binder.restoreCallingIdentity(ident);
1218 }
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001219 }
1220
Yao Chenca5edbb2016-01-13 14:44:36 -08001221 @Override public boolean registerMaintenanceActivityListener(
1222 IMaintenanceActivityListener listener) {
1223 return DeviceIdleController.this.registerMaintenanceActivityListener(listener);
1224 }
1225
1226 @Override public void unregisterMaintenanceActivityListener(
1227 IMaintenanceActivityListener listener) {
1228 DeviceIdleController.this.unregisterMaintenanceActivityListener(listener);
1229 }
1230
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001231 @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1232 DeviceIdleController.this.dump(fd, pw, args);
1233 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001234
1235 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
1236 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
1237 (new Shell()).exec(this, in, out, err, args, resultReceiver);
1238 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001239 }
1240
Dianne Hackborna750a632015-06-16 17:18:23 -07001241 public final class LocalService {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001242 public void addPowerSaveTempWhitelistAppDirect(int appId, long duration, boolean sync,
1243 String reason) {
1244 addPowerSaveTempWhitelistAppDirectInternal(0, appId, duration, sync, reason);
1245 }
1246
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001247 public long getNotificationWhitelistDuration() {
1248 return mConstants.NOTIFICATION_WHITELIST_DURATION;
1249 }
1250
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001251 public void setNetworkPolicyTempWhitelistCallback(Runnable callback) {
1252 setNetworkPolicyTempWhitelistCallbackInternal(callback);
Dianne Hackborna750a632015-06-16 17:18:23 -07001253 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001254
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001255 public void setJobsActive(boolean active) {
1256 DeviceIdleController.this.setJobsActive(active);
1257 }
1258
1259 // Up-call from alarm manager.
1260 public void setAlarmsActive(boolean active) {
1261 DeviceIdleController.this.setAlarmsActive(active);
1262 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001263
1264 /**
1265 * Returns the array of app ids whitelisted by user. Take care not to
1266 * modify this, as it is a reference to the original copy. But the reference
1267 * can change when the list changes, so it needs to be re-acquired when
1268 * {@link PowerManager#ACTION_POWER_SAVE_WHITELIST_CHANGED} is sent.
1269 */
1270 public int[] getPowerSaveWhitelistUserAppIds() {
1271 return DeviceIdleController.this.getPowerSaveWhitelistUserAppIds();
1272 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001273 }
1274
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001275 public DeviceIdleController(Context context) {
1276 super(context);
1277 mConfigFile = new AtomicFile(new File(getSystemDir(), "deviceidle.xml"));
1278 mHandler = new MyHandler(BackgroundThread.getHandler().getLooper());
1279 }
1280
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001281 int[] getPowerSaveWhitelistUserAppIds() {
1282 synchronized (this) {
1283 return mPowerSaveWhitelistUserAppIdArray;
1284 }
1285 }
1286
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001287 private static File getSystemDir() {
1288 return new File(Environment.getDataDirectory(), "system");
1289 }
1290
1291 @Override
1292 public void onStart() {
1293 final PackageManager pm = getContext().getPackageManager();
1294
1295 synchronized (this) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001296 mLightEnabled = mDeepEnabled = getContext().getResources().getBoolean(
Dianne Hackborn92617032015-06-19 15:32:19 -07001297 com.android.internal.R.bool.config_enableAutoPowerModes);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001298 SystemConfig sysConfig = SystemConfig.getInstance();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001299 ArraySet<String> allowPowerExceptIdle = sysConfig.getAllowInPowerSaveExceptIdle();
1300 for (int i=0; i<allowPowerExceptIdle.size(); i++) {
1301 String pkg = allowPowerExceptIdle.valueAt(i);
1302 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001303 ApplicationInfo ai = pm.getApplicationInfo(pkg,
1304 PackageManager.MATCH_SYSTEM_ONLY);
1305 int appid = UserHandle.getAppId(ai.uid);
1306 mPowerSaveWhitelistAppsExceptIdle.put(ai.packageName, appid);
1307 mPowerSaveWhitelistSystemAppIdsExceptIdle.put(appid, true);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001308 } catch (PackageManager.NameNotFoundException e) {
1309 }
1310 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001311 ArraySet<String> allowPower = sysConfig.getAllowInPowerSave();
1312 for (int i=0; i<allowPower.size(); i++) {
1313 String pkg = allowPower.valueAt(i);
1314 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001315 ApplicationInfo ai = pm.getApplicationInfo(pkg,
1316 PackageManager.MATCH_SYSTEM_ONLY);
1317 int appid = UserHandle.getAppId(ai.uid);
1318 // These apps are on both the whitelist-except-idle as well
1319 // as the full whitelist, so they apply in all cases.
1320 mPowerSaveWhitelistAppsExceptIdle.put(ai.packageName, appid);
1321 mPowerSaveWhitelistSystemAppIdsExceptIdle.put(appid, true);
1322 mPowerSaveWhitelistApps.put(ai.packageName, appid);
1323 mPowerSaveWhitelistSystemAppIds.put(appid, true);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001324 } catch (PackageManager.NameNotFoundException e) {
1325 }
1326 }
1327
Adam Lesinski31c05d12015-06-09 17:34:04 -07001328 mConstants = new Constants(mHandler, getContext().getContentResolver());
1329
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001330 readConfigFileLocked();
1331 updateWhitelistAppIdsLocked();
1332
Dianne Hackborn88c41352016-04-07 15:18:58 -07001333 mNetworkConnected = true;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001334 mScreenOn = true;
1335 // Start out assuming we are charging. If we aren't, we will at least get
1336 // a battery update the next time the level drops.
1337 mCharging = true;
1338 mState = STATE_ACTIVE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001339 mLightState = LIGHT_STATE_ACTIVE;
Adam Lesinski31c05d12015-06-09 17:34:04 -07001340 mInactiveTimeout = mConstants.INACTIVE_TIMEOUT;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001341 }
1342
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001343 mBinderService = new BinderService();
1344 publishBinderService(Context.DEVICE_IDLE_CONTROLLER, mBinderService);
Dianne Hackborna750a632015-06-16 17:18:23 -07001345 publishLocalService(LocalService.class, new LocalService());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001346 }
1347
1348 @Override
1349 public void onBootPhase(int phase) {
1350 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1351 synchronized (this) {
1352 mAlarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
1353 mBatteryStats = BatteryStatsService.getService();
1354 mLocalPowerManager = getLocalService(PowerManagerInternal.class);
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001355 mPowerManager = getContext().getSystemService(PowerManager.class);
1356 mActiveIdleWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
1357 "deviceidle_maint");
1358 mActiveIdleWakeLock.setReferenceCounted(false);
Dianne Hackborn88c41352016-04-07 15:18:58 -07001359 mConnectivityService = (ConnectivityService)ServiceManager.getService(
1360 Context.CONNECTIVITY_SERVICE);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001361 mLocalAlarmManager = getLocalService(AlarmManagerService.LocalService.class);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001362 mNetworkPolicyManager = INetworkPolicyManager.Stub.asInterface(
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001363 ServiceManager.getService(Context.NETWORK_POLICY_SERVICE));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001364 mDisplayManager = (DisplayManager) getContext().getSystemService(
1365 Context.DISPLAY_SERVICE);
1366 mSensorManager = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001367 int sigMotionSensorId = getContext().getResources().getInteger(
1368 com.android.internal.R.integer.config_autoPowerModeAnyMotionSensor);
1369 if (sigMotionSensorId > 0) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001370 mMotionSensor = mSensorManager.getDefaultSensor(sigMotionSensorId, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001371 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001372 if (mMotionSensor == null && getContext().getResources().getBoolean(
Joe LaPenna23d681b2015-08-27 15:12:11 -07001373 com.android.internal.R.bool.config_autoPowerModePreferWristTilt)) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001374 mMotionSensor = mSensorManager.getDefaultSensor(
1375 Sensor.TYPE_WRIST_TILT_GESTURE, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001376 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001377 if (mMotionSensor == null) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07001378 // As a last ditch, fall back to SMD.
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001379 mMotionSensor = mSensorManager.getDefaultSensor(
1380 Sensor.TYPE_SIGNIFICANT_MOTION, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001381 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001382
Joe LaPenna23d681b2015-08-27 15:12:11 -07001383 if (getContext().getResources().getBoolean(
1384 com.android.internal.R.bool.config_autoPowerModePrefetchLocation)) {
1385 mLocationManager = (LocationManager) getContext().getSystemService(
1386 Context.LOCATION_SERVICE);
1387 mLocationRequest = new LocationRequest()
1388 .setQuality(LocationRequest.ACCURACY_FINE)
1389 .setInterval(0)
1390 .setFastestInterval(0)
1391 .setNumUpdates(1);
1392 }
1393
1394 float angleThreshold = getContext().getResources().getInteger(
1395 com.android.internal.R.integer.config_autoPowerModeThresholdAngle) / 100f;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001396 mAnyMotionDetector = new AnyMotionDetector(
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001397 (PowerManager) getContext().getSystemService(Context.POWER_SERVICE),
Joe LaPenna23d681b2015-08-27 15:12:11 -07001398 mHandler, mSensorManager, this, angleThreshold);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001399
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001400 mIdleIntent = new Intent(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001401 mIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1402 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001403 mLightIdleIntent = new Intent(PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED);
1404 mLightIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1405 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001406
1407 IntentFilter filter = new IntentFilter();
1408 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001409 getContext().registerReceiver(mReceiver, filter);
Amith Yamasaniac59f75e2016-05-05 12:38:17 -07001410
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001411 filter = new IntentFilter();
1412 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1413 filter.addDataScheme("package");
Amith Yamasaniac59f75e2016-05-05 12:38:17 -07001414 getContext().registerReceiver(mReceiver, filter);
1415
Dianne Hackborn88c41352016-04-07 15:18:58 -07001416 filter = new IntentFilter();
1417 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001418 getContext().registerReceiver(mReceiver, filter);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001419
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001420 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001421 mLocalAlarmManager.setDeviceIdleUserWhitelist(mPowerSaveWhitelistUserAppIdArray);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001422 mDisplayManager.registerDisplayListener(mDisplayListener, null);
1423 updateDisplayLocked();
1424 }
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -07001425 updateConnectivityState(null);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001426 }
1427 }
1428
1429 public boolean addPowerSaveWhitelistAppInternal(String name) {
1430 synchronized (this) {
1431 try {
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001432 ApplicationInfo ai = getContext().getPackageManager().getApplicationInfo(name,
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001433 PackageManager.MATCH_UNINSTALLED_PACKAGES);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001434 if (mPowerSaveWhitelistUserApps.put(name, UserHandle.getAppId(ai.uid)) == null) {
1435 reportPowerSaveWhitelistChangedLocked();
1436 updateWhitelistAppIdsLocked();
1437 writeConfigFileLocked();
1438 }
1439 return true;
1440 } catch (PackageManager.NameNotFoundException e) {
1441 return false;
1442 }
1443 }
1444 }
1445
1446 public boolean removePowerSaveWhitelistAppInternal(String name) {
1447 synchronized (this) {
1448 if (mPowerSaveWhitelistUserApps.remove(name) != null) {
1449 reportPowerSaveWhitelistChangedLocked();
1450 updateWhitelistAppIdsLocked();
1451 writeConfigFileLocked();
1452 return true;
1453 }
1454 }
1455 return false;
1456 }
1457
Felipe Lemef8a46232016-02-10 13:51:54 -08001458 public boolean getPowerSaveWhitelistAppInternal(String name) {
1459 synchronized (this) {
1460 return mPowerSaveWhitelistUserApps.containsKey(name);
1461 }
1462 }
1463
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001464 public String[] getSystemPowerWhitelistExceptIdleInternal() {
1465 synchronized (this) {
1466 int size = mPowerSaveWhitelistAppsExceptIdle.size();
1467 String[] apps = new String[size];
1468 for (int i = 0; i < size; i++) {
1469 apps[i] = mPowerSaveWhitelistAppsExceptIdle.keyAt(i);
1470 }
1471 return apps;
1472 }
1473 }
1474
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001475 public String[] getSystemPowerWhitelistInternal() {
1476 synchronized (this) {
1477 int size = mPowerSaveWhitelistApps.size();
1478 String[] apps = new String[size];
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001479 for (int i = 0; i < size; i++) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001480 apps[i] = mPowerSaveWhitelistApps.keyAt(i);
1481 }
1482 return apps;
1483 }
1484 }
1485
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001486 public String[] getUserPowerWhitelistInternal() {
1487 synchronized (this) {
1488 int size = mPowerSaveWhitelistUserApps.size();
1489 String[] apps = new String[size];
1490 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1491 apps[i] = mPowerSaveWhitelistUserApps.keyAt(i);
1492 }
1493 return apps;
1494 }
1495 }
1496
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001497 public String[] getFullPowerWhitelistExceptIdleInternal() {
1498 synchronized (this) {
1499 int size = mPowerSaveWhitelistAppsExceptIdle.size() + mPowerSaveWhitelistUserApps.size();
1500 String[] apps = new String[size];
1501 int cur = 0;
1502 for (int i = 0; i < mPowerSaveWhitelistAppsExceptIdle.size(); i++) {
1503 apps[cur] = mPowerSaveWhitelistAppsExceptIdle.keyAt(i);
1504 cur++;
1505 }
1506 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1507 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
1508 cur++;
1509 }
1510 return apps;
1511 }
1512 }
1513
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001514 public String[] getFullPowerWhitelistInternal() {
1515 synchronized (this) {
1516 int size = mPowerSaveWhitelistApps.size() + mPowerSaveWhitelistUserApps.size();
1517 String[] apps = new String[size];
1518 int cur = 0;
1519 for (int i = 0; i < mPowerSaveWhitelistApps.size(); i++) {
1520 apps[cur] = mPowerSaveWhitelistApps.keyAt(i);
1521 cur++;
1522 }
1523 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1524 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
1525 cur++;
1526 }
1527 return apps;
1528 }
1529 }
1530
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001531 public boolean isPowerSaveWhitelistExceptIdleAppInternal(String packageName) {
1532 synchronized (this) {
1533 return mPowerSaveWhitelistAppsExceptIdle.containsKey(packageName)
1534 || mPowerSaveWhitelistUserApps.containsKey(packageName);
1535 }
1536 }
1537
Amith Yamasani06bf8242015-05-08 16:36:21 -07001538 public boolean isPowerSaveWhitelistAppInternal(String packageName) {
1539 synchronized (this) {
1540 return mPowerSaveWhitelistApps.containsKey(packageName)
1541 || mPowerSaveWhitelistUserApps.containsKey(packageName);
1542 }
1543 }
1544
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001545 public int[] getAppIdWhitelistExceptIdleInternal() {
1546 synchronized (this) {
1547 return mPowerSaveWhitelistExceptIdleAppIdArray;
1548 }
1549 }
1550
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001551 public int[] getAppIdWhitelistInternal() {
1552 synchronized (this) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001553 return mPowerSaveWhitelistAllAppIdArray;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001554 }
1555 }
1556
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001557 public int[] getAppIdUserWhitelistInternal() {
1558 synchronized (this) {
1559 return mPowerSaveWhitelistUserAppIdArray;
1560 }
1561 }
1562
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001563 public int[] getAppIdTempWhitelistInternal() {
1564 synchronized (this) {
1565 return mTempWhitelistAppIdArray;
1566 }
1567 }
1568
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001569 void addPowerSaveTempWhitelistAppChecked(String packageName, long duration,
1570 int userId, String reason) throws RemoteException {
1571 getContext().enforceCallingPermission(
1572 Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
1573 "No permission to change device idle whitelist");
1574 final int callingUid = Binder.getCallingUid();
1575 userId = ActivityManagerNative.getDefault().handleIncomingUser(
1576 Binder.getCallingPid(),
1577 callingUid,
1578 userId,
1579 /*allowAll=*/ false,
1580 /*requireFull=*/ false,
1581 "addPowerSaveTempWhitelistApp", null);
1582 final long token = Binder.clearCallingIdentity();
1583 try {
1584 addPowerSaveTempWhitelistAppInternal(callingUid,
1585 packageName, duration, userId, true, reason);
1586 } finally {
1587 Binder.restoreCallingIdentity(token);
1588 }
1589 }
1590
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001591 /**
1592 * Adds an app to the temporary whitelist and resets the endTime for granting the
1593 * app an exemption to access network and acquire wakelocks.
1594 */
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001595 void addPowerSaveTempWhitelistAppInternal(int callingUid, String packageName,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001596 long duration, int userId, boolean sync, String reason) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001597 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001598 int uid = getContext().getPackageManager().getPackageUidAsUser(packageName, userId);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001599 int appId = UserHandle.getAppId(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001600 addPowerSaveTempWhitelistAppDirectInternal(callingUid, appId, duration, sync, reason);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001601 } catch (NameNotFoundException e) {
1602 }
1603 }
1604
Dianne Hackborna750a632015-06-16 17:18:23 -07001605 /**
1606 * Adds an app to the temporary whitelist and resets the endTime for granting the
1607 * app an exemption to access network and acquire wakelocks.
1608 */
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001609 void addPowerSaveTempWhitelistAppDirectInternal(int callingUid, int appId,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001610 long duration, boolean sync, String reason) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001611 final long timeNow = SystemClock.elapsedRealtime();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001612 Runnable networkPolicyTempWhitelistCallback = null;
Dianne Hackborna750a632015-06-16 17:18:23 -07001613 synchronized (this) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001614 int callingAppId = UserHandle.getAppId(callingUid);
1615 if (callingAppId >= Process.FIRST_APPLICATION_UID) {
1616 if (!mPowerSaveWhitelistSystemAppIds.get(callingAppId)) {
1617 throw new SecurityException("Calling app " + UserHandle.formatUid(callingUid)
1618 + " is not on whitelist");
1619 }
1620 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001621 duration = Math.min(duration, mConstants.MAX_TEMP_APP_WHITELIST_DURATION);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001622 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.get(appId);
1623 final boolean newEntry = entry == null;
Dianne Hackborna750a632015-06-16 17:18:23 -07001624 // Set the new end time
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001625 if (newEntry) {
1626 entry = new Pair<>(new MutableLong(0), reason);
1627 mTempWhitelistAppIdEndTimes.put(appId, entry);
1628 }
1629 entry.first.value = timeNow + duration;
Dianne Hackborna750a632015-06-16 17:18:23 -07001630 if (DEBUG) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001631 Slog.d(TAG, "Adding AppId " + appId + " to temp whitelist. New entry: " + newEntry);
Dianne Hackborna750a632015-06-16 17:18:23 -07001632 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001633 if (newEntry) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001634 // No pending timeout for the app id, post a delayed message
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001635 try {
1636 mBatteryStats.noteEvent(BatteryStats.HistoryItem.EVENT_TEMP_WHITELIST_START,
1637 reason, appId);
1638 } catch (RemoteException e) {
1639 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001640 postTempActiveTimeoutMessage(appId, duration);
1641 updateTempWhitelistAppIdsLocked();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001642 if (mNetworkPolicyTempWhitelistCallback != null) {
1643 if (!sync) {
1644 mHandler.post(mNetworkPolicyTempWhitelistCallback);
1645 } else {
1646 networkPolicyTempWhitelistCallback = mNetworkPolicyTempWhitelistCallback;
1647 }
1648 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001649 reportTempWhitelistChangedLocked();
1650 }
1651 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001652 if (networkPolicyTempWhitelistCallback != null) {
1653 networkPolicyTempWhitelistCallback.run();
1654 }
1655 }
1656
1657 public void setNetworkPolicyTempWhitelistCallbackInternal(Runnable callback) {
1658 synchronized (this) {
1659 mNetworkPolicyTempWhitelistCallback = callback;
1660 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001661 }
1662
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001663 private void postTempActiveTimeoutMessage(int uid, long delay) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001664 if (DEBUG) {
1665 Slog.d(TAG, "postTempActiveTimeoutMessage: uid=" + uid + ", delay=" + delay);
1666 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001667 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_TEMP_APP_WHITELIST_TIMEOUT, uid, 0),
1668 delay);
1669 }
1670
1671 void checkTempAppWhitelistTimeout(int uid) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001672 final long timeNow = SystemClock.elapsedRealtime();
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001673 if (DEBUG) {
1674 Slog.d(TAG, "checkTempAppWhitelistTimeout: uid=" + uid + ", timeNow=" + timeNow);
1675 }
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
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001699 if (DEBUG) {
1700 Slog.d(TAG, "Time to remove UID " + uid + ": " + entry.first.value);
1701 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001702 postTempActiveTimeoutMessage(uid, entry.first.value - timeNow);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001703 }
1704 }
1705 }
1706
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001707 public void exitIdleInternal(String reason) {
1708 synchronized (this) {
1709 becomeActiveLocked(reason, Binder.getCallingUid());
1710 }
1711 }
1712
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -07001713 void updateConnectivityState(Intent connIntent) {
1714 ConnectivityService cm;
1715 synchronized (this) {
1716 cm = mConnectivityService;
1717 }
1718 if (cm == null) {
1719 return;
1720 }
1721 // Note: can't call out to ConnectivityService with our lock held.
1722 NetworkInfo ni = cm.getActiveNetworkInfo();
1723 synchronized (this) {
Dianne Hackborn88c41352016-04-07 15:18:58 -07001724 boolean conn;
1725 if (ni == null) {
1726 conn = false;
1727 } else {
1728 if (connIntent == null) {
1729 conn = ni.isConnected();
1730 } else {
1731 final int networkType =
1732 connIntent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1733 ConnectivityManager.TYPE_NONE);
1734 if (ni.getType() != networkType) {
1735 return;
1736 }
1737 conn = !connIntent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,
1738 false);
1739 }
1740 }
1741 if (conn != mNetworkConnected) {
1742 mNetworkConnected = conn;
1743 if (conn && mLightState == LIGHT_STATE_WAITING_FOR_NETWORK) {
1744 stepLightIdleStateLocked("network");
1745 }
1746 }
1747 }
1748 }
1749
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001750 void updateDisplayLocked() {
1751 mCurDisplay = mDisplayManager.getDisplay(Display.DEFAULT_DISPLAY);
1752 // We consider any situation where the display is showing something to be it on,
1753 // because if there is anything shown we are going to be updating it at some
1754 // frequency so can't be allowed to go into deep sleeps.
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001755 boolean screenOn = mCurDisplay.getState() == Display.STATE_ON;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001756 if (DEBUG) Slog.d(TAG, "updateDisplayLocked: screenOn=" + screenOn);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001757 if (!screenOn && mScreenOn) {
1758 mScreenOn = false;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001759 if (!mForceIdle) {
1760 becomeInactiveIfAppropriateLocked();
1761 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001762 } else if (screenOn) {
1763 mScreenOn = true;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001764 if (!mForceIdle) {
1765 becomeActiveLocked("screen", Process.myUid());
1766 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001767 }
1768 }
1769
1770 void updateChargingLocked(boolean charging) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001771 if (DEBUG) Slog.i(TAG, "updateChargingLocked: charging=" + charging);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001772 if (!charging && mCharging) {
1773 mCharging = false;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001774 if (!mForceIdle) {
1775 becomeInactiveIfAppropriateLocked();
1776 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001777 } else if (charging) {
1778 mCharging = charging;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001779 if (!mForceIdle) {
1780 becomeActiveLocked("charging", Process.myUid());
1781 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001782 }
1783 }
1784
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001785 void scheduleReportActiveLocked(String activeReason, int activeUid) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001786 Message msg = mHandler.obtainMessage(MSG_REPORT_ACTIVE, activeUid, 0, activeReason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001787 mHandler.sendMessage(msg);
1788 }
1789
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001790 void becomeActiveLocked(String activeReason, int activeUid) {
1791 if (DEBUG) Slog.i(TAG, "becomeActiveLocked, reason = " + activeReason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001792 if (mState != STATE_ACTIVE || mLightState != STATE_ACTIVE) {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001793 EventLogTags.writeDeviceIdle(STATE_ACTIVE, activeReason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001794 EventLogTags.writeDeviceIdleLight(LIGHT_STATE_ACTIVE, activeReason);
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001795 scheduleReportActiveLocked(activeReason, activeUid);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001796 mState = STATE_ACTIVE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001797 mLightState = LIGHT_STATE_ACTIVE;
Adam Lesinski31c05d12015-06-09 17:34:04 -07001798 mInactiveTimeout = mConstants.INACTIVE_TIMEOUT;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001799 mCurIdleBudget = 0;
1800 mMaintenanceStartTime = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001801 resetIdleManagementLocked();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001802 resetLightIdleManagementLocked();
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001803 addEvent(EVENT_NORMAL);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001804 }
1805 }
1806
1807 void becomeInactiveIfAppropriateLocked() {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001808 if (DEBUG) Slog.d(TAG, "becomeInactiveIfAppropriateLocked()");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001809 if ((!mScreenOn && !mCharging) || mForceIdle) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001810 // Screen has turned off; we are now going to become inactive and start
1811 // waiting to see if we will ultimately go idle.
Dianne Hackbornb6843652016-02-22 12:20:13 -08001812 if (mState == STATE_ACTIVE && mDeepEnabled) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001813 mState = STATE_INACTIVE;
1814 if (DEBUG) Slog.d(TAG, "Moved from STATE_ACTIVE to STATE_INACTIVE");
1815 resetIdleManagementLocked();
1816 scheduleAlarmLocked(mInactiveTimeout, false);
1817 EventLogTags.writeDeviceIdle(mState, "no activity");
1818 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001819 if (mLightState == LIGHT_STATE_ACTIVE && mLightEnabled) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001820 mLightState = LIGHT_STATE_INACTIVE;
1821 if (DEBUG) Slog.d(TAG, "Moved from LIGHT_STATE_ACTIVE to LIGHT_STATE_INACTIVE");
1822 resetLightIdleManagementLocked();
Dianne Hackborn953fc942016-03-29 15:36:24 -07001823 scheduleLightAlarmLocked(mConstants.LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001824 EventLogTags.writeDeviceIdleLight(mLightState, "no activity");
1825 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001826 }
1827 }
1828
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001829 void resetIdleManagementLocked() {
1830 mNextIdlePendingDelay = 0;
1831 mNextIdleDelay = 0;
Dianne Hackborn953fc942016-03-29 15:36:24 -07001832 mNextLightIdleDelay = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001833 cancelAlarmLocked();
Kevin Gabayan92f15e62016-04-04 17:52:22 -07001834 cancelSensingTimeoutAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001835 cancelLocatingLocked();
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001836 stopMonitoringMotionLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001837 mAnyMotionDetector.stop();
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001838 }
1839
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001840 void resetLightIdleManagementLocked() {
1841 cancelLightAlarmLocked();
1842 }
1843
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001844 void exitForceIdleLocked() {
1845 if (mForceIdle) {
1846 mForceIdle = false;
1847 if (mScreenOn || mCharging) {
Dianne Hackborn88c41352016-04-07 15:18:58 -07001848 becomeActiveLocked("exit-force", Process.myUid());
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001849 }
1850 }
1851 }
1852
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001853 void stepLightIdleStateLocked(String reason) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001854 if (mLightState == LIGHT_STATE_OVERRIDE) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001855 // If we are already in deep device idle mode, then
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001856 // there is nothing left to do for light mode.
1857 return;
1858 }
1859
1860 if (DEBUG) Slog.d(TAG, "stepLightIdleStateLocked: mLightState=" + mLightState);
1861 EventLogTags.writeDeviceIdleLightStep();
1862
1863 switch (mLightState) {
1864 case LIGHT_STATE_INACTIVE:
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001865 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
Dianne Hackborn953fc942016-03-29 15:36:24 -07001866 // Reset the upcoming idle delays.
1867 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001868 mMaintenanceStartTime = 0;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001869 if (!isOpsInactiveLocked()) {
1870 // We have some active ops going on... give them a chance to finish
1871 // before going in to our first idle.
1872 mLightState = LIGHT_STATE_PRE_IDLE;
1873 EventLogTags.writeDeviceIdleLight(mLightState, reason);
1874 scheduleLightAlarmLocked(mConstants.LIGHT_PRE_IDLE_TIMEOUT);
1875 break;
1876 }
1877 // Nothing active, fall through to immediately idle.
1878 case LIGHT_STATE_PRE_IDLE:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001879 case LIGHT_STATE_IDLE_MAINTENANCE:
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001880 if (mMaintenanceStartTime != 0) {
1881 long duration = SystemClock.elapsedRealtime() - mMaintenanceStartTime;
1882 if (duration < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
1883 // We didn't use up all of our minimum budget; add this to the reserve.
1884 mCurIdleBudget += (mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET-duration);
1885 } else {
1886 // We used more than our minimum budget; this comes out of the reserve.
1887 mCurIdleBudget -= (duration-mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET);
1888 }
1889 }
1890 mMaintenanceStartTime = 0;
Dianne Hackborn953fc942016-03-29 15:36:24 -07001891 scheduleLightAlarmLocked(mNextLightIdleDelay);
1892 mNextLightIdleDelay = Math.min(mConstants.LIGHT_MAX_IDLE_TIMEOUT,
1893 (long)(mNextLightIdleDelay * mConstants.LIGHT_IDLE_FACTOR));
1894 if (mNextLightIdleDelay < mConstants.LIGHT_IDLE_TIMEOUT) {
1895 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
1896 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001897 if (DEBUG) Slog.d(TAG, "Moved to LIGHT_STATE_IDLE.");
1898 mLightState = LIGHT_STATE_IDLE;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001899 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001900 addEvent(EVENT_LIGHT_IDLE);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001901 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON_LIGHT);
1902 break;
1903 case LIGHT_STATE_IDLE:
Dianne Hackborn88c41352016-04-07 15:18:58 -07001904 case LIGHT_STATE_WAITING_FOR_NETWORK:
1905 if (mNetworkConnected || mLightState == LIGHT_STATE_WAITING_FOR_NETWORK) {
1906 // We have been idling long enough, now it is time to do some work.
1907 mActiveIdleOpCount = 1;
1908 mActiveIdleWakeLock.acquire();
1909 mMaintenanceStartTime = SystemClock.elapsedRealtime();
1910 if (mCurIdleBudget < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
1911 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
1912 } else if (mCurIdleBudget > mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET) {
1913 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET;
1914 }
1915 scheduleLightAlarmLocked(mCurIdleBudget);
1916 if (DEBUG) Slog.d(TAG,
1917 "Moved from LIGHT_STATE_IDLE to LIGHT_STATE_IDLE_MAINTENANCE.");
1918 mLightState = LIGHT_STATE_IDLE_MAINTENANCE;
1919 EventLogTags.writeDeviceIdleLight(mLightState, reason);
1920 addEvent(EVENT_LIGHT_MAINTENANCE);
1921 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
1922 } else {
1923 // We'd like to do maintenance, but currently don't have network
1924 // connectivity... let's try to wait until the network comes back.
1925 // We'll only wait for another full idle period, however, and then give up.
1926 scheduleLightAlarmLocked(mNextLightIdleDelay);
1927 if (DEBUG) Slog.d(TAG, "Moved to LIGHT_WAITING_FOR_NETWORK.");
1928 mLightState = LIGHT_STATE_WAITING_FOR_NETWORK;
1929 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001930 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001931 break;
1932 }
1933 }
1934
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001935 void stepIdleStateLocked(String reason) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001936 if (DEBUG) Slog.d(TAG, "stepIdleStateLocked: mState=" + mState);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001937 EventLogTags.writeDeviceIdleStep();
1938
1939 final long now = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07001940 if ((now+mConstants.MIN_TIME_TO_ALARM) > mAlarmManager.getNextWakeFromIdleTime()) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001941 // Whoops, there is an upcoming alarm. We don't actually want to go idle.
1942 if (mState != STATE_ACTIVE) {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001943 becomeActiveLocked("alarm", Process.myUid());
Koji Fukui27b33302015-12-16 19:43:01 +09001944 becomeInactiveIfAppropriateLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001945 }
1946 return;
1947 }
1948
1949 switch (mState) {
1950 case STATE_INACTIVE:
1951 // We have now been inactive long enough, it is time to start looking
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001952 // for motion and sleep some more while doing so.
1953 startMonitoringMotionLocked();
Adam Lesinski31c05d12015-06-09 17:34:04 -07001954 scheduleAlarmLocked(mConstants.IDLE_AFTER_INACTIVE_TIMEOUT, false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001955 // Reset the upcoming idle delays.
Adam Lesinski31c05d12015-06-09 17:34:04 -07001956 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
1957 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001958 mState = STATE_IDLE_PENDING;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001959 if (DEBUG) Slog.d(TAG, "Moved from STATE_INACTIVE to STATE_IDLE_PENDING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001960 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001961 break;
1962 case STATE_IDLE_PENDING:
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001963 mState = STATE_SENSING;
1964 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE_PENDING to STATE_SENSING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001965 EventLogTags.writeDeviceIdle(mState, reason);
Kevin Gabayan92f15e62016-04-04 17:52:22 -07001966 scheduleSensingTimeoutAlarmLocked(mConstants.SENSING_TIMEOUT);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001967 cancelLocatingLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001968 mNotMoving = false;
1969 mLocated = false;
1970 mLastGenericLocation = null;
1971 mLastGpsLocation = null;
Kevin Gabayan92f15e62016-04-04 17:52:22 -07001972 mAnyMotionDetector.checkForAnyMotion();
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001973 break;
1974 case STATE_SENSING:
Kevin Gabayan92f15e62016-04-04 17:52:22 -07001975 cancelSensingTimeoutAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001976 mState = STATE_LOCATING;
1977 if (DEBUG) Slog.d(TAG, "Moved from STATE_SENSING to STATE_LOCATING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001978 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001979 scheduleAlarmLocked(mConstants.LOCATING_TIMEOUT, false);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001980 if (mLocationManager != null
1981 && mLocationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
1982 mLocationManager.requestLocationUpdates(mLocationRequest,
1983 mGenericLocationListener, mHandler.getLooper());
1984 mLocating = true;
1985 } else {
1986 mHasNetworkLocation = false;
1987 }
1988 if (mLocationManager != null
1989 && mLocationManager.getProvider(LocationManager.GPS_PROVIDER) != null) {
1990 mHasGps = true;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001991 mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 5,
1992 mGpsLocationListener, mHandler.getLooper());
Joe LaPenna23d681b2015-08-27 15:12:11 -07001993 mLocating = true;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001994 } else {
Joe LaPenna23d681b2015-08-27 15:12:11 -07001995 mHasGps = false;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001996 }
Joe LaPenna23d681b2015-08-27 15:12:11 -07001997 // If we have a location provider, we're all set, the listeners will move state
1998 // forward.
1999 if (mLocating) {
2000 break;
2001 }
2002
2003 // Otherwise, we have to move from locating into idle maintenance.
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002004 case STATE_LOCATING:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002005 cancelAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002006 cancelLocatingLocked();
2007 mAnyMotionDetector.stop();
Dianne Hackborn953fc942016-03-29 15:36:24 -07002008
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002009 case STATE_IDLE_MAINTENANCE:
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002010 scheduleAlarmLocked(mNextIdleDelay, true);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002011 if (DEBUG) Slog.d(TAG, "Moved to STATE_IDLE. Next alarm in " + mNextIdleDelay +
2012 " ms.");
Adam Lesinski31c05d12015-06-09 17:34:04 -07002013 mNextIdleDelay = (long)(mNextIdleDelay * mConstants.IDLE_FACTOR);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002014 if (DEBUG) Slog.d(TAG, "Setting mNextIdleDelay = " + mNextIdleDelay);
Adam Lesinski31c05d12015-06-09 17:34:04 -07002015 mNextIdleDelay = Math.min(mNextIdleDelay, mConstants.MAX_IDLE_TIMEOUT);
Dianne Hackborn953fc942016-03-29 15:36:24 -07002016 if (mNextIdleDelay < mConstants.IDLE_TIMEOUT) {
2017 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
2018 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002019 mState = STATE_IDLE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002020 if (mLightState != LIGHT_STATE_OVERRIDE) {
2021 mLightState = LIGHT_STATE_OVERRIDE;
2022 cancelLightAlarmLocked();
2023 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002024 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackbornb6843652016-02-22 12:20:13 -08002025 addEvent(EVENT_DEEP_IDLE);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002026 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON);
2027 break;
2028 case STATE_IDLE:
2029 // We have been idling long enough, now it is time to do some work.
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002030 mActiveIdleOpCount = 1;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002031 mActiveIdleWakeLock.acquire();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002032 scheduleAlarmLocked(mNextIdlePendingDelay, false);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002033 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE to STATE_IDLE_MAINTENANCE. " +
2034 "Next alarm in " + mNextIdlePendingDelay + " ms.");
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002035 mMaintenanceStartTime = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07002036 mNextIdlePendingDelay = Math.min(mConstants.MAX_IDLE_PENDING_TIMEOUT,
2037 (long)(mNextIdlePendingDelay * mConstants.IDLE_PENDING_FACTOR));
Dianne Hackborn953fc942016-03-29 15:36:24 -07002038 if (mNextIdlePendingDelay < mConstants.IDLE_PENDING_TIMEOUT) {
2039 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
2040 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002041 mState = STATE_IDLE_MAINTENANCE;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002042 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackbornb6843652016-02-22 12:20:13 -08002043 addEvent(EVENT_DEEP_MAINTENANCE);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002044 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
2045 break;
2046 }
2047 }
2048
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002049 void incActiveIdleOps() {
2050 synchronized (this) {
2051 mActiveIdleOpCount++;
2052 }
2053 }
2054
2055 void decActiveIdleOps() {
2056 synchronized (this) {
2057 mActiveIdleOpCount--;
2058 if (mActiveIdleOpCount <= 0) {
2059 exitMaintenanceEarlyIfNeededLocked();
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002060 mActiveIdleWakeLock.release();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002061 }
2062 }
2063 }
2064
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002065 void setJobsActive(boolean active) {
2066 synchronized (this) {
2067 mJobsActive = active;
Yao Chenca5edbb2016-01-13 14:44:36 -08002068 reportMaintenanceActivityIfNeededLocked();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002069 if (!active) {
2070 exitMaintenanceEarlyIfNeededLocked();
2071 }
2072 }
2073 }
2074
2075 void setAlarmsActive(boolean active) {
2076 synchronized (this) {
2077 mAlarmsActive = active;
2078 if (!active) {
2079 exitMaintenanceEarlyIfNeededLocked();
2080 }
2081 }
2082 }
2083
Yao Chenca5edbb2016-01-13 14:44:36 -08002084 boolean registerMaintenanceActivityListener(IMaintenanceActivityListener listener) {
2085 synchronized (this) {
2086 mMaintenanceActivityListeners.register(listener);
2087 return mReportedMaintenanceActivity;
2088 }
2089 }
2090
2091 void unregisterMaintenanceActivityListener(IMaintenanceActivityListener listener) {
2092 synchronized (this) {
2093 mMaintenanceActivityListeners.unregister(listener);
2094 }
2095 }
2096
2097 void reportMaintenanceActivityIfNeededLocked() {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07002098 boolean active = mJobsActive;
Yao Chenca5edbb2016-01-13 14:44:36 -08002099 if (active == mReportedMaintenanceActivity) {
2100 return;
2101 }
2102 mReportedMaintenanceActivity = active;
2103 Message msg = mHandler.obtainMessage(MSG_REPORT_MAINTENANCE_ACTIVITY,
2104 mReportedMaintenanceActivity ? 1 : 0, 0);
2105 mHandler.sendMessage(msg);
2106 }
2107
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002108 boolean isOpsInactiveLocked() {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07002109 return mActiveIdleOpCount <= 0 && !mJobsActive && !mAlarmsActive;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002110 }
2111
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002112 void exitMaintenanceEarlyIfNeededLocked() {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002113 if (mState == STATE_IDLE_MAINTENANCE || mLightState == LIGHT_STATE_IDLE_MAINTENANCE
2114 || mLightState == LIGHT_STATE_PRE_IDLE) {
2115 if (isOpsInactiveLocked()) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002116 final long now = SystemClock.elapsedRealtime();
2117 if (DEBUG) {
2118 StringBuilder sb = new StringBuilder();
2119 sb.append("Exit: start=");
2120 TimeUtils.formatDuration(mMaintenanceStartTime, sb);
2121 sb.append(" now=");
2122 TimeUtils.formatDuration(now, sb);
2123 Slog.d(TAG, sb.toString());
2124 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002125 if (mState == STATE_IDLE_MAINTENANCE) {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002126 stepIdleStateLocked("s:early");
2127 } else if (mLightState == LIGHT_STATE_PRE_IDLE) {
2128 stepLightIdleStateLocked("s:predone");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002129 } else {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002130 stepLightIdleStateLocked("s:early");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002131 }
2132 }
2133 }
2134 }
2135
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002136 void motionLocked() {
2137 if (DEBUG) Slog.d(TAG, "motionLocked()");
2138 // The motion sensor will have been disabled at this point
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002139 handleMotionDetectedLocked(mConstants.MOTION_INACTIVE_TIMEOUT, "motion");
2140 }
2141
2142 void handleMotionDetectedLocked(long timeout, String type) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002143 // The device is not yet active, so we want to go back to the pending idle
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002144 // state to wait again for no motion. Note that we only monitor for motion
2145 // after moving out of the inactive state, so no need to worry about that.
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002146 boolean becomeInactive = false;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002147 if (mState != STATE_ACTIVE) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002148 scheduleReportActiveLocked(type, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002149 mState = STATE_ACTIVE;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002150 mInactiveTimeout = timeout;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002151 mCurIdleBudget = 0;
2152 mMaintenanceStartTime = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002153 EventLogTags.writeDeviceIdle(mState, type);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002154 addEvent(EVENT_NORMAL);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002155 becomeInactive = true;
2156 }
2157 if (mLightState == LIGHT_STATE_OVERRIDE) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002158 // We went out of light idle mode because we had started deep idle mode... let's
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002159 // now go back and reset things so we resume light idling if appropriate.
2160 mLightState = STATE_ACTIVE;
2161 EventLogTags.writeDeviceIdleLight(mLightState, type);
2162 becomeInactive = true;
2163 }
2164 if (becomeInactive) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002165 becomeInactiveIfAppropriateLocked();
2166 }
2167 }
2168
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002169 void receivedGenericLocationLocked(Location location) {
2170 if (mState != STATE_LOCATING) {
2171 cancelLocatingLocked();
2172 return;
2173 }
2174 if (DEBUG) Slog.d(TAG, "Generic location: " + location);
2175 mLastGenericLocation = new Location(location);
Joe LaPenna23d681b2015-08-27 15:12:11 -07002176 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY && mHasGps) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002177 return;
2178 }
2179 mLocated = true;
2180 if (mNotMoving) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002181 stepIdleStateLocked("s:location");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002182 }
2183 }
2184
2185 void receivedGpsLocationLocked(Location location) {
2186 if (mState != STATE_LOCATING) {
2187 cancelLocatingLocked();
2188 return;
2189 }
2190 if (DEBUG) Slog.d(TAG, "GPS location: " + location);
2191 mLastGpsLocation = new Location(location);
2192 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY) {
2193 return;
2194 }
2195 mLocated = true;
2196 if (mNotMoving) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002197 stepIdleStateLocked("s:gps");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002198 }
2199 }
2200
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002201 void startMonitoringMotionLocked() {
2202 if (DEBUG) Slog.d(TAG, "startMonitoringMotionLocked()");
2203 if (mMotionSensor != null && !mMotionListener.active) {
2204 mMotionListener.registerLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002205 }
2206 }
2207
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002208 void stopMonitoringMotionLocked() {
2209 if (DEBUG) Slog.d(TAG, "stopMonitoringMotionLocked()");
2210 if (mMotionSensor != null && mMotionListener.active) {
2211 mMotionListener.unregisterLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002212 }
2213 }
2214
2215 void cancelAlarmLocked() {
2216 if (mNextAlarmTime != 0) {
2217 mNextAlarmTime = 0;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002218 mAlarmManager.cancel(mDeepAlarmListener);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002219 }
2220 }
2221
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002222 void cancelLightAlarmLocked() {
2223 if (mNextLightAlarmTime != 0) {
2224 mNextLightAlarmTime = 0;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002225 mAlarmManager.cancel(mLightAlarmListener);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002226 }
2227 }
2228
2229 void cancelLocatingLocked() {
2230 if (mLocating) {
2231 mLocationManager.removeUpdates(mGenericLocationListener);
2232 mLocationManager.removeUpdates(mGpsLocationListener);
2233 mLocating = false;
2234 }
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002235 }
2236
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002237 void cancelSensingTimeoutAlarmLocked() {
2238 if (mNextSensingTimeoutAlarmTime != 0) {
2239 mNextSensingTimeoutAlarmTime = 0;
2240 mAlarmManager.cancel(mSensingTimeoutAlarmListener);
2241 }
2242 }
2243
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002244 void scheduleAlarmLocked(long delay, boolean idleUntil) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002245 if (DEBUG) Slog.d(TAG, "scheduleAlarmLocked(" + delay + ", " + idleUntil + ")");
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002246 if (mMotionSensor == null) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07002247 // If there is no motion sensor on this device, then we won't schedule
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002248 // alarms, because we can't determine if the device is not moving. This effectively
Joe LaPenna23d681b2015-08-27 15:12:11 -07002249 // turns off normal execution of device idling, although it is still possible to
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002250 // manually poke it by pretending like the alarm is going off.
2251 return;
2252 }
2253 mNextAlarmTime = SystemClock.elapsedRealtime() + delay;
2254 if (idleUntil) {
2255 mAlarmManager.setIdleUntil(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002256 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002257 } else {
2258 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002259 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002260 }
2261 }
2262
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002263 void scheduleLightAlarmLocked(long delay) {
2264 if (DEBUG) Slog.d(TAG, "scheduleLightAlarmLocked(" + delay + ")");
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002265 mNextLightAlarmTime = SystemClock.elapsedRealtime() + delay;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002266 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002267 mNextLightAlarmTime, "DeviceIdleController.light", mLightAlarmListener, mHandler);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002268 }
2269
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002270 void scheduleSensingTimeoutAlarmLocked(long delay) {
2271 if (DEBUG) Slog.d(TAG, "scheduleSensingAlarmLocked(" + delay + ")");
2272 mNextSensingTimeoutAlarmTime = SystemClock.elapsedRealtime() + delay;
2273 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, mNextSensingTimeoutAlarmTime,
2274 "DeviceIdleController.sensing", mSensingTimeoutAlarmListener, mHandler);
2275 }
2276
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002277 private static int[] buildAppIdArray(ArrayMap<String, Integer> systemApps,
2278 ArrayMap<String, Integer> userApps, SparseBooleanArray outAppIds) {
2279 outAppIds.clear();
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002280 if (systemApps != null) {
2281 for (int i = 0; i < systemApps.size(); i++) {
2282 outAppIds.put(systemApps.valueAt(i), true);
2283 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002284 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002285 if (userApps != null) {
2286 for (int i = 0; i < userApps.size(); i++) {
2287 outAppIds.put(userApps.valueAt(i), true);
2288 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002289 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002290 int size = outAppIds.size();
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002291 int[] appids = new int[size];
2292 for (int i = 0; i < size; i++) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002293 appids[i] = outAppIds.keyAt(i);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002294 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002295 return appids;
2296 }
2297
2298 private void updateWhitelistAppIdsLocked() {
2299 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(mPowerSaveWhitelistAppsExceptIdle,
2300 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistExceptIdleAppIds);
2301 mPowerSaveWhitelistAllAppIdArray = buildAppIdArray(mPowerSaveWhitelistApps,
2302 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistAllAppIds);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002303 mPowerSaveWhitelistUserAppIdArray = buildAppIdArray(null,
2304 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistUserAppIds);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002305 if (mLocalPowerManager != null) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002306 if (DEBUG) {
2307 Slog.d(TAG, "Setting wakelock whitelist to "
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002308 + Arrays.toString(mPowerSaveWhitelistAllAppIdArray));
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002309 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002310 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002311 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002312 if (mLocalAlarmManager != null) {
2313 if (DEBUG) {
2314 Slog.d(TAG, "Setting alarm whitelist to "
2315 + Arrays.toString(mPowerSaveWhitelistUserAppIdArray));
2316 }
2317 mLocalAlarmManager.setDeviceIdleUserWhitelist(mPowerSaveWhitelistUserAppIdArray);
2318 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002319 }
2320
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002321 private void updateTempWhitelistAppIdsLocked() {
2322 final int size = mTempWhitelistAppIdEndTimes.size();
2323 if (mTempWhitelistAppIdArray.length != size) {
2324 mTempWhitelistAppIdArray = new int[size];
2325 }
2326 for (int i = 0; i < size; i++) {
2327 mTempWhitelistAppIdArray[i] = mTempWhitelistAppIdEndTimes.keyAt(i);
2328 }
2329 if (mLocalPowerManager != null) {
2330 if (DEBUG) {
2331 Slog.d(TAG, "Setting wakelock temp whitelist to "
2332 + Arrays.toString(mTempWhitelistAppIdArray));
2333 }
2334 mLocalPowerManager.setDeviceIdleTempWhitelist(mTempWhitelistAppIdArray);
2335 }
2336 }
2337
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002338 private void reportPowerSaveWhitelistChangedLocked() {
2339 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
2340 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Xiaohui Chene4de5a02015-09-22 15:33:31 -07002341 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002342 }
2343
2344 private void reportTempWhitelistChangedLocked() {
2345 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_TEMP_WHITELIST_CHANGED);
2346 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Xiaohui Chene4de5a02015-09-22 15:33:31 -07002347 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002348 }
2349
2350 void readConfigFileLocked() {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002351 if (DEBUG) Slog.d(TAG, "Reading config from " + mConfigFile.getBaseFile());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002352 mPowerSaveWhitelistUserApps.clear();
2353 FileInputStream stream;
2354 try {
2355 stream = mConfigFile.openRead();
2356 } catch (FileNotFoundException e) {
2357 return;
2358 }
2359 try {
2360 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002361 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002362 readConfigFileLocked(parser);
2363 } catch (XmlPullParserException e) {
2364 } finally {
2365 try {
2366 stream.close();
2367 } catch (IOException e) {
2368 }
2369 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002370 }
2371
2372 private void readConfigFileLocked(XmlPullParser parser) {
2373 final PackageManager pm = getContext().getPackageManager();
2374
2375 try {
2376 int type;
2377 while ((type = parser.next()) != XmlPullParser.START_TAG
2378 && type != XmlPullParser.END_DOCUMENT) {
2379 ;
2380 }
2381
2382 if (type != XmlPullParser.START_TAG) {
2383 throw new IllegalStateException("no start tag found");
2384 }
2385
2386 int outerDepth = parser.getDepth();
2387 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2388 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2389 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2390 continue;
2391 }
2392
2393 String tagName = parser.getName();
2394 if (tagName.equals("wl")) {
2395 String name = parser.getAttributeValue(null, "n");
2396 if (name != null) {
2397 try {
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07002398 ApplicationInfo ai = pm.getApplicationInfo(name,
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07002399 PackageManager.MATCH_UNINSTALLED_PACKAGES);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002400 mPowerSaveWhitelistUserApps.put(ai.packageName,
2401 UserHandle.getAppId(ai.uid));
2402 } catch (PackageManager.NameNotFoundException e) {
2403 }
2404 }
2405 } else {
2406 Slog.w(TAG, "Unknown element under <config>: "
2407 + parser.getName());
2408 XmlUtils.skipCurrentTag(parser);
2409 }
2410 }
2411
2412 } catch (IllegalStateException e) {
2413 Slog.w(TAG, "Failed parsing config " + e);
2414 } catch (NullPointerException e) {
2415 Slog.w(TAG, "Failed parsing config " + e);
2416 } catch (NumberFormatException e) {
2417 Slog.w(TAG, "Failed parsing config " + e);
2418 } catch (XmlPullParserException e) {
2419 Slog.w(TAG, "Failed parsing config " + e);
2420 } catch (IOException e) {
2421 Slog.w(TAG, "Failed parsing config " + e);
2422 } catch (IndexOutOfBoundsException e) {
2423 Slog.w(TAG, "Failed parsing config " + e);
2424 }
2425 }
2426
2427 void writeConfigFileLocked() {
2428 mHandler.removeMessages(MSG_WRITE_CONFIG);
2429 mHandler.sendEmptyMessageDelayed(MSG_WRITE_CONFIG, 5000);
2430 }
2431
2432 void handleWriteConfigFile() {
2433 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
2434
2435 try {
2436 synchronized (this) {
2437 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002438 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002439 writeConfigFileLocked(out);
2440 }
2441 } catch (IOException e) {
2442 }
2443
2444 synchronized (mConfigFile) {
2445 FileOutputStream stream = null;
2446 try {
2447 stream = mConfigFile.startWrite();
2448 memStream.writeTo(stream);
2449 stream.flush();
2450 FileUtils.sync(stream);
2451 stream.close();
2452 mConfigFile.finishWrite(stream);
2453 } catch (IOException e) {
2454 Slog.w(TAG, "Error writing config file", e);
2455 mConfigFile.failWrite(stream);
2456 }
2457 }
2458 }
2459
2460 void writeConfigFileLocked(XmlSerializer out) throws IOException {
2461 out.startDocument(null, true);
2462 out.startTag(null, "config");
2463 for (int i=0; i<mPowerSaveWhitelistUserApps.size(); i++) {
2464 String name = mPowerSaveWhitelistUserApps.keyAt(i);
2465 out.startTag(null, "wl");
2466 out.attribute(null, "n", name);
2467 out.endTag(null, "wl");
2468 }
2469 out.endTag(null, "config");
2470 out.endDocument();
2471 }
2472
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002473 static void dumpHelp(PrintWriter pw) {
2474 pw.println("Device idle controller (deviceidle) commands:");
2475 pw.println(" help");
2476 pw.println(" Print this help text.");
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002477 pw.println(" step [light|deep]");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002478 pw.println(" Immediately step to next state, without waiting for alarm.");
Dianne Hackborn88c41352016-04-07 15:18:58 -07002479 pw.println(" force-idle [light|deep]");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002480 pw.println(" Force directly into idle mode, regardless of other device state.");
Dianne Hackborn88c41352016-04-07 15:18:58 -07002481 pw.println(" force-inactive");
2482 pw.println(" Force to be inactive, ready to freely step idle states.");
2483 pw.println(" unforce");
2484 pw.println(" Resume normal functioning after force-idle or force-inactive.");
2485 pw.println(" get [light|deep|force|screen|charging|network]");
2486 pw.println(" Retrieve the current given state.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002487 pw.println(" disable [light|deep|all]");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002488 pw.println(" Completely disable device idle mode.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002489 pw.println(" enable [light|deep|all]");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002490 pw.println(" Re-enable device idle mode after it had previously been disabled.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002491 pw.println(" enabled [light|deep|all]");
Dianne Hackborn92617032015-06-19 15:32:19 -07002492 pw.println(" Print 1 if device idle mode is currently enabled, else 0.");
Dianne Hackborn1b139682015-07-06 15:13:37 -07002493 pw.println(" whitelist");
2494 pw.println(" Print currently whitelisted apps.");
Dianne Hackborn92617032015-06-19 15:32:19 -07002495 pw.println(" whitelist [package ...]");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002496 pw.println(" Add (prefix with +) or remove (prefix with -) packages.");
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002497 pw.println(" tempwhitelist");
2498 pw.println(" Print packages that are temporarily whitelisted.");
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002499 pw.println(" tempwhitelist [-u] [package ..]");
Dianne Hackborn92617032015-06-19 15:32:19 -07002500 pw.println(" Temporarily place packages in whitelist for 10 seconds.");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002501 }
2502
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002503 class Shell extends ShellCommand {
2504 int userId = UserHandle.USER_SYSTEM;
2505
2506 @Override
2507 public int onCommand(String cmd) {
2508 return onShellCommand(this, cmd);
2509 }
2510
2511 @Override
2512 public void onHelp() {
2513 PrintWriter pw = getOutPrintWriter();
2514 dumpHelp(pw);
2515 }
2516 }
2517
2518 int onShellCommand(Shell shell, String cmd) {
2519 PrintWriter pw = shell.getOutPrintWriter();
2520 if ("step".equals(cmd)) {
2521 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2522 null);
2523 synchronized (this) {
2524 long token = Binder.clearCallingIdentity();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002525 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002526 try {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002527 if (arg == null || "deep".equals(arg)) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002528 stepIdleStateLocked("s:shell");
2529 pw.print("Stepped to deep: ");
2530 pw.println(stateToString(mState));
2531 } else if ("light".equals(arg)) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002532 stepLightIdleStateLocked("s:shell");
2533 pw.print("Stepped to light: "); pw.println(lightStateToString(mLightState));
2534 } else {
2535 pw.println("Unknown idle mode: " + arg);
2536 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002537 } finally {
2538 Binder.restoreCallingIdentity(token);
2539 }
2540 }
2541 } else if ("force-idle".equals(cmd)) {
2542 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2543 null);
2544 synchronized (this) {
2545 long token = Binder.clearCallingIdentity();
Dianne Hackborn88c41352016-04-07 15:18:58 -07002546 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002547 try {
Dianne Hackborn88c41352016-04-07 15:18:58 -07002548 if (arg == null || "deep".equals(arg)) {
2549 if (!mDeepEnabled) {
2550 pw.println("Unable to go deep idle; not enabled");
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002551 return -1;
2552 }
Dianne Hackborn88c41352016-04-07 15:18:58 -07002553 mForceIdle = true;
2554 becomeInactiveIfAppropriateLocked();
2555 int curState = mState;
2556 while (curState != STATE_IDLE) {
2557 stepIdleStateLocked("s:shell");
2558 if (curState == mState) {
2559 pw.print("Unable to go deep idle; stopped at ");
2560 pw.println(stateToString(mState));
2561 exitForceIdleLocked();
2562 return -1;
2563 }
2564 curState = mState;
2565 }
2566 pw.println("Now forced in to deep idle mode");
2567 } else if ("light".equals(arg)) {
2568 mForceIdle = true;
2569 becomeInactiveIfAppropriateLocked();
2570 int curLightState = mLightState;
2571 while (curLightState != LIGHT_STATE_IDLE) {
2572 stepIdleStateLocked("s:shell");
2573 if (curLightState == mLightState) {
2574 pw.print("Unable to go light idle; stopped at ");
2575 pw.println(lightStateToString(mLightState));
2576 exitForceIdleLocked();
2577 return -1;
2578 }
2579 curLightState = mLightState;
2580 }
2581 pw.println("Now forced in to light idle mode");
2582 } else {
2583 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002584 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002585 } finally {
2586 Binder.restoreCallingIdentity(token);
2587 }
2588 }
Dianne Hackborn88c41352016-04-07 15:18:58 -07002589 } else if ("force-inactive".equals(cmd)) {
2590 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2591 null);
2592 synchronized (this) {
2593 long token = Binder.clearCallingIdentity();
2594 try {
2595 mForceIdle = true;
2596 becomeInactiveIfAppropriateLocked();
2597 pw.print("Light state: ");
2598 pw.print(lightStateToString(mLightState));
2599 pw.print(", deep state: ");
2600 pw.println(stateToString(mState));
2601 } finally {
2602 Binder.restoreCallingIdentity(token);
2603 }
2604 }
2605 } else if ("unforce".equals(cmd)) {
2606 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2607 null);
2608 synchronized (this) {
2609 long token = Binder.clearCallingIdentity();
2610 try {
2611 exitForceIdleLocked();
2612 pw.print("Light state: ");
2613 pw.print(lightStateToString(mLightState));
2614 pw.print(", deep state: ");
2615 pw.println(stateToString(mState));
2616 } finally {
2617 Binder.restoreCallingIdentity(token);
2618 }
2619 }
2620 } else if ("get".equals(cmd)) {
2621 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2622 null);
2623 synchronized (this) {
2624 String arg = shell.getNextArg();
2625 if (arg != null) {
2626 long token = Binder.clearCallingIdentity();
2627 try {
2628 switch (arg) {
2629 case "light": pw.println(lightStateToString(mLightState)); break;
2630 case "deep": pw.println(stateToString(mState)); break;
2631 case "force": pw.println(mForceIdle); break;
2632 case "screen": pw.println(mScreenOn); break;
2633 case "charging": pw.println(mCharging); break;
2634 case "network": pw.println(mNetworkConnected); break;
2635 default: pw.println("Unknown get option: " + arg); break;
2636 }
2637 } finally {
2638 Binder.restoreCallingIdentity(token);
2639 }
2640 } else {
2641 pw.println("Argument required");
2642 }
2643 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002644 } else if ("disable".equals(cmd)) {
2645 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2646 null);
2647 synchronized (this) {
2648 long token = Binder.clearCallingIdentity();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002649 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002650 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002651 boolean becomeActive = false;
2652 boolean valid = false;
2653 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
2654 valid = true;
2655 if (mDeepEnabled) {
2656 mDeepEnabled = false;
2657 becomeActive = true;
2658 pw.println("Deep idle mode disabled");
2659 }
2660 }
2661 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
2662 valid = true;
2663 if (mLightEnabled) {
2664 mLightEnabled = false;
2665 becomeActive = true;
2666 pw.println("Light idle mode disabled");
2667 }
2668 }
2669 if (becomeActive) {
2670 becomeActiveLocked((arg == null ? "all" : arg) + "-disabled",
2671 Process.myUid());
2672 }
2673 if (!valid) {
2674 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002675 }
2676 } finally {
2677 Binder.restoreCallingIdentity(token);
2678 }
2679 }
2680 } else if ("enable".equals(cmd)) {
2681 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2682 null);
2683 synchronized (this) {
2684 long token = Binder.clearCallingIdentity();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002685 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002686 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002687 boolean becomeInactive = false;
2688 boolean valid = false;
2689 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
2690 valid = true;
2691 if (!mDeepEnabled) {
2692 mDeepEnabled = true;
2693 becomeInactive = true;
2694 pw.println("Deep idle mode enabled");
2695 }
2696 }
2697 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
2698 valid = true;
2699 if (!mLightEnabled) {
2700 mLightEnabled = true;
2701 becomeInactive = true;
2702 pw.println("Light idle mode enable");
2703 }
2704 }
2705 if (becomeInactive) {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002706 becomeInactiveIfAppropriateLocked();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002707 }
2708 if (!valid) {
2709 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002710 }
2711 } finally {
2712 Binder.restoreCallingIdentity(token);
2713 }
2714 }
2715 } else if ("enabled".equals(cmd)) {
2716 synchronized (this) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002717 String arg = shell.getNextArg();
2718 if (arg == null || "all".equals(arg)) {
2719 pw.println(mDeepEnabled && mLightEnabled ? "1" : 0);
2720 } else if ("deep".equals(arg)) {
2721 pw.println(mDeepEnabled ? "1" : 0);
2722 } else if ("light".equals(arg)) {
2723 pw.println(mLightEnabled ? "1" : 0);
2724 } else {
2725 pw.println("Unknown idle mode: " + arg);
2726 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002727 }
2728 } else if ("whitelist".equals(cmd)) {
2729 long token = Binder.clearCallingIdentity();
2730 try {
2731 String arg = shell.getNextArg();
2732 if (arg != null) {
2733 getContext().enforceCallingOrSelfPermission(
2734 android.Manifest.permission.DEVICE_POWER, null);
2735 do {
2736 if (arg.length() < 1 || (arg.charAt(0) != '-'
Felipe Lemef8a46232016-02-10 13:51:54 -08002737 && arg.charAt(0) != '+' && arg.charAt(0) != '=')) {
2738 pw.println("Package must be prefixed with +, -, or =: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002739 return -1;
2740 }
2741 char op = arg.charAt(0);
2742 String pkg = arg.substring(1);
2743 if (op == '+') {
2744 if (addPowerSaveWhitelistAppInternal(pkg)) {
2745 pw.println("Added: " + pkg);
2746 } else {
2747 pw.println("Unknown package: " + pkg);
2748 }
Felipe Lemef8a46232016-02-10 13:51:54 -08002749 } else if (op == '-') {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002750 if (removePowerSaveWhitelistAppInternal(pkg)) {
2751 pw.println("Removed: " + pkg);
2752 }
Felipe Lemef8a46232016-02-10 13:51:54 -08002753 } else {
2754 pw.println(getPowerSaveWhitelistAppInternal(pkg));
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002755 }
2756 } while ((arg=shell.getNextArg()) != null);
2757 } else {
2758 synchronized (this) {
2759 for (int j=0; j<mPowerSaveWhitelistAppsExceptIdle.size(); j++) {
2760 pw.print("system-excidle,");
2761 pw.print(mPowerSaveWhitelistAppsExceptIdle.keyAt(j));
2762 pw.print(",");
2763 pw.println(mPowerSaveWhitelistAppsExceptIdle.valueAt(j));
2764 }
2765 for (int j=0; j<mPowerSaveWhitelistApps.size(); j++) {
2766 pw.print("system,");
2767 pw.print(mPowerSaveWhitelistApps.keyAt(j));
2768 pw.print(",");
2769 pw.println(mPowerSaveWhitelistApps.valueAt(j));
2770 }
2771 for (int j=0; j<mPowerSaveWhitelistUserApps.size(); j++) {
2772 pw.print("user,");
2773 pw.print(mPowerSaveWhitelistUserApps.keyAt(j));
2774 pw.print(",");
2775 pw.println(mPowerSaveWhitelistUserApps.valueAt(j));
2776 }
2777 }
2778 }
2779 } finally {
2780 Binder.restoreCallingIdentity(token);
2781 }
2782 } else if ("tempwhitelist".equals(cmd)) {
2783 String opt;
2784 while ((opt=shell.getNextOption()) != null) {
2785 if ("-u".equals(opt)) {
2786 opt = shell.getNextArg();
2787 if (opt == null) {
2788 pw.println("-u requires a user number");
2789 return -1;
2790 }
2791 shell.userId = Integer.parseInt(opt);
2792 }
2793 }
2794 String arg = shell.getNextArg();
2795 if (arg != null) {
2796 try {
2797 addPowerSaveTempWhitelistAppChecked(arg, 10000L, shell.userId, "shell");
2798 } catch (RemoteException re) {
2799 pw.println("Failed: " + re);
2800 }
2801 } else {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002802 dumpTempWhitelistSchedule(pw, false);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002803 }
2804 } else {
2805 return shell.handleDefaultCommands(cmd);
2806 }
2807 return 0;
2808 }
2809
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002810 void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2811 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2812 != PackageManager.PERMISSION_GRANTED) {
2813 pw.println("Permission Denial: can't dump DeviceIdleController from from pid="
2814 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2815 + " without permission " + android.Manifest.permission.DUMP);
2816 return;
2817 }
2818
2819 if (args != null) {
Xiaohui Chen7c696362015-09-16 09:56:14 -07002820 int userId = UserHandle.USER_SYSTEM;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002821 for (int i=0; i<args.length; i++) {
2822 String arg = args[i];
2823 if ("-h".equals(arg)) {
2824 dumpHelp(pw);
2825 return;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002826 } else if ("-u".equals(arg)) {
2827 i++;
2828 if (i < args.length) {
2829 arg = args[i];
2830 userId = Integer.parseInt(arg);
2831 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002832 } else if ("-a".equals(arg)) {
2833 // Ignore, we always dump all.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002834 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
2835 pw.println("Unknown option: " + arg);
2836 return;
2837 } else {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002838 Shell shell = new Shell();
2839 shell.userId = userId;
2840 String[] newArgs = new String[args.length-i];
2841 System.arraycopy(args, i, newArgs, 0, args.length-i);
2842 shell.exec(mBinderService, null, fd, null, newArgs, new ResultReceiver(null));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002843 return;
2844 }
2845 }
2846 }
2847
2848 synchronized (this) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002849 mConstants.dump(pw);
2850
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002851 if (mEventCmds[0] != EVENT_NULL) {
2852 pw.println(" Idling history:");
2853 long now = SystemClock.elapsedRealtime();
2854 for (int i=EVENT_BUFFER_SIZE-1; i>=0; i--) {
2855 int cmd = mEventCmds[i];
2856 if (cmd == EVENT_NULL) {
2857 continue;
2858 }
2859 String label;
2860 switch (mEventCmds[i]) {
2861 case EVENT_NORMAL: label = " normal"; break;
2862 case EVENT_LIGHT_IDLE: label = " light-idle"; break;
2863 case EVENT_LIGHT_MAINTENANCE: label = "light-maint"; break;
Dianne Hackbornb6843652016-02-22 12:20:13 -08002864 case EVENT_DEEP_IDLE: label = " deep-idle"; break;
2865 case EVENT_DEEP_MAINTENANCE: label = " deep-maint"; break;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002866 default: label = " ??"; break;
2867 }
2868 pw.print(" ");
2869 pw.print(label);
2870 pw.print(": ");
2871 TimeUtils.formatDuration(mEventTimes[i], now, pw);;
2872 pw.println();
2873 }
2874 }
2875
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002876 int size = mPowerSaveWhitelistAppsExceptIdle.size();
2877 if (size > 0) {
2878 pw.println(" Whitelist (except idle) system apps:");
2879 for (int i = 0; i < size; i++) {
2880 pw.print(" ");
2881 pw.println(mPowerSaveWhitelistAppsExceptIdle.keyAt(i));
2882 }
2883 }
2884 size = mPowerSaveWhitelistApps.size();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002885 if (size > 0) {
2886 pw.println(" Whitelist system apps:");
2887 for (int i = 0; i < size; i++) {
2888 pw.print(" ");
2889 pw.println(mPowerSaveWhitelistApps.keyAt(i));
2890 }
2891 }
2892 size = mPowerSaveWhitelistUserApps.size();
2893 if (size > 0) {
2894 pw.println(" Whitelist user apps:");
2895 for (int i = 0; i < size; i++) {
2896 pw.print(" ");
2897 pw.println(mPowerSaveWhitelistUserApps.keyAt(i));
2898 }
2899 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002900 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2901 if (size > 0) {
2902 pw.println(" Whitelist (except idle) all app ids:");
2903 for (int i = 0; i < size; i++) {
2904 pw.print(" ");
2905 pw.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2906 pw.println();
2907 }
2908 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002909 size = mPowerSaveWhitelistUserAppIds.size();
2910 if (size > 0) {
2911 pw.println(" Whitelist user app ids:");
2912 for (int i = 0; i < size; i++) {
2913 pw.print(" ");
2914 pw.print(mPowerSaveWhitelistUserAppIds.keyAt(i));
2915 pw.println();
2916 }
2917 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002918 size = mPowerSaveWhitelistAllAppIds.size();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002919 if (size > 0) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002920 pw.println(" Whitelist all app ids:");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002921 for (int i = 0; i < size; i++) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002922 pw.print(" ");
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002923 pw.print(mPowerSaveWhitelistAllAppIds.keyAt(i));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002924 pw.println();
2925 }
2926 }
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002927 dumpTempWhitelistSchedule(pw, true);
2928
Dianne Hackborna750a632015-06-16 17:18:23 -07002929 size = mTempWhitelistAppIdArray != null ? mTempWhitelistAppIdArray.length : 0;
2930 if (size > 0) {
2931 pw.println(" Temp whitelist app ids:");
2932 for (int i = 0; i < size; i++) {
2933 pw.print(" ");
2934 pw.print(mTempWhitelistAppIdArray[i]);
2935 pw.println();
2936 }
2937 }
Adam Lesinski31c05d12015-06-09 17:34:04 -07002938
Dianne Hackbornb6843652016-02-22 12:20:13 -08002939 pw.print(" mLightEnabled="); pw.print(mLightEnabled);
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002940 pw.print(" mDeepEnabled="); pw.println(mDeepEnabled);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002941 pw.print(" mForceIdle="); pw.println(mForceIdle);
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002942 pw.print(" mMotionSensor="); pw.println(mMotionSensor);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002943 pw.print(" mCurDisplay="); pw.println(mCurDisplay);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002944 pw.print(" mScreenOn="); pw.println(mScreenOn);
Dianne Hackborn88c41352016-04-07 15:18:58 -07002945 pw.print(" mNetworkConnected="); pw.println(mNetworkConnected);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002946 pw.print(" mCharging="); pw.println(mCharging);
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002947 pw.print(" mMotionActive="); pw.println(mMotionListener.active);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002948 pw.print(" mNotMoving="); pw.println(mNotMoving);
Joe LaPenna23d681b2015-08-27 15:12:11 -07002949 pw.print(" mLocating="); pw.print(mLocating); pw.print(" mHasGps=");
2950 pw.print(mHasGps); pw.print(" mHasNetwork=");
2951 pw.print(mHasNetworkLocation); pw.print(" mLocated="); pw.println(mLocated);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002952 if (mLastGenericLocation != null) {
2953 pw.print(" mLastGenericLocation="); pw.println(mLastGenericLocation);
2954 }
2955 if (mLastGpsLocation != null) {
2956 pw.print(" mLastGpsLocation="); pw.println(mLastGpsLocation);
2957 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002958 pw.print(" mState="); pw.print(stateToString(mState));
2959 pw.print(" mLightState=");
2960 pw.println(lightStateToString(mLightState));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002961 pw.print(" mInactiveTimeout="); TimeUtils.formatDuration(mInactiveTimeout, pw);
2962 pw.println();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002963 if (mActiveIdleOpCount != 0) {
2964 pw.print(" mActiveIdleOpCount="); pw.println(mActiveIdleOpCount);
2965 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002966 if (mNextAlarmTime != 0) {
2967 pw.print(" mNextAlarmTime=");
2968 TimeUtils.formatDuration(mNextAlarmTime, SystemClock.elapsedRealtime(), pw);
2969 pw.println();
2970 }
2971 if (mNextIdlePendingDelay != 0) {
2972 pw.print(" mNextIdlePendingDelay=");
2973 TimeUtils.formatDuration(mNextIdlePendingDelay, pw);
2974 pw.println();
2975 }
2976 if (mNextIdleDelay != 0) {
2977 pw.print(" mNextIdleDelay=");
2978 TimeUtils.formatDuration(mNextIdleDelay, pw);
2979 pw.println();
2980 }
Dianne Hackborn953fc942016-03-29 15:36:24 -07002981 if (mNextLightIdleDelay != 0) {
2982 pw.print(" mNextIdleDelay=");
2983 TimeUtils.formatDuration(mNextLightIdleDelay, pw);
2984 pw.println();
2985 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002986 if (mNextLightAlarmTime != 0) {
2987 pw.print(" mNextLightAlarmTime=");
2988 TimeUtils.formatDuration(mNextLightAlarmTime, SystemClock.elapsedRealtime(), pw);
2989 pw.println();
2990 }
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002991 if (mCurIdleBudget != 0) {
2992 pw.print(" mCurIdleBudget=");
2993 TimeUtils.formatDuration(mCurIdleBudget, pw);
2994 pw.println();
2995 }
2996 if (mMaintenanceStartTime != 0) {
2997 pw.print(" mMaintenanceStartTime=");
2998 TimeUtils.formatDuration(mMaintenanceStartTime, SystemClock.elapsedRealtime(), pw);
2999 pw.println();
3000 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003001 if (mJobsActive) {
3002 pw.print(" mJobsActive="); pw.println(mJobsActive);
3003 }
3004 if (mAlarmsActive) {
3005 pw.print(" mAlarmsActive="); pw.println(mAlarmsActive);
3006 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003007 }
3008 }
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003009
3010 void dumpTempWhitelistSchedule(PrintWriter pw, boolean printTitle) {
3011 final int size = mTempWhitelistAppIdEndTimes.size();
3012 if (size > 0) {
3013 String prefix = "";
3014 if (printTitle) {
3015 pw.println(" Temp whitelist schedule:");
3016 prefix = " ";
3017 }
3018 final long timeNow = SystemClock.elapsedRealtime();
3019 for (int i = 0; i < size; i++) {
3020 pw.print(prefix);
3021 pw.print("UID=");
3022 pw.print(mTempWhitelistAppIdEndTimes.keyAt(i));
3023 pw.print(": ");
3024 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.valueAt(i);
3025 TimeUtils.formatDuration(entry.first.value, timeNow, pw);
3026 pw.print(" - ");
3027 pw.println(entry.second);
3028 }
3029 }
3030 }
3031 }