blob: 6b73fec8c9201a8b4d0c1e5c3e24f7d530030824 [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;
52import android.os.IDeviceIdleController;
Yao Chenca5edbb2016-01-13 14:44:36 -080053import android.os.IMaintenanceActivityListener;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070054import android.os.Looper;
55import android.os.Message;
56import android.os.PowerManager;
57import android.os.PowerManagerInternal;
Dianne Hackbornb6683c42015-06-18 17:40:33 -070058import android.os.Process;
Yao Chenca5edbb2016-01-13 14:44:36 -080059import android.os.RemoteCallbackList;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070060import android.os.RemoteException;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -070061import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070062import android.os.ServiceManager;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -070063import android.os.ShellCommand;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070064import android.os.SystemClock;
65import android.os.UserHandle;
Adam Lesinski31c05d12015-06-09 17:34:04 -070066import android.provider.Settings;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070067import android.util.ArrayMap;
68import android.util.ArraySet;
Adam Lesinski31c05d12015-06-09 17:34:04 -070069import android.util.KeyValueListParser;
Dianne Hackbornfd854ee2015-07-13 18:00:37 -070070import android.util.MutableLong;
71import android.util.Pair;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070072import android.util.Slog;
Dianne Hackbornfd854ee2015-07-13 18:00:37 -070073import android.util.SparseArray;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070074import android.util.SparseBooleanArray;
75import android.util.TimeUtils;
76import android.util.Xml;
77import android.view.Display;
Amith Yamasani520d8f22015-05-08 16:36:21 -070078
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070079import com.android.internal.app.IBatteryStats;
80import com.android.internal.os.AtomicFile;
81import com.android.internal.os.BackgroundThread;
82import com.android.internal.util.FastXmlSerializer;
83import com.android.internal.util.XmlUtils;
84import com.android.server.am.BatteryStatsService;
Amith Yamasani520d8f22015-05-08 16:36:21 -070085
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070086import org.xmlpull.v1.XmlPullParser;
87import org.xmlpull.v1.XmlPullParserException;
88import org.xmlpull.v1.XmlSerializer;
89
90import java.io.ByteArrayOutputStream;
91import java.io.File;
92import java.io.FileDescriptor;
93import java.io.FileInputStream;
94import java.io.FileNotFoundException;
95import java.io.FileOutputStream;
96import java.io.IOException;
97import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010098import java.nio.charset.StandardCharsets;
Amith Yamasaniaf575b92015-05-29 15:35:26 -070099import java.util.Arrays;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700100
101/**
102 * Keeps track of device idleness and drives low power mode based on that.
103 */
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700104public class DeviceIdleController extends SystemService
105 implements AnyMotionDetector.DeviceIdleCallback {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700106 private static final String TAG = "DeviceIdleController";
107
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700108 private static final boolean DEBUG = false;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700109
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700110 private static final boolean COMPRESS_TIME = false;
Amith Yamasani520d8f22015-05-08 16:36:21 -0700111
Dianne Hackborn953fc942016-03-29 15:36:24 -0700112 private static final int EVENT_BUFFER_SIZE = 100;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800113
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700114 private AlarmManager mAlarmManager;
115 private IBatteryStats mBatteryStats;
116 private PowerManagerInternal mLocalPowerManager;
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700117 private PowerManager mPowerManager;
Dianne Hackborn88c41352016-04-07 15:18:58 -0700118 private ConnectivityService mConnectivityService;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -0800119 private AlarmManagerService.LocalService mLocalAlarmManager;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700120 private INetworkPolicyManager mNetworkPolicyManager;
121 private DisplayManager mDisplayManager;
122 private SensorManager mSensorManager;
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700123 private Sensor mMotionSensor;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700124 private LocationManager mLocationManager;
125 private LocationRequest mLocationRequest;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700126 private Intent mIdleIntent;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700127 private Intent mLightIdleIntent;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700128 private Display mCurDisplay;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700129 private AnyMotionDetector mAnyMotionDetector;
Dianne Hackbornb6843652016-02-22 12:20:13 -0800130 private boolean mLightEnabled;
131 private boolean mDeepEnabled;
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700132 private boolean mForceIdle;
Dianne Hackborn88c41352016-04-07 15:18:58 -0700133 private boolean mNetworkConnected;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700134 private boolean mScreenOn;
135 private boolean mCharging;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700136 private boolean mNotMoving;
137 private boolean mLocating;
138 private boolean mLocated;
Joe LaPenna23d681b2015-08-27 15:12:11 -0700139 private boolean mHasGps;
140 private boolean mHasNetworkLocation;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700141 private Location mLastGenericLocation;
142 private Location mLastGpsLocation;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700143
144 /** Device is currently active. */
145 private static final int STATE_ACTIVE = 0;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700146 /** Device is inactive (screen off, no motion) and we are waiting to for idle. */
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700147 private static final int STATE_INACTIVE = 1;
148 /** Device is past the initial inactive period, and waiting for the next idle period. */
149 private static final int STATE_IDLE_PENDING = 2;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700150 /** Device is currently sensing motion. */
151 private static final int STATE_SENSING = 3;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700152 /** Device is currently finding location (and may still be sensing). */
153 private static final int STATE_LOCATING = 4;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700154 /** Device is in the idle state, trying to stay asleep as much as possible. */
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700155 private static final int STATE_IDLE = 5;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700156 /** Device is in the idle state, but temporarily out of idle to do regular maintenance. */
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700157 private static final int STATE_IDLE_MAINTENANCE = 6;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700158 private static String stateToString(int state) {
159 switch (state) {
160 case STATE_ACTIVE: return "ACTIVE";
161 case STATE_INACTIVE: return "INACTIVE";
162 case STATE_IDLE_PENDING: return "IDLE_PENDING";
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700163 case STATE_SENSING: return "SENSING";
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700164 case STATE_LOCATING: return "LOCATING";
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700165 case STATE_IDLE: return "IDLE";
166 case STATE_IDLE_MAINTENANCE: return "IDLE_MAINTENANCE";
167 default: return Integer.toString(state);
168 }
169 }
170
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700171 /** Device is currently active. */
172 private static final int LIGHT_STATE_ACTIVE = 0;
173 /** Device is inactive (screen off) and we are waiting to for the first light idle. */
174 private static final int LIGHT_STATE_INACTIVE = 1;
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700175 /** Device is about to go idle for the first time, wait for current work to complete. */
176 private static final int LIGHT_STATE_PRE_IDLE = 3;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700177 /** Device is in the light idle state, trying to stay asleep as much as possible. */
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700178 private static final int LIGHT_STATE_IDLE = 4;
Dianne Hackborn88c41352016-04-07 15:18:58 -0700179 /** Device is in the light idle state, we want to go in to idle maintenance but are
180 * waiting for network connectivity before doing so. */
181 private static final int LIGHT_STATE_WAITING_FOR_NETWORK = 5;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700182 /** Device is in the light idle state, but temporarily out of idle to do regular maintenance. */
Dianne Hackborn88c41352016-04-07 15:18:58 -0700183 private static final int LIGHT_STATE_IDLE_MAINTENANCE = 6;
Dianne Hackbornb6843652016-02-22 12:20:13 -0800184 /** Device light idle state is overriden, now applying deep doze state. */
Dianne Hackborn88c41352016-04-07 15:18:58 -0700185 private static final int LIGHT_STATE_OVERRIDE = 7;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700186 private static String lightStateToString(int state) {
187 switch (state) {
188 case LIGHT_STATE_ACTIVE: return "ACTIVE";
189 case LIGHT_STATE_INACTIVE: return "INACTIVE";
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700190 case LIGHT_STATE_PRE_IDLE: return "PRE_IDLE";
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700191 case LIGHT_STATE_IDLE: return "IDLE";
Dianne Hackborn88c41352016-04-07 15:18:58 -0700192 case LIGHT_STATE_WAITING_FOR_NETWORK: return "WAITING_FOR_NETWORK";
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700193 case LIGHT_STATE_IDLE_MAINTENANCE: return "IDLE_MAINTENANCE";
194 case LIGHT_STATE_OVERRIDE: return "OVERRIDE";
195 default: return Integer.toString(state);
196 }
197 }
198
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700199 private int mState;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700200 private int mLightState;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700201
202 private long mInactiveTimeout;
203 private long mNextAlarmTime;
204 private long mNextIdlePendingDelay;
205 private long mNextIdleDelay;
Dianne Hackborn953fc942016-03-29 15:36:24 -0700206 private long mNextLightIdleDelay;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700207 private long mNextLightAlarmTime;
Kevin Gabayan92f15e62016-04-04 17:52:22 -0700208 private long mNextSensingTimeoutAlarmTime;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800209 private long mCurIdleBudget;
210 private long mMaintenanceStartTime;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700211
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800212 private int mActiveIdleOpCount;
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700213 private PowerManager.WakeLock mActiveIdleWakeLock;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800214 private boolean mJobsActive;
215 private boolean mAlarmsActive;
Yao Chenca5edbb2016-01-13 14:44:36 -0800216 private boolean mReportedMaintenanceActivity;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800217
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700218 public final AtomicFile mConfigFile;
219
Yao Chenca5edbb2016-01-13 14:44:36 -0800220 private final RemoteCallbackList<IMaintenanceActivityListener> mMaintenanceActivityListeners =
221 new RemoteCallbackList<IMaintenanceActivityListener>();
222
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700223 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700224 * Package names the system has white-listed to opt out of power save restrictions,
225 * except for device idle mode.
226 */
227 private final ArrayMap<String, Integer> mPowerSaveWhitelistAppsExceptIdle = new ArrayMap<>();
228
229 /**
230 * Package names the system has white-listed to opt out of power save restrictions for
231 * all modes.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700232 */
233 private final ArrayMap<String, Integer> mPowerSaveWhitelistApps = new ArrayMap<>();
234
235 /**
236 * Package names the user has white-listed to opt out of power save restrictions.
237 */
238 private final ArrayMap<String, Integer> mPowerSaveWhitelistUserApps = new ArrayMap<>();
239
240 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700241 * App IDs of built-in system apps that have been white-listed except for idle modes.
242 */
243 private final SparseBooleanArray mPowerSaveWhitelistSystemAppIdsExceptIdle
244 = new SparseBooleanArray();
245
246 /**
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700247 * App IDs of built-in system apps that have been white-listed.
248 */
249 private final SparseBooleanArray mPowerSaveWhitelistSystemAppIds = new SparseBooleanArray();
250
251 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700252 * App IDs that have been white-listed to opt out of power save restrictions, except
253 * for device idle modes.
254 */
255 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
256
257 /**
258 * Current app IDs that are in the complete power save white list, but shouldn't be
259 * excluded from idle modes. This array can be shared with others because it will not be
260 * modified once set.
261 */
262 private int[] mPowerSaveWhitelistExceptIdleAppIdArray = new int[0];
263
264 /**
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700265 * App IDs that have been white-listed to opt out of power save restrictions.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700266 */
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700267 private final SparseBooleanArray mPowerSaveWhitelistAllAppIds = new SparseBooleanArray();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700268
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700269 /**
270 * Current app IDs that are in the complete power save white list. This array can
271 * be shared with others because it will not be modified once set.
272 */
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700273 private int[] mPowerSaveWhitelistAllAppIdArray = new int[0];
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700274
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700275 /**
Dianne Hackborn262ae5c2016-02-10 16:28:29 -0800276 * App IDs that have been white-listed by the user to opt out of power save restrictions.
277 */
278 private final SparseBooleanArray mPowerSaveWhitelistUserAppIds = new SparseBooleanArray();
279
280 /**
281 * Current app IDs that are in the user power save white list. This array can
282 * be shared with others because it will not be modified once set.
283 */
284 private int[] mPowerSaveWhitelistUserAppIdArray = new int[0];
285
286 /**
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700287 * List of end times for UIDs that are temporarily marked as being allowed to access
288 * the network and acquire wakelocks. Times are in milliseconds.
289 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700290 private final SparseArray<Pair<MutableLong, String>> mTempWhitelistAppIdEndTimes
291 = new SparseArray<>();
292
293 /**
294 * Callback to the NetworkPolicyManagerService to tell it that the temp whitelist has changed.
295 */
296 Runnable mNetworkPolicyTempWhitelistCallback;
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700297
298 /**
299 * Current app IDs of temporarily whitelist apps for high-priority messages.
300 */
301 private int[] mTempWhitelistAppIdArray = new int[0];
302
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800303 private static final int EVENT_NULL = 0;
304 private static final int EVENT_NORMAL = 1;
305 private static final int EVENT_LIGHT_IDLE = 2;
306 private static final int EVENT_LIGHT_MAINTENANCE = 3;
Dianne Hackbornb6843652016-02-22 12:20:13 -0800307 private static final int EVENT_DEEP_IDLE = 4;
308 private static final int EVENT_DEEP_MAINTENANCE = 5;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800309
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -0700310 private final int[] mEventCmds = new int[EVENT_BUFFER_SIZE];
311 private final long[] mEventTimes = new long[EVENT_BUFFER_SIZE];
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800312
313 private void addEvent(int cmd) {
314 if (mEventCmds[0] != cmd) {
315 System.arraycopy(mEventCmds, 0, mEventCmds, 1, EVENT_BUFFER_SIZE - 1);
316 System.arraycopy(mEventTimes, 0, mEventTimes, 1, EVENT_BUFFER_SIZE - 1);
317 mEventCmds[0] = cmd;
318 mEventTimes[0] = SystemClock.elapsedRealtime();
319 }
320 }
321
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700322 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
323 @Override public void onReceive(Context context, Intent intent) {
Dianne Hackborn88c41352016-04-07 15:18:58 -0700324 switch (intent.getAction()) {
325 case ConnectivityManager.CONNECTIVITY_ACTION: {
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -0700326 updateConnectivityState(intent);
Dianne Hackborn88c41352016-04-07 15:18:58 -0700327 } break;
328 case Intent.ACTION_BATTERY_CHANGED: {
329 synchronized (DeviceIdleController.this) {
330 int plugged = intent.getIntExtra("plugged", 0);
331 updateChargingLocked(plugged != 0);
332 }
333 } break;
334 case Intent.ACTION_PACKAGE_REMOVED: {
335 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
336 Uri data = intent.getData();
337 String ssp;
338 if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
339 removePowerSaveWhitelistAppInternal(ssp);
340 }
341 }
342 } break;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700343 }
344 }
345 };
346
347 private final AlarmManager.OnAlarmListener mLightAlarmListener
348 = new AlarmManager.OnAlarmListener() {
349 @Override
350 public void onAlarm() {
351 synchronized (DeviceIdleController.this) {
352 stepLightIdleStateLocked("s:alarm");
353 }
354 }
355 };
356
Kevin Gabayan92f15e62016-04-04 17:52:22 -0700357 private final AlarmManager.OnAlarmListener mSensingTimeoutAlarmListener
358 = new AlarmManager.OnAlarmListener() {
359 @Override
360 public void onAlarm() {
361 if (mState == STATE_SENSING) {
362 synchronized (DeviceIdleController.this) {
363 becomeInactiveIfAppropriateLocked();
364 }
365 }
366 }
367 };
368
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700369 private final AlarmManager.OnAlarmListener mDeepAlarmListener
370 = new AlarmManager.OnAlarmListener() {
371 @Override
372 public void onAlarm() {
373 synchronized (DeviceIdleController.this) {
374 stepIdleStateLocked("s:alarm");
375 }
376 }
377 };
378
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800379 private final BroadcastReceiver mIdleStartedDoneReceiver = new BroadcastReceiver() {
380 @Override public void onReceive(Context context, Intent intent) {
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700381 // When coming out of a deep idle, we will add in some delay before we allow
382 // the system to settle down and finish the maintenance window. This is
383 // to give a chance for any pending work to be scheduled.
384 if (PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED.equals(intent.getAction())) {
385 mHandler.sendEmptyMessageDelayed(MSG_FINISH_IDLE_OP,
386 mConstants.MIN_DEEP_MAINTENANCE_TIME);
387 } else {
388 mHandler.sendEmptyMessageDelayed(MSG_FINISH_IDLE_OP,
389 mConstants.MIN_LIGHT_MAINTENANCE_TIME);
390 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800391 }
392 };
393
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700394 private final DisplayManager.DisplayListener mDisplayListener
395 = new DisplayManager.DisplayListener() {
396 @Override public void onDisplayAdded(int displayId) {
397 }
398
399 @Override public void onDisplayRemoved(int displayId) {
400 }
401
402 @Override public void onDisplayChanged(int displayId) {
403 if (displayId == Display.DEFAULT_DISPLAY) {
404 synchronized (DeviceIdleController.this) {
405 updateDisplayLocked();
406 }
407 }
408 }
409 };
410
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700411 private final class MotionListener extends TriggerEventListener
412 implements SensorEventListener {
413
414 boolean active = false;
415
416 @Override
417 public void onTrigger(TriggerEvent event) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700418 synchronized (DeviceIdleController.this) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700419 active = false;
420 motionLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700421 }
422 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700423
424 @Override
425 public void onSensorChanged(SensorEvent event) {
426 synchronized (DeviceIdleController.this) {
427 mSensorManager.unregisterListener(this, mMotionSensor);
428 active = false;
429 motionLocked();
430 }
431 }
432
433 @Override
434 public void onAccuracyChanged(Sensor sensor, int accuracy) {}
435
436 public boolean registerLocked() {
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700437 boolean success;
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700438 if (mMotionSensor.getReportingMode() == Sensor.REPORTING_MODE_ONE_SHOT) {
439 success = mSensorManager.requestTriggerSensor(mMotionListener, mMotionSensor);
440 } else {
441 success = mSensorManager.registerListener(
442 mMotionListener, mMotionSensor, SensorManager.SENSOR_DELAY_NORMAL);
443 }
444 if (success) {
445 active = true;
446 } else {
447 Slog.e(TAG, "Unable to register for " + mMotionSensor);
448 }
449 return success;
450 }
451
452 public void unregisterLocked() {
453 if (mMotionSensor.getReportingMode() == Sensor.REPORTING_MODE_ONE_SHOT) {
454 mSensorManager.cancelTriggerSensor(mMotionListener, mMotionSensor);
455 } else {
456 mSensorManager.unregisterListener(mMotionListener);
457 }
458 active = false;
459 }
460 }
461 private final MotionListener mMotionListener = new MotionListener();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700462
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700463 private final LocationListener mGenericLocationListener = new LocationListener() {
464 @Override
465 public void onLocationChanged(Location location) {
466 synchronized (DeviceIdleController.this) {
467 receivedGenericLocationLocked(location);
468 }
469 }
470
471 @Override
472 public void onStatusChanged(String provider, int status, Bundle extras) {
473 }
474
475 @Override
476 public void onProviderEnabled(String provider) {
477 }
478
479 @Override
480 public void onProviderDisabled(String provider) {
481 }
482 };
483
484 private final LocationListener mGpsLocationListener = new LocationListener() {
485 @Override
486 public void onLocationChanged(Location location) {
487 synchronized (DeviceIdleController.this) {
488 receivedGpsLocationLocked(location);
489 }
490 }
491
492 @Override
493 public void onStatusChanged(String provider, int status, Bundle extras) {
494 }
495
496 @Override
497 public void onProviderEnabled(String provider) {
498 }
499
500 @Override
501 public void onProviderDisabled(String provider) {
502 }
503 };
504
Adam Lesinski31c05d12015-06-09 17:34:04 -0700505 /**
506 * All times are in milliseconds. These constants are kept synchronized with the system
507 * global Settings. Any access to this class or its fields should be done while
508 * holding the DeviceIdleController lock.
509 */
Dianne Hackborna750a632015-06-16 17:18:23 -0700510 private final class Constants extends ContentObserver {
Adam Lesinski31c05d12015-06-09 17:34:04 -0700511 // Key names stored in the settings value.
Dianne Hackborn953fc942016-03-29 15:36:24 -0700512 private static final String KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT
513 = "light_after_inactive_to";
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700514 private static final String KEY_LIGHT_PRE_IDLE_TIMEOUT = "light_pre_idle_to";
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700515 private static final String KEY_LIGHT_IDLE_TIMEOUT = "light_idle_to";
Dianne Hackborn953fc942016-03-29 15:36:24 -0700516 private static final String KEY_LIGHT_IDLE_FACTOR = "light_idle_factor";
517 private static final String KEY_LIGHT_MAX_IDLE_TIMEOUT = "light_max_idle_to";
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800518 private static final String KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET
519 = "light_idle_maintenance_min_budget";
520 private static final String KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET
521 = "light_idle_maintenance_max_budget";
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700522 private static final String KEY_MIN_LIGHT_MAINTENANCE_TIME = "min_light_maintenance_time";
523 private static final String KEY_MIN_DEEP_MAINTENANCE_TIME = "min_deep_maintenance_time";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700524 private static final String KEY_INACTIVE_TIMEOUT = "inactive_to";
525 private static final String KEY_SENSING_TIMEOUT = "sensing_to";
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700526 private static final String KEY_LOCATING_TIMEOUT = "locating_to";
527 private static final String KEY_LOCATION_ACCURACY = "location_accuracy";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700528 private static final String KEY_MOTION_INACTIVE_TIMEOUT = "motion_inactive_to";
529 private static final String KEY_IDLE_AFTER_INACTIVE_TIMEOUT = "idle_after_inactive_to";
530 private static final String KEY_IDLE_PENDING_TIMEOUT = "idle_pending_to";
531 private static final String KEY_MAX_IDLE_PENDING_TIMEOUT = "max_idle_pending_to";
532 private static final String KEY_IDLE_PENDING_FACTOR = "idle_pending_factor";
533 private static final String KEY_IDLE_TIMEOUT = "idle_to";
534 private static final String KEY_MAX_IDLE_TIMEOUT = "max_idle_to";
535 private static final String KEY_IDLE_FACTOR = "idle_factor";
536 private static final String KEY_MIN_TIME_TO_ALARM = "min_time_to_alarm";
537 private static final String KEY_MAX_TEMP_APP_WHITELIST_DURATION =
538 "max_temp_app_whitelist_duration";
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700539 private static final String KEY_MMS_TEMP_APP_WHITELIST_DURATION =
540 "mms_temp_app_whitelist_duration";
Dianne Hackborn451c3462015-07-21 17:39:46 -0700541 private static final String KEY_SMS_TEMP_APP_WHITELIST_DURATION =
542 "sms_temp_app_whitelist_duration";
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700543 private static final String KEY_NOTIFICATION_WHITELIST_DURATION =
544 "notification_whitelist_duration";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700545
546 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700547 * This is the time, after becoming inactive, that we go in to the first
548 * light-weight idle mode.
549 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
550 * @see #KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT
551 */
552 public long LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT;
553
554 /**
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700555 * This is amount of time we will wait from the point where we decide we would
556 * like to go idle until we actually do, while waiting for jobs and other current
557 * activity to finish.
558 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
559 * @see #KEY_LIGHT_PRE_IDLE_TIMEOUT
560 */
561 public long LIGHT_PRE_IDLE_TIMEOUT;
562
563 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700564 * This is the initial time that we will run in idle maintenance mode.
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700565 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
566 * @see #KEY_LIGHT_IDLE_TIMEOUT
567 */
568 public long LIGHT_IDLE_TIMEOUT;
569
570 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700571 * Scaling factor to apply to the light idle mode time each time we complete a cycle.
572 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
573 * @see #KEY_LIGHT_IDLE_FACTOR
574 */
575 public float LIGHT_IDLE_FACTOR;
576
577 /**
578 * This is the maximum time we will run in idle maintenence mode.
579 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
580 * @see #KEY_LIGHT_MAX_IDLE_TIMEOUT
581 */
582 public long LIGHT_MAX_IDLE_TIMEOUT;
583
584 /**
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800585 * This is the minimum amount of time we want to make available for maintenance mode
586 * when lightly idling. That is, we will always have at least this amount of time
587 * available maintenance before timing out and cutting off maintenance mode.
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700588 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800589 * @see #KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700590 */
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800591 public long LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
592
593 /**
594 * This is the maximum amount of time we want to make available for maintenance mode
595 * when lightly idling. That is, if the system isn't using up its minimum maintenance
596 * budget and this time is being added to the budget reserve, this is the maximum
597 * reserve size we will allow to grow and thus the maximum amount of time we will
598 * allow for the maintenance window.
599 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
600 * @see #KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET
601 */
602 public long LIGHT_IDLE_MAINTENANCE_MAX_BUDGET;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700603
604 /**
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700605 * This is the minimum amount of time that we will stay in maintenance mode after
606 * a light doze. We have this minimum to allow various things to respond to switching
607 * in to maintenance mode and scheduling their work -- otherwise we may
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700608 * see there is nothing to do (no jobs pending) and go out of maintenance
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700609 * mode immediately.
610 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
611 * @see #KEY_MIN_LIGHT_MAINTENANCE_TIME
612 */
613 public long MIN_LIGHT_MAINTENANCE_TIME;
614
615 /**
616 * This is the minimum amount of time that we will stay in maintenance mode after
617 * a full doze. We have this minimum to allow various things to respond to switching
618 * in to maintenance mode and scheduling their work -- otherwise we may
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700619 * see there is nothing to do (no jobs pending) and go out of maintenance
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700620 * mode immediately.
621 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
622 * @see #KEY_MIN_DEEP_MAINTENANCE_TIME
623 */
624 public long MIN_DEEP_MAINTENANCE_TIME;
625
626 /**
Adam Lesinski31c05d12015-06-09 17:34:04 -0700627 * This is the time, after becoming inactive, at which we start looking at the
628 * motion sensor to determine if the device is being left alone. We don't do this
629 * immediately after going inactive just because we don't want to be continually running
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700630 * the motion sensor whenever the screen is off.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700631 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
632 * @see #KEY_INACTIVE_TIMEOUT
633 */
634 public long INACTIVE_TIMEOUT;
635
636 /**
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700637 * If we don't receive a callback from AnyMotion in this amount of time +
638 * {@link #LOCATING_TIMEOUT}, we will change from
Adam Lesinski31c05d12015-06-09 17:34:04 -0700639 * STATE_SENSING to STATE_INACTIVE, and any AnyMotion callbacks while not in STATE_SENSING
640 * will be ignored.
641 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
642 * @see #KEY_SENSING_TIMEOUT
643 */
644 public long SENSING_TIMEOUT;
645
646 /**
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700647 * This is how long we will wait to try to get a good location fix before going in to
648 * idle mode.
649 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
650 * @see #KEY_LOCATING_TIMEOUT
651 */
652 public long LOCATING_TIMEOUT;
653
654 /**
655 * The desired maximum accuracy (in meters) we consider the location to be good enough to go
656 * on to idle. We will be trying to get an accuracy fix at least this good or until
657 * {@link #LOCATING_TIMEOUT} expires.
658 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
659 * @see #KEY_LOCATION_ACCURACY
660 */
661 public float LOCATION_ACCURACY;
662
663 /**
Adam Lesinski31c05d12015-06-09 17:34:04 -0700664 * This is the time, after seeing motion, that we wait after becoming inactive from
665 * that until we start looking for motion again.
666 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
667 * @see #KEY_MOTION_INACTIVE_TIMEOUT
668 */
669 public long MOTION_INACTIVE_TIMEOUT;
670
671 /**
672 * This is the time, after the inactive timeout elapses, that we will wait looking
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700673 * for motion until we truly consider the device to be idle.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700674 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
675 * @see #KEY_IDLE_AFTER_INACTIVE_TIMEOUT
676 */
677 public long IDLE_AFTER_INACTIVE_TIMEOUT;
678
679 /**
680 * This is the initial time, after being idle, that we will allow ourself to be back
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700681 * in the IDLE_MAINTENANCE state allowing the system to run normally until we return to
682 * idle.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700683 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
684 * @see #KEY_IDLE_PENDING_TIMEOUT
685 */
686 public long IDLE_PENDING_TIMEOUT;
687
688 /**
689 * Maximum pending idle timeout (time spent running) we will be allowed to use.
690 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
691 * @see #KEY_MAX_IDLE_PENDING_TIMEOUT
692 */
693 public long MAX_IDLE_PENDING_TIMEOUT;
694
695 /**
696 * Scaling factor to apply to current pending idle timeout each time we cycle through
697 * that state.
698 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
699 * @see #KEY_IDLE_PENDING_FACTOR
700 */
701 public float IDLE_PENDING_FACTOR;
702
703 /**
704 * This is the initial time that we want to sit in the idle state before waking up
705 * again to return to pending idle and allowing normal work to run.
706 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
707 * @see #KEY_IDLE_TIMEOUT
708 */
709 public long IDLE_TIMEOUT;
710
711 /**
712 * Maximum idle duration we will be allowed to use.
713 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
714 * @see #KEY_MAX_IDLE_TIMEOUT
715 */
716 public long MAX_IDLE_TIMEOUT;
717
718 /**
719 * Scaling factor to apply to current idle timeout each time we cycle through that state.
720 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
721 * @see #KEY_IDLE_FACTOR
722 */
723 public float IDLE_FACTOR;
724
725 /**
726 * This is the minimum time we will allow until the next upcoming alarm for us to
727 * actually go in to idle mode.
728 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
729 * @see #KEY_MIN_TIME_TO_ALARM
730 */
731 public long MIN_TIME_TO_ALARM;
732
733 /**
734 * Max amount of time to temporarily whitelist an app when it receives a high priority
735 * tickle.
736 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
737 * @see #KEY_MAX_TEMP_APP_WHITELIST_DURATION
738 */
739 public long MAX_TEMP_APP_WHITELIST_DURATION;
740
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700741 /**
742 * Amount of time we would like to whitelist an app that is receiving an MMS.
743 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
744 * @see #KEY_MMS_TEMP_APP_WHITELIST_DURATION
745 */
746 public long MMS_TEMP_APP_WHITELIST_DURATION;
747
Dianne Hackborn451c3462015-07-21 17:39:46 -0700748 /**
749 * Amount of time we would like to whitelist an app that is receiving an SMS.
750 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
751 * @see #KEY_SMS_TEMP_APP_WHITELIST_DURATION
752 */
753 public long SMS_TEMP_APP_WHITELIST_DURATION;
754
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700755 /**
756 * Amount of time we would like to whitelist an app that is handling a
757 * {@link android.app.PendingIntent} triggered by a {@link android.app.Notification}.
758 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
759 * @see #KEY_NOTIFICATION_WHITELIST_DURATION
760 */
761 public long NOTIFICATION_WHITELIST_DURATION;
762
Adam Lesinski31c05d12015-06-09 17:34:04 -0700763 private final ContentResolver mResolver;
Joe LaPennaf33b5bf2016-03-23 15:19:47 -0700764 private final boolean mHasWatch;
Adam Lesinski31c05d12015-06-09 17:34:04 -0700765 private final KeyValueListParser mParser = new KeyValueListParser(',');
766
767 public Constants(Handler handler, ContentResolver resolver) {
768 super(handler);
769 mResolver = resolver;
Joe LaPennaf33b5bf2016-03-23 15:19:47 -0700770 mHasWatch = getContext().getPackageManager().hasSystemFeature(
771 PackageManager.FEATURE_WATCH);
772 mResolver.registerContentObserver(Settings.Global.getUriFor(
773 mHasWatch ? Settings.Global.DEVICE_IDLE_CONSTANTS_WATCH
774 : Settings.Global.DEVICE_IDLE_CONSTANTS),
775 false, this);
Adam Lesinski31c05d12015-06-09 17:34:04 -0700776 updateConstants();
777 }
778
779 @Override
780 public void onChange(boolean selfChange, Uri uri) {
781 updateConstants();
782 }
783
784 private void updateConstants() {
785 synchronized (DeviceIdleController.this) {
786 try {
787 mParser.setString(Settings.Global.getString(mResolver,
Joe LaPennaf33b5bf2016-03-23 15:19:47 -0700788 mHasWatch ? Settings.Global.DEVICE_IDLE_CONSTANTS_WATCH
789 : Settings.Global.DEVICE_IDLE_CONSTANTS));
Adam Lesinski31c05d12015-06-09 17:34:04 -0700790 } catch (IllegalArgumentException e) {
791 // Failed to parse the settings string, log this and move on
792 // with defaults.
793 Slog.e(TAG, "Bad device idle settings", e);
794 }
795
Dianne Hackborn953fc942016-03-29 15:36:24 -0700796 LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT = mParser.getLong(
797 KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT,
798 !COMPRESS_TIME ? 5 * 60 * 1000L : 15 * 1000L);
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700799 LIGHT_PRE_IDLE_TIMEOUT = mParser.getLong(KEY_LIGHT_PRE_IDLE_TIMEOUT,
800 !COMPRESS_TIME ? 10 * 60 * 1000L : 30 * 1000L);
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700801 LIGHT_IDLE_TIMEOUT = mParser.getLong(KEY_LIGHT_IDLE_TIMEOUT,
Dianne Hackborn953fc942016-03-29 15:36:24 -0700802 !COMPRESS_TIME ? 5 * 60 * 1000L : 15 * 1000L);
803 LIGHT_IDLE_FACTOR = mParser.getFloat(KEY_LIGHT_IDLE_FACTOR,
804 2f);
805 LIGHT_MAX_IDLE_TIMEOUT = mParser.getLong(KEY_LIGHT_MAX_IDLE_TIMEOUT,
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700806 !COMPRESS_TIME ? 15 * 60 * 1000L : 60 * 1000L);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800807 LIGHT_IDLE_MAINTENANCE_MIN_BUDGET = mParser.getLong(
808 KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET,
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700809 !COMPRESS_TIME ? 1 * 60 * 1000L : 15 * 1000L);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800810 LIGHT_IDLE_MAINTENANCE_MAX_BUDGET = mParser.getLong(
811 KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET,
812 !COMPRESS_TIME ? 5 * 60 * 1000L : 30 * 1000L);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700813 MIN_LIGHT_MAINTENANCE_TIME = mParser.getLong(
814 KEY_MIN_LIGHT_MAINTENANCE_TIME,
815 !COMPRESS_TIME ? 5 * 1000L : 1 * 1000L);
816 MIN_DEEP_MAINTENANCE_TIME = mParser.getLong(
817 KEY_MIN_DEEP_MAINTENANCE_TIME,
818 !COMPRESS_TIME ? 30 * 1000L : 5 * 1000L);
Joe LaPenna0c5d3e92016-03-24 13:29:56 -0700819 long inactiveTimeoutDefault = (mHasWatch ? 15 : 30) * 60 * 1000L;
Adam Lesinski31c05d12015-06-09 17:34:04 -0700820 INACTIVE_TIMEOUT = mParser.getLong(KEY_INACTIVE_TIMEOUT,
Joe LaPenna0c5d3e92016-03-24 13:29:56 -0700821 !COMPRESS_TIME ? inactiveTimeoutDefault : (inactiveTimeoutDefault / 10));
Adam Lesinski31c05d12015-06-09 17:34:04 -0700822 SENSING_TIMEOUT = mParser.getLong(KEY_SENSING_TIMEOUT,
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700823 !DEBUG ? 4 * 60 * 1000L : 60 * 1000L);
824 LOCATING_TIMEOUT = mParser.getLong(KEY_LOCATING_TIMEOUT,
825 !DEBUG ? 30 * 1000L : 15 * 1000L);
826 LOCATION_ACCURACY = mParser.getFloat(KEY_LOCATION_ACCURACY, 20);
Adam Lesinski31c05d12015-06-09 17:34:04 -0700827 MOTION_INACTIVE_TIMEOUT = mParser.getLong(KEY_MOTION_INACTIVE_TIMEOUT,
828 !COMPRESS_TIME ? 10 * 60 * 1000L : 60 * 1000L);
Joe LaPenna0c5d3e92016-03-24 13:29:56 -0700829 long idleAfterInactiveTimeout = (mHasWatch ? 15 : 30) * 60 * 1000L;
Adam Lesinski31c05d12015-06-09 17:34:04 -0700830 IDLE_AFTER_INACTIVE_TIMEOUT = mParser.getLong(KEY_IDLE_AFTER_INACTIVE_TIMEOUT,
Joe LaPenna0c5d3e92016-03-24 13:29:56 -0700831 !COMPRESS_TIME ? idleAfterInactiveTimeout
832 : (idleAfterInactiveTimeout / 10));
Adam Lesinski31c05d12015-06-09 17:34:04 -0700833 IDLE_PENDING_TIMEOUT = mParser.getLong(KEY_IDLE_PENDING_TIMEOUT,
834 !COMPRESS_TIME ? 5 * 60 * 1000L : 30 * 1000L);
835 MAX_IDLE_PENDING_TIMEOUT = mParser.getLong(KEY_MAX_IDLE_PENDING_TIMEOUT,
836 !COMPRESS_TIME ? 10 * 60 * 1000L : 60 * 1000L);
837 IDLE_PENDING_FACTOR = mParser.getFloat(KEY_IDLE_PENDING_FACTOR,
838 2f);
839 IDLE_TIMEOUT = mParser.getLong(KEY_IDLE_TIMEOUT,
840 !COMPRESS_TIME ? 60 * 60 * 1000L : 6 * 60 * 1000L);
841 MAX_IDLE_TIMEOUT = mParser.getLong(KEY_MAX_IDLE_TIMEOUT,
842 !COMPRESS_TIME ? 6 * 60 * 60 * 1000L : 30 * 60 * 1000L);
843 IDLE_FACTOR = mParser.getFloat(KEY_IDLE_FACTOR,
844 2f);
845 MIN_TIME_TO_ALARM = mParser.getLong(KEY_MIN_TIME_TO_ALARM,
846 !COMPRESS_TIME ? 60 * 60 * 1000L : 6 * 60 * 1000L);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700847 MAX_TEMP_APP_WHITELIST_DURATION = mParser.getLong(
848 KEY_MAX_TEMP_APP_WHITELIST_DURATION, 5 * 60 * 1000L);
849 MMS_TEMP_APP_WHITELIST_DURATION = mParser.getLong(
Dianne Hackborn0b6134b2015-07-14 18:48:07 -0700850 KEY_MMS_TEMP_APP_WHITELIST_DURATION, 60 * 1000L);
Dianne Hackborn451c3462015-07-21 17:39:46 -0700851 SMS_TEMP_APP_WHITELIST_DURATION = mParser.getLong(
852 KEY_SMS_TEMP_APP_WHITELIST_DURATION, 20 * 1000L);
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700853 NOTIFICATION_WHITELIST_DURATION = mParser.getLong(
854 KEY_NOTIFICATION_WHITELIST_DURATION, 30 * 1000L);
Adam Lesinski31c05d12015-06-09 17:34:04 -0700855 }
856 }
857
858 void dump(PrintWriter pw) {
859 pw.println(" Settings:");
860
Dianne Hackborn953fc942016-03-29 15:36:24 -0700861 pw.print(" "); pw.print(KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT); pw.print("=");
862 TimeUtils.formatDuration(LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT, pw);
863 pw.println();
864
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700865 pw.print(" "); pw.print(KEY_LIGHT_PRE_IDLE_TIMEOUT); pw.print("=");
866 TimeUtils.formatDuration(LIGHT_PRE_IDLE_TIMEOUT, pw);
867 pw.println();
868
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700869 pw.print(" "); pw.print(KEY_LIGHT_IDLE_TIMEOUT); pw.print("=");
870 TimeUtils.formatDuration(LIGHT_IDLE_TIMEOUT, pw);
871 pw.println();
872
Dianne Hackborn953fc942016-03-29 15:36:24 -0700873 pw.print(" "); pw.print(KEY_LIGHT_IDLE_FACTOR); pw.print("=");
874 pw.print(LIGHT_IDLE_FACTOR);
875 pw.println();
876
877 pw.print(" "); pw.print(KEY_LIGHT_MAX_IDLE_TIMEOUT); pw.print("=");
878 TimeUtils.formatDuration(LIGHT_MAX_IDLE_TIMEOUT, pw);
879 pw.println();
880
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800881 pw.print(" "); pw.print(KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET); pw.print("=");
882 TimeUtils.formatDuration(LIGHT_IDLE_MAINTENANCE_MIN_BUDGET, pw);
883 pw.println();
884
885 pw.print(" "); pw.print(KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET); pw.print("=");
886 TimeUtils.formatDuration(LIGHT_IDLE_MAINTENANCE_MAX_BUDGET, pw);
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700887 pw.println();
888
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700889 pw.print(" "); pw.print(KEY_MIN_LIGHT_MAINTENANCE_TIME); pw.print("=");
890 TimeUtils.formatDuration(MIN_LIGHT_MAINTENANCE_TIME, pw);
891 pw.println();
892
893 pw.print(" "); pw.print(KEY_MIN_DEEP_MAINTENANCE_TIME); pw.print("=");
894 TimeUtils.formatDuration(MIN_DEEP_MAINTENANCE_TIME, pw);
895 pw.println();
896
Dianne Hackborna750a632015-06-16 17:18:23 -0700897 pw.print(" "); pw.print(KEY_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700898 TimeUtils.formatDuration(INACTIVE_TIMEOUT, pw);
899 pw.println();
900
Dianne Hackborna750a632015-06-16 17:18:23 -0700901 pw.print(" "); pw.print(KEY_SENSING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700902 TimeUtils.formatDuration(SENSING_TIMEOUT, pw);
903 pw.println();
904
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700905 pw.print(" "); pw.print(KEY_LOCATING_TIMEOUT); pw.print("=");
906 TimeUtils.formatDuration(LOCATING_TIMEOUT, pw);
907 pw.println();
908
909 pw.print(" "); pw.print(KEY_LOCATION_ACCURACY); pw.print("=");
910 pw.print(LOCATION_ACCURACY); pw.print("m");
911 pw.println();
912
Dianne Hackborna750a632015-06-16 17:18:23 -0700913 pw.print(" "); pw.print(KEY_MOTION_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700914 TimeUtils.formatDuration(MOTION_INACTIVE_TIMEOUT, pw);
915 pw.println();
916
Dianne Hackborna750a632015-06-16 17:18:23 -0700917 pw.print(" "); pw.print(KEY_IDLE_AFTER_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700918 TimeUtils.formatDuration(IDLE_AFTER_INACTIVE_TIMEOUT, pw);
919 pw.println();
920
Dianne Hackborna750a632015-06-16 17:18:23 -0700921 pw.print(" "); pw.print(KEY_IDLE_PENDING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700922 TimeUtils.formatDuration(IDLE_PENDING_TIMEOUT, pw);
923 pw.println();
924
Dianne Hackborna750a632015-06-16 17:18:23 -0700925 pw.print(" "); pw.print(KEY_MAX_IDLE_PENDING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700926 TimeUtils.formatDuration(MAX_IDLE_PENDING_TIMEOUT, pw);
927 pw.println();
928
Dianne Hackborna750a632015-06-16 17:18:23 -0700929 pw.print(" "); pw.print(KEY_IDLE_PENDING_FACTOR); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700930 pw.println(IDLE_PENDING_FACTOR);
931
Dianne Hackborna750a632015-06-16 17:18:23 -0700932 pw.print(" "); pw.print(KEY_IDLE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700933 TimeUtils.formatDuration(IDLE_TIMEOUT, pw);
934 pw.println();
935
Dianne Hackborna750a632015-06-16 17:18:23 -0700936 pw.print(" "); pw.print(KEY_MAX_IDLE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700937 TimeUtils.formatDuration(MAX_IDLE_TIMEOUT, pw);
938 pw.println();
939
Dianne Hackborna750a632015-06-16 17:18:23 -0700940 pw.print(" "); pw.print(KEY_IDLE_FACTOR); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700941 pw.println(IDLE_FACTOR);
942
Dianne Hackborna750a632015-06-16 17:18:23 -0700943 pw.print(" "); pw.print(KEY_MIN_TIME_TO_ALARM); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700944 TimeUtils.formatDuration(MIN_TIME_TO_ALARM, pw);
945 pw.println();
946
Dianne Hackborna750a632015-06-16 17:18:23 -0700947 pw.print(" "); pw.print(KEY_MAX_TEMP_APP_WHITELIST_DURATION); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700948 TimeUtils.formatDuration(MAX_TEMP_APP_WHITELIST_DURATION, pw);
949 pw.println();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700950
951 pw.print(" "); pw.print(KEY_MMS_TEMP_APP_WHITELIST_DURATION); pw.print("=");
952 TimeUtils.formatDuration(MMS_TEMP_APP_WHITELIST_DURATION, pw);
953 pw.println();
Dianne Hackborn451c3462015-07-21 17:39:46 -0700954
955 pw.print(" "); pw.print(KEY_SMS_TEMP_APP_WHITELIST_DURATION); pw.print("=");
956 TimeUtils.formatDuration(SMS_TEMP_APP_WHITELIST_DURATION, pw);
957 pw.println();
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700958
959 pw.print(" "); pw.print(KEY_NOTIFICATION_WHITELIST_DURATION); pw.print("=");
960 TimeUtils.formatDuration(NOTIFICATION_WHITELIST_DURATION, pw);
961 pw.println();
Adam Lesinski31c05d12015-06-09 17:34:04 -0700962 }
963 }
964
965 private Constants mConstants;
966
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700967 @Override
968 public void onAnyMotionResult(int result) {
969 if (DEBUG) Slog.d(TAG, "onAnyMotionResult(" + result + ")");
Kevin Gabayan92f15e62016-04-04 17:52:22 -0700970 if (result != AnyMotionDetector.RESULT_UNKNOWN) {
971 synchronized (this) {
972 cancelSensingTimeoutAlarmLocked();
973 }
974 }
Kevin Gabayandcf47012016-07-08 10:41:24 -0700975 if ((result == AnyMotionDetector.RESULT_MOVED) ||
976 (result == AnyMotionDetector.RESULT_UNKNOWN)) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700977 synchronized (this) {
Kevin Gabayandcf47012016-07-08 10:41:24 -0700978 handleMotionDetectedLocked(mConstants.INACTIVE_TIMEOUT, "non_stationary");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700979 }
980 } else if (result == AnyMotionDetector.RESULT_STATIONARY) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700981 if (mState == STATE_SENSING) {
982 // If we are currently sensing, it is time to move to locating.
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700983 synchronized (this) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700984 mNotMoving = true;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800985 stepIdleStateLocked("s:stationary");
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700986 }
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700987 } else if (mState == STATE_LOCATING) {
988 // If we are currently locating, note that we are not moving and step
989 // if we have located the position.
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700990 synchronized (this) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700991 mNotMoving = true;
992 if (mLocated) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800993 stepIdleStateLocked("s:stationary");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700994 }
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700995 }
996 }
997 }
998 }
999
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001000 static final int MSG_WRITE_CONFIG = 1;
1001 static final int MSG_REPORT_IDLE_ON = 2;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001002 static final int MSG_REPORT_IDLE_ON_LIGHT = 3;
1003 static final int MSG_REPORT_IDLE_OFF = 4;
1004 static final int MSG_REPORT_ACTIVE = 5;
1005 static final int MSG_TEMP_APP_WHITELIST_TIMEOUT = 6;
Yao Chenca5edbb2016-01-13 14:44:36 -08001006 static final int MSG_REPORT_MAINTENANCE_ACTIVITY = 7;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001007 static final int MSG_FINISH_IDLE_OP = 8;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001008
1009 final class MyHandler extends Handler {
1010 MyHandler(Looper looper) {
1011 super(looper);
1012 }
1013
1014 @Override public void handleMessage(Message msg) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001015 if (DEBUG) Slog.d(TAG, "handleMessage(" + msg.what + ")");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001016 switch (msg.what) {
1017 case MSG_WRITE_CONFIG: {
1018 handleWriteConfigFile();
1019 } break;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001020 case MSG_REPORT_IDLE_ON:
1021 case MSG_REPORT_IDLE_ON_LIGHT: {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001022 EventLogTags.writeDeviceIdleOnStart();
Dianne Hackbornb6843652016-02-22 12:20:13 -08001023 final boolean deepChanged;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001024 final boolean lightChanged;
1025 if (msg.what == MSG_REPORT_IDLE_ON) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001026 deepChanged = mLocalPowerManager.setDeviceIdleMode(true);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001027 lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
1028 } else {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001029 deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001030 lightChanged = mLocalPowerManager.setLightDeviceIdleMode(true);
1031 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001032 try {
1033 mNetworkPolicyManager.setDeviceIdleMode(true);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001034 mBatteryStats.noteDeviceIdleMode(msg.what == MSG_REPORT_IDLE_ON
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07001035 ? BatteryStats.DEVICE_IDLE_MODE_DEEP
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001036 : BatteryStats.DEVICE_IDLE_MODE_LIGHT, null, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001037 } catch (RemoteException e) {
1038 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001039 if (deepChanged) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001040 getContext().sendBroadcastAsUser(mIdleIntent, UserHandle.ALL);
1041 }
1042 if (lightChanged) {
1043 getContext().sendBroadcastAsUser(mLightIdleIntent, UserHandle.ALL);
1044 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001045 EventLogTags.writeDeviceIdleOnComplete();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001046 } break;
1047 case MSG_REPORT_IDLE_OFF: {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001048 EventLogTags.writeDeviceIdleOffStart("unknown");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001049 final boolean deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001050 final boolean lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001051 try {
1052 mNetworkPolicyManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001053 mBatteryStats.noteDeviceIdleMode(BatteryStats.DEVICE_IDLE_MODE_OFF,
1054 null, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001055 } catch (RemoteException e) {
1056 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001057 if (deepChanged) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001058 incActiveIdleOps();
1059 getContext().sendOrderedBroadcastAsUser(mIdleIntent, UserHandle.ALL,
1060 null, mIdleStartedDoneReceiver, null, 0, null, null);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001061 }
1062 if (lightChanged) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001063 incActiveIdleOps();
1064 getContext().sendOrderedBroadcastAsUser(mLightIdleIntent, UserHandle.ALL,
1065 null, mIdleStartedDoneReceiver, null, 0, null, null);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001066 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001067 // Always start with one active op for the message being sent here.
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001068 // Now we are done!
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001069 decActiveIdleOps();
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001070 EventLogTags.writeDeviceIdleOffComplete();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001071 } break;
1072 case MSG_REPORT_ACTIVE: {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001073 String activeReason = (String)msg.obj;
1074 int activeUid = msg.arg1;
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001075 EventLogTags.writeDeviceIdleOffStart(
1076 activeReason != null ? activeReason : "unknown");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001077 final boolean deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001078 final boolean lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001079 try {
1080 mNetworkPolicyManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001081 mBatteryStats.noteDeviceIdleMode(BatteryStats.DEVICE_IDLE_MODE_OFF,
1082 activeReason, activeUid);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001083 } catch (RemoteException e) {
1084 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001085 if (deepChanged) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001086 getContext().sendBroadcastAsUser(mIdleIntent, UserHandle.ALL);
1087 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001088 if (lightChanged) {
1089 getContext().sendBroadcastAsUser(mLightIdleIntent, UserHandle.ALL);
1090 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001091 EventLogTags.writeDeviceIdleOffComplete();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001092 } break;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001093 case MSG_TEMP_APP_WHITELIST_TIMEOUT: {
1094 int uid = msg.arg1;
1095 checkTempAppWhitelistTimeout(uid);
1096 } break;
Yao Chenca5edbb2016-01-13 14:44:36 -08001097 case MSG_REPORT_MAINTENANCE_ACTIVITY: {
1098 boolean active = (msg.arg1 == 1);
1099 final int size = mMaintenanceActivityListeners.beginBroadcast();
1100 try {
1101 for (int i = 0; i < size; i++) {
1102 try {
1103 mMaintenanceActivityListeners.getBroadcastItem(i)
1104 .onMaintenanceActivityChanged(active);
1105 } catch (RemoteException ignored) {
1106 }
1107 }
1108 } finally {
1109 mMaintenanceActivityListeners.finishBroadcast();
1110 }
1111 } break;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001112 case MSG_FINISH_IDLE_OP: {
1113 decActiveIdleOps();
1114 } break;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001115 }
1116 }
1117 }
1118
1119 final MyHandler mHandler;
1120
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001121 BinderService mBinderService;
1122
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001123 private final class BinderService extends IDeviceIdleController.Stub {
1124 @Override public void addPowerSaveWhitelistApp(String name) {
1125 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1126 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001127 long ident = Binder.clearCallingIdentity();
1128 try {
1129 addPowerSaveWhitelistAppInternal(name);
1130 } finally {
1131 Binder.restoreCallingIdentity(ident);
1132 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001133 }
1134
1135 @Override public void removePowerSaveWhitelistApp(String name) {
1136 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1137 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001138 long ident = Binder.clearCallingIdentity();
1139 try {
1140 removePowerSaveWhitelistAppInternal(name);
1141 } finally {
1142 Binder.restoreCallingIdentity(ident);
1143 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001144 }
1145
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001146 @Override public String[] getSystemPowerWhitelistExceptIdle() {
1147 return getSystemPowerWhitelistExceptIdleInternal();
1148 }
1149
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001150 @Override public String[] getSystemPowerWhitelist() {
1151 return getSystemPowerWhitelistInternal();
1152 }
1153
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001154 @Override public String[] getUserPowerWhitelist() {
1155 return getUserPowerWhitelistInternal();
1156 }
1157
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001158 @Override public String[] getFullPowerWhitelistExceptIdle() {
1159 return getFullPowerWhitelistExceptIdleInternal();
1160 }
1161
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001162 @Override public String[] getFullPowerWhitelist() {
1163 return getFullPowerWhitelistInternal();
1164 }
1165
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001166 @Override public int[] getAppIdWhitelistExceptIdle() {
1167 return getAppIdWhitelistExceptIdleInternal();
1168 }
1169
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001170 @Override public int[] getAppIdWhitelist() {
1171 return getAppIdWhitelistInternal();
1172 }
1173
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001174 @Override public int[] getAppIdUserWhitelist() {
1175 return getAppIdUserWhitelistInternal();
1176 }
1177
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001178 @Override public int[] getAppIdTempWhitelist() {
1179 return getAppIdTempWhitelistInternal();
1180 }
1181
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001182 @Override public boolean isPowerSaveWhitelistExceptIdleApp(String name) {
1183 return isPowerSaveWhitelistExceptIdleAppInternal(name);
1184 }
1185
Amith Yamasani06bf8242015-05-08 16:36:21 -07001186 @Override public boolean isPowerSaveWhitelistApp(String name) {
1187 return isPowerSaveWhitelistAppInternal(name);
1188 }
1189
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001190 @Override public void addPowerSaveTempWhitelistApp(String packageName, long duration,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001191 int userId, String reason) throws RemoteException {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001192 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001193 }
1194
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001195 @Override public long addPowerSaveTempWhitelistAppForMms(String packageName,
1196 int userId, String reason) throws RemoteException {
1197 long duration = mConstants.MMS_TEMP_APP_WHITELIST_DURATION;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001198 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001199 return duration;
1200 }
1201
Dianne Hackborn451c3462015-07-21 17:39:46 -07001202 @Override public long addPowerSaveTempWhitelistAppForSms(String packageName,
1203 int userId, String reason) throws RemoteException {
1204 long duration = mConstants.SMS_TEMP_APP_WHITELIST_DURATION;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001205 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Dianne Hackborn451c3462015-07-21 17:39:46 -07001206 return duration;
1207 }
1208
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001209 @Override public void exitIdle(String reason) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001210 getContext().enforceCallingOrSelfPermission(Manifest.permission.DEVICE_POWER,
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001211 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001212 long ident = Binder.clearCallingIdentity();
1213 try {
1214 exitIdleInternal(reason);
1215 } finally {
1216 Binder.restoreCallingIdentity(ident);
1217 }
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001218 }
1219
Yao Chenca5edbb2016-01-13 14:44:36 -08001220 @Override public boolean registerMaintenanceActivityListener(
1221 IMaintenanceActivityListener listener) {
1222 return DeviceIdleController.this.registerMaintenanceActivityListener(listener);
1223 }
1224
1225 @Override public void unregisterMaintenanceActivityListener(
1226 IMaintenanceActivityListener listener) {
1227 DeviceIdleController.this.unregisterMaintenanceActivityListener(listener);
1228 }
1229
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001230 @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1231 DeviceIdleController.this.dump(fd, pw, args);
1232 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001233
1234 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
1235 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
1236 (new Shell()).exec(this, in, out, err, args, resultReceiver);
1237 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001238 }
1239
Felipe Lemeef134662016-08-10 14:46:39 -07001240 public class LocalService {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001241 public void addPowerSaveTempWhitelistAppDirect(int appId, long duration, boolean sync,
1242 String reason) {
1243 addPowerSaveTempWhitelistAppDirectInternal(0, appId, duration, sync, reason);
1244 }
1245
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001246 public long getNotificationWhitelistDuration() {
1247 return mConstants.NOTIFICATION_WHITELIST_DURATION;
1248 }
1249
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001250 public void setNetworkPolicyTempWhitelistCallback(Runnable callback) {
1251 setNetworkPolicyTempWhitelistCallbackInternal(callback);
Dianne Hackborna750a632015-06-16 17:18:23 -07001252 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001253
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001254 public void setJobsActive(boolean active) {
1255 DeviceIdleController.this.setJobsActive(active);
1256 }
1257
1258 // Up-call from alarm manager.
1259 public void setAlarmsActive(boolean active) {
1260 DeviceIdleController.this.setAlarmsActive(active);
1261 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001262
1263 /**
1264 * Returns the array of app ids whitelisted by user. Take care not to
1265 * modify this, as it is a reference to the original copy. But the reference
1266 * can change when the list changes, so it needs to be re-acquired when
1267 * {@link PowerManager#ACTION_POWER_SAVE_WHITELIST_CHANGED} is sent.
1268 */
1269 public int[] getPowerSaveWhitelistUserAppIds() {
1270 return DeviceIdleController.this.getPowerSaveWhitelistUserAppIds();
1271 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001272 }
1273
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001274 public DeviceIdleController(Context context) {
1275 super(context);
1276 mConfigFile = new AtomicFile(new File(getSystemDir(), "deviceidle.xml"));
1277 mHandler = new MyHandler(BackgroundThread.getHandler().getLooper());
1278 }
1279
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001280 int[] getPowerSaveWhitelistUserAppIds() {
1281 synchronized (this) {
1282 return mPowerSaveWhitelistUserAppIdArray;
1283 }
1284 }
1285
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001286 private static File getSystemDir() {
1287 return new File(Environment.getDataDirectory(), "system");
1288 }
1289
1290 @Override
1291 public void onStart() {
1292 final PackageManager pm = getContext().getPackageManager();
1293
1294 synchronized (this) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001295 mLightEnabled = mDeepEnabled = getContext().getResources().getBoolean(
Dianne Hackborn92617032015-06-19 15:32:19 -07001296 com.android.internal.R.bool.config_enableAutoPowerModes);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001297 SystemConfig sysConfig = SystemConfig.getInstance();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001298 ArraySet<String> allowPowerExceptIdle = sysConfig.getAllowInPowerSaveExceptIdle();
1299 for (int i=0; i<allowPowerExceptIdle.size(); i++) {
1300 String pkg = allowPowerExceptIdle.valueAt(i);
1301 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001302 ApplicationInfo ai = pm.getApplicationInfo(pkg,
1303 PackageManager.MATCH_SYSTEM_ONLY);
1304 int appid = UserHandle.getAppId(ai.uid);
1305 mPowerSaveWhitelistAppsExceptIdle.put(ai.packageName, appid);
1306 mPowerSaveWhitelistSystemAppIdsExceptIdle.put(appid, true);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001307 } catch (PackageManager.NameNotFoundException e) {
1308 }
1309 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001310 ArraySet<String> allowPower = sysConfig.getAllowInPowerSave();
1311 for (int i=0; i<allowPower.size(); i++) {
1312 String pkg = allowPower.valueAt(i);
1313 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001314 ApplicationInfo ai = pm.getApplicationInfo(pkg,
1315 PackageManager.MATCH_SYSTEM_ONLY);
1316 int appid = UserHandle.getAppId(ai.uid);
1317 // These apps are on both the whitelist-except-idle as well
1318 // as the full whitelist, so they apply in all cases.
1319 mPowerSaveWhitelistAppsExceptIdle.put(ai.packageName, appid);
1320 mPowerSaveWhitelistSystemAppIdsExceptIdle.put(appid, true);
1321 mPowerSaveWhitelistApps.put(ai.packageName, appid);
1322 mPowerSaveWhitelistSystemAppIds.put(appid, true);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001323 } catch (PackageManager.NameNotFoundException e) {
1324 }
1325 }
1326
Adam Lesinski31c05d12015-06-09 17:34:04 -07001327 mConstants = new Constants(mHandler, getContext().getContentResolver());
1328
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001329 readConfigFileLocked();
1330 updateWhitelistAppIdsLocked();
1331
Dianne Hackborn88c41352016-04-07 15:18:58 -07001332 mNetworkConnected = true;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001333 mScreenOn = true;
1334 // Start out assuming we are charging. If we aren't, we will at least get
1335 // a battery update the next time the level drops.
1336 mCharging = true;
1337 mState = STATE_ACTIVE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001338 mLightState = LIGHT_STATE_ACTIVE;
Adam Lesinski31c05d12015-06-09 17:34:04 -07001339 mInactiveTimeout = mConstants.INACTIVE_TIMEOUT;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001340 }
1341
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001342 mBinderService = new BinderService();
1343 publishBinderService(Context.DEVICE_IDLE_CONTROLLER, mBinderService);
Dianne Hackborna750a632015-06-16 17:18:23 -07001344 publishLocalService(LocalService.class, new LocalService());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001345 }
1346
1347 @Override
1348 public void onBootPhase(int phase) {
1349 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1350 synchronized (this) {
1351 mAlarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
1352 mBatteryStats = BatteryStatsService.getService();
1353 mLocalPowerManager = getLocalService(PowerManagerInternal.class);
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001354 mPowerManager = getContext().getSystemService(PowerManager.class);
1355 mActiveIdleWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
1356 "deviceidle_maint");
1357 mActiveIdleWakeLock.setReferenceCounted(false);
Dianne Hackborn88c41352016-04-07 15:18:58 -07001358 mConnectivityService = (ConnectivityService)ServiceManager.getService(
1359 Context.CONNECTIVITY_SERVICE);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001360 mLocalAlarmManager = getLocalService(AlarmManagerService.LocalService.class);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001361 mNetworkPolicyManager = INetworkPolicyManager.Stub.asInterface(
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001362 ServiceManager.getService(Context.NETWORK_POLICY_SERVICE));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001363 mDisplayManager = (DisplayManager) getContext().getSystemService(
1364 Context.DISPLAY_SERVICE);
1365 mSensorManager = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001366 int sigMotionSensorId = getContext().getResources().getInteger(
1367 com.android.internal.R.integer.config_autoPowerModeAnyMotionSensor);
1368 if (sigMotionSensorId > 0) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001369 mMotionSensor = mSensorManager.getDefaultSensor(sigMotionSensorId, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001370 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001371 if (mMotionSensor == null && getContext().getResources().getBoolean(
Joe LaPenna23d681b2015-08-27 15:12:11 -07001372 com.android.internal.R.bool.config_autoPowerModePreferWristTilt)) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001373 mMotionSensor = mSensorManager.getDefaultSensor(
1374 Sensor.TYPE_WRIST_TILT_GESTURE, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001375 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001376 if (mMotionSensor == null) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07001377 // As a last ditch, fall back to SMD.
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001378 mMotionSensor = mSensorManager.getDefaultSensor(
1379 Sensor.TYPE_SIGNIFICANT_MOTION, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001380 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001381
Joe LaPenna23d681b2015-08-27 15:12:11 -07001382 if (getContext().getResources().getBoolean(
1383 com.android.internal.R.bool.config_autoPowerModePrefetchLocation)) {
1384 mLocationManager = (LocationManager) getContext().getSystemService(
1385 Context.LOCATION_SERVICE);
1386 mLocationRequest = new LocationRequest()
1387 .setQuality(LocationRequest.ACCURACY_FINE)
1388 .setInterval(0)
1389 .setFastestInterval(0)
1390 .setNumUpdates(1);
1391 }
1392
1393 float angleThreshold = getContext().getResources().getInteger(
1394 com.android.internal.R.integer.config_autoPowerModeThresholdAngle) / 100f;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001395 mAnyMotionDetector = new AnyMotionDetector(
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001396 (PowerManager) getContext().getSystemService(Context.POWER_SERVICE),
Joe LaPenna23d681b2015-08-27 15:12:11 -07001397 mHandler, mSensorManager, this, angleThreshold);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001398
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001399 mIdleIntent = new Intent(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001400 mIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1401 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001402 mLightIdleIntent = new Intent(PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED);
1403 mLightIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1404 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001405
1406 IntentFilter filter = new IntentFilter();
1407 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001408 getContext().registerReceiver(mReceiver, filter);
Amith Yamasaniac59f75e2016-05-05 12:38:17 -07001409
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001410 filter = new IntentFilter();
1411 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1412 filter.addDataScheme("package");
Amith Yamasaniac59f75e2016-05-05 12:38:17 -07001413 getContext().registerReceiver(mReceiver, filter);
1414
Dianne Hackborn88c41352016-04-07 15:18:58 -07001415 filter = new IntentFilter();
1416 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001417 getContext().registerReceiver(mReceiver, filter);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001418
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001419 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001420 mLocalAlarmManager.setDeviceIdleUserWhitelist(mPowerSaveWhitelistUserAppIdArray);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001421 mDisplayManager.registerDisplayListener(mDisplayListener, null);
1422 updateDisplayLocked();
1423 }
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -07001424 updateConnectivityState(null);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001425 }
1426 }
1427
1428 public boolean addPowerSaveWhitelistAppInternal(String name) {
1429 synchronized (this) {
1430 try {
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001431 ApplicationInfo ai = getContext().getPackageManager().getApplicationInfo(name,
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001432 PackageManager.MATCH_UNINSTALLED_PACKAGES);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001433 if (mPowerSaveWhitelistUserApps.put(name, UserHandle.getAppId(ai.uid)) == null) {
1434 reportPowerSaveWhitelistChangedLocked();
1435 updateWhitelistAppIdsLocked();
1436 writeConfigFileLocked();
1437 }
1438 return true;
1439 } catch (PackageManager.NameNotFoundException e) {
1440 return false;
1441 }
1442 }
1443 }
1444
1445 public boolean removePowerSaveWhitelistAppInternal(String name) {
1446 synchronized (this) {
1447 if (mPowerSaveWhitelistUserApps.remove(name) != null) {
1448 reportPowerSaveWhitelistChangedLocked();
1449 updateWhitelistAppIdsLocked();
1450 writeConfigFileLocked();
1451 return true;
1452 }
1453 }
1454 return false;
1455 }
1456
Felipe Lemef8a46232016-02-10 13:51:54 -08001457 public boolean getPowerSaveWhitelistAppInternal(String name) {
1458 synchronized (this) {
1459 return mPowerSaveWhitelistUserApps.containsKey(name);
1460 }
1461 }
1462
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001463 public String[] getSystemPowerWhitelistExceptIdleInternal() {
1464 synchronized (this) {
1465 int size = mPowerSaveWhitelistAppsExceptIdle.size();
1466 String[] apps = new String[size];
1467 for (int i = 0; i < size; i++) {
1468 apps[i] = mPowerSaveWhitelistAppsExceptIdle.keyAt(i);
1469 }
1470 return apps;
1471 }
1472 }
1473
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001474 public String[] getSystemPowerWhitelistInternal() {
1475 synchronized (this) {
1476 int size = mPowerSaveWhitelistApps.size();
1477 String[] apps = new String[size];
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001478 for (int i = 0; i < size; i++) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001479 apps[i] = mPowerSaveWhitelistApps.keyAt(i);
1480 }
1481 return apps;
1482 }
1483 }
1484
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001485 public String[] getUserPowerWhitelistInternal() {
1486 synchronized (this) {
1487 int size = mPowerSaveWhitelistUserApps.size();
1488 String[] apps = new String[size];
1489 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1490 apps[i] = mPowerSaveWhitelistUserApps.keyAt(i);
1491 }
1492 return apps;
1493 }
1494 }
1495
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001496 public String[] getFullPowerWhitelistExceptIdleInternal() {
1497 synchronized (this) {
1498 int size = mPowerSaveWhitelistAppsExceptIdle.size() + mPowerSaveWhitelistUserApps.size();
1499 String[] apps = new String[size];
1500 int cur = 0;
1501 for (int i = 0; i < mPowerSaveWhitelistAppsExceptIdle.size(); i++) {
1502 apps[cur] = mPowerSaveWhitelistAppsExceptIdle.keyAt(i);
1503 cur++;
1504 }
1505 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1506 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
1507 cur++;
1508 }
1509 return apps;
1510 }
1511 }
1512
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001513 public String[] getFullPowerWhitelistInternal() {
1514 synchronized (this) {
1515 int size = mPowerSaveWhitelistApps.size() + mPowerSaveWhitelistUserApps.size();
1516 String[] apps = new String[size];
1517 int cur = 0;
1518 for (int i = 0; i < mPowerSaveWhitelistApps.size(); i++) {
1519 apps[cur] = mPowerSaveWhitelistApps.keyAt(i);
1520 cur++;
1521 }
1522 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1523 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
1524 cur++;
1525 }
1526 return apps;
1527 }
1528 }
1529
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001530 public boolean isPowerSaveWhitelistExceptIdleAppInternal(String packageName) {
1531 synchronized (this) {
1532 return mPowerSaveWhitelistAppsExceptIdle.containsKey(packageName)
1533 || mPowerSaveWhitelistUserApps.containsKey(packageName);
1534 }
1535 }
1536
Amith Yamasani06bf8242015-05-08 16:36:21 -07001537 public boolean isPowerSaveWhitelistAppInternal(String packageName) {
1538 synchronized (this) {
1539 return mPowerSaveWhitelistApps.containsKey(packageName)
1540 || mPowerSaveWhitelistUserApps.containsKey(packageName);
1541 }
1542 }
1543
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001544 public int[] getAppIdWhitelistExceptIdleInternal() {
1545 synchronized (this) {
1546 return mPowerSaveWhitelistExceptIdleAppIdArray;
1547 }
1548 }
1549
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001550 public int[] getAppIdWhitelistInternal() {
1551 synchronized (this) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001552 return mPowerSaveWhitelistAllAppIdArray;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001553 }
1554 }
1555
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001556 public int[] getAppIdUserWhitelistInternal() {
1557 synchronized (this) {
1558 return mPowerSaveWhitelistUserAppIdArray;
1559 }
1560 }
1561
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001562 public int[] getAppIdTempWhitelistInternal() {
1563 synchronized (this) {
1564 return mTempWhitelistAppIdArray;
1565 }
1566 }
1567
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001568 void addPowerSaveTempWhitelistAppChecked(String packageName, long duration,
1569 int userId, String reason) throws RemoteException {
1570 getContext().enforceCallingPermission(
1571 Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
1572 "No permission to change device idle whitelist");
1573 final int callingUid = Binder.getCallingUid();
1574 userId = ActivityManagerNative.getDefault().handleIncomingUser(
1575 Binder.getCallingPid(),
1576 callingUid,
1577 userId,
1578 /*allowAll=*/ false,
1579 /*requireFull=*/ false,
1580 "addPowerSaveTempWhitelistApp", null);
1581 final long token = Binder.clearCallingIdentity();
1582 try {
1583 addPowerSaveTempWhitelistAppInternal(callingUid,
1584 packageName, duration, userId, true, reason);
1585 } finally {
1586 Binder.restoreCallingIdentity(token);
1587 }
1588 }
1589
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001590 /**
1591 * Adds an app to the temporary whitelist and resets the endTime for granting the
1592 * app an exemption to access network and acquire wakelocks.
1593 */
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001594 void addPowerSaveTempWhitelistAppInternal(int callingUid, String packageName,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001595 long duration, int userId, boolean sync, String reason) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001596 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001597 int uid = getContext().getPackageManager().getPackageUidAsUser(packageName, userId);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001598 int appId = UserHandle.getAppId(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001599 addPowerSaveTempWhitelistAppDirectInternal(callingUid, appId, duration, sync, reason);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001600 } catch (NameNotFoundException e) {
1601 }
1602 }
1603
Dianne Hackborna750a632015-06-16 17:18:23 -07001604 /**
1605 * Adds an app to the temporary whitelist and resets the endTime for granting the
1606 * app an exemption to access network and acquire wakelocks.
1607 */
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001608 void addPowerSaveTempWhitelistAppDirectInternal(int callingUid, int appId,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001609 long duration, boolean sync, String reason) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001610 final long timeNow = SystemClock.elapsedRealtime();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001611 Runnable networkPolicyTempWhitelistCallback = null;
Dianne Hackborna750a632015-06-16 17:18:23 -07001612 synchronized (this) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001613 int callingAppId = UserHandle.getAppId(callingUid);
1614 if (callingAppId >= Process.FIRST_APPLICATION_UID) {
1615 if (!mPowerSaveWhitelistSystemAppIds.get(callingAppId)) {
1616 throw new SecurityException("Calling app " + UserHandle.formatUid(callingUid)
1617 + " is not on whitelist");
1618 }
1619 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001620 duration = Math.min(duration, mConstants.MAX_TEMP_APP_WHITELIST_DURATION);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001621 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.get(appId);
1622 final boolean newEntry = entry == null;
Dianne Hackborna750a632015-06-16 17:18:23 -07001623 // Set the new end time
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001624 if (newEntry) {
1625 entry = new Pair<>(new MutableLong(0), reason);
1626 mTempWhitelistAppIdEndTimes.put(appId, entry);
1627 }
1628 entry.first.value = timeNow + duration;
Dianne Hackborna750a632015-06-16 17:18:23 -07001629 if (DEBUG) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001630 Slog.d(TAG, "Adding AppId " + appId + " to temp whitelist. New entry: " + newEntry);
Dianne Hackborna750a632015-06-16 17:18:23 -07001631 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001632 if (newEntry) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001633 // No pending timeout for the app id, post a delayed message
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001634 try {
1635 mBatteryStats.noteEvent(BatteryStats.HistoryItem.EVENT_TEMP_WHITELIST_START,
1636 reason, appId);
1637 } catch (RemoteException e) {
1638 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001639 postTempActiveTimeoutMessage(appId, duration);
1640 updateTempWhitelistAppIdsLocked();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001641 if (mNetworkPolicyTempWhitelistCallback != null) {
1642 if (!sync) {
1643 mHandler.post(mNetworkPolicyTempWhitelistCallback);
1644 } else {
1645 networkPolicyTempWhitelistCallback = mNetworkPolicyTempWhitelistCallback;
1646 }
1647 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001648 reportTempWhitelistChangedLocked();
1649 }
1650 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001651 if (networkPolicyTempWhitelistCallback != null) {
1652 networkPolicyTempWhitelistCallback.run();
1653 }
1654 }
1655
1656 public void setNetworkPolicyTempWhitelistCallbackInternal(Runnable callback) {
1657 synchronized (this) {
1658 mNetworkPolicyTempWhitelistCallback = callback;
1659 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001660 }
1661
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001662 private void postTempActiveTimeoutMessage(int uid, long delay) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001663 if (DEBUG) {
1664 Slog.d(TAG, "postTempActiveTimeoutMessage: uid=" + uid + ", delay=" + delay);
1665 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001666 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_TEMP_APP_WHITELIST_TIMEOUT, uid, 0),
1667 delay);
1668 }
1669
1670 void checkTempAppWhitelistTimeout(int uid) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001671 final long timeNow = SystemClock.elapsedRealtime();
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001672 if (DEBUG) {
1673 Slog.d(TAG, "checkTempAppWhitelistTimeout: uid=" + uid + ", timeNow=" + timeNow);
1674 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001675 synchronized (this) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001676 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.get(uid);
1677 if (entry == null) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001678 // Nothing to do
1679 return;
1680 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001681 if (timeNow >= entry.first.value) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001682 mTempWhitelistAppIdEndTimes.delete(uid);
1683 if (DEBUG) {
1684 Slog.d(TAG, "Removing UID " + uid + " from temp whitelist");
1685 }
1686 updateTempWhitelistAppIdsLocked();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001687 if (mNetworkPolicyTempWhitelistCallback != null) {
1688 mHandler.post(mNetworkPolicyTempWhitelistCallback);
1689 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001690 reportTempWhitelistChangedLocked();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001691 try {
1692 mBatteryStats.noteEvent(BatteryStats.HistoryItem.EVENT_TEMP_WHITELIST_FINISH,
1693 entry.second, uid);
1694 } catch (RemoteException e) {
1695 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001696 } else {
1697 // Need more time
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001698 if (DEBUG) {
1699 Slog.d(TAG, "Time to remove UID " + uid + ": " + entry.first.value);
1700 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001701 postTempActiveTimeoutMessage(uid, entry.first.value - timeNow);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001702 }
1703 }
1704 }
1705
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001706 public void exitIdleInternal(String reason) {
1707 synchronized (this) {
1708 becomeActiveLocked(reason, Binder.getCallingUid());
1709 }
1710 }
1711
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -07001712 void updateConnectivityState(Intent connIntent) {
1713 ConnectivityService cm;
1714 synchronized (this) {
1715 cm = mConnectivityService;
1716 }
1717 if (cm == null) {
1718 return;
1719 }
1720 // Note: can't call out to ConnectivityService with our lock held.
1721 NetworkInfo ni = cm.getActiveNetworkInfo();
1722 synchronized (this) {
Dianne Hackborn88c41352016-04-07 15:18:58 -07001723 boolean conn;
1724 if (ni == null) {
1725 conn = false;
1726 } else {
1727 if (connIntent == null) {
1728 conn = ni.isConnected();
1729 } else {
1730 final int networkType =
1731 connIntent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1732 ConnectivityManager.TYPE_NONE);
1733 if (ni.getType() != networkType) {
1734 return;
1735 }
1736 conn = !connIntent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,
1737 false);
1738 }
1739 }
1740 if (conn != mNetworkConnected) {
1741 mNetworkConnected = conn;
1742 if (conn && mLightState == LIGHT_STATE_WAITING_FOR_NETWORK) {
1743 stepLightIdleStateLocked("network");
1744 }
1745 }
1746 }
1747 }
1748
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001749 void updateDisplayLocked() {
1750 mCurDisplay = mDisplayManager.getDisplay(Display.DEFAULT_DISPLAY);
1751 // We consider any situation where the display is showing something to be it on,
1752 // because if there is anything shown we are going to be updating it at some
1753 // frequency so can't be allowed to go into deep sleeps.
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001754 boolean screenOn = mCurDisplay.getState() == Display.STATE_ON;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001755 if (DEBUG) Slog.d(TAG, "updateDisplayLocked: screenOn=" + screenOn);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001756 if (!screenOn && mScreenOn) {
1757 mScreenOn = false;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001758 if (!mForceIdle) {
1759 becomeInactiveIfAppropriateLocked();
1760 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001761 } else if (screenOn) {
1762 mScreenOn = true;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001763 if (!mForceIdle) {
1764 becomeActiveLocked("screen", Process.myUid());
1765 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001766 }
1767 }
1768
1769 void updateChargingLocked(boolean charging) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001770 if (DEBUG) Slog.i(TAG, "updateChargingLocked: charging=" + charging);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001771 if (!charging && mCharging) {
1772 mCharging = false;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001773 if (!mForceIdle) {
1774 becomeInactiveIfAppropriateLocked();
1775 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001776 } else if (charging) {
1777 mCharging = charging;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001778 if (!mForceIdle) {
1779 becomeActiveLocked("charging", Process.myUid());
1780 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001781 }
1782 }
1783
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001784 void scheduleReportActiveLocked(String activeReason, int activeUid) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001785 Message msg = mHandler.obtainMessage(MSG_REPORT_ACTIVE, activeUid, 0, activeReason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001786 mHandler.sendMessage(msg);
1787 }
1788
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001789 void becomeActiveLocked(String activeReason, int activeUid) {
1790 if (DEBUG) Slog.i(TAG, "becomeActiveLocked, reason = " + activeReason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001791 if (mState != STATE_ACTIVE || mLightState != STATE_ACTIVE) {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001792 EventLogTags.writeDeviceIdle(STATE_ACTIVE, activeReason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001793 EventLogTags.writeDeviceIdleLight(LIGHT_STATE_ACTIVE, activeReason);
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001794 scheduleReportActiveLocked(activeReason, activeUid);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001795 mState = STATE_ACTIVE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001796 mLightState = LIGHT_STATE_ACTIVE;
Adam Lesinski31c05d12015-06-09 17:34:04 -07001797 mInactiveTimeout = mConstants.INACTIVE_TIMEOUT;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001798 mCurIdleBudget = 0;
1799 mMaintenanceStartTime = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001800 resetIdleManagementLocked();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001801 resetLightIdleManagementLocked();
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001802 addEvent(EVENT_NORMAL);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001803 }
1804 }
1805
1806 void becomeInactiveIfAppropriateLocked() {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001807 if (DEBUG) Slog.d(TAG, "becomeInactiveIfAppropriateLocked()");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001808 if ((!mScreenOn && !mCharging) || mForceIdle) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001809 // Screen has turned off; we are now going to become inactive and start
1810 // waiting to see if we will ultimately go idle.
Dianne Hackbornb6843652016-02-22 12:20:13 -08001811 if (mState == STATE_ACTIVE && mDeepEnabled) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001812 mState = STATE_INACTIVE;
1813 if (DEBUG) Slog.d(TAG, "Moved from STATE_ACTIVE to STATE_INACTIVE");
1814 resetIdleManagementLocked();
1815 scheduleAlarmLocked(mInactiveTimeout, false);
1816 EventLogTags.writeDeviceIdle(mState, "no activity");
1817 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001818 if (mLightState == LIGHT_STATE_ACTIVE && mLightEnabled) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001819 mLightState = LIGHT_STATE_INACTIVE;
1820 if (DEBUG) Slog.d(TAG, "Moved from LIGHT_STATE_ACTIVE to LIGHT_STATE_INACTIVE");
1821 resetLightIdleManagementLocked();
Dianne Hackborn953fc942016-03-29 15:36:24 -07001822 scheduleLightAlarmLocked(mConstants.LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001823 EventLogTags.writeDeviceIdleLight(mLightState, "no activity");
1824 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001825 }
1826 }
1827
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001828 void resetIdleManagementLocked() {
1829 mNextIdlePendingDelay = 0;
1830 mNextIdleDelay = 0;
Dianne Hackborn953fc942016-03-29 15:36:24 -07001831 mNextLightIdleDelay = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001832 cancelAlarmLocked();
Kevin Gabayan92f15e62016-04-04 17:52:22 -07001833 cancelSensingTimeoutAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001834 cancelLocatingLocked();
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001835 stopMonitoringMotionLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001836 mAnyMotionDetector.stop();
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001837 }
1838
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001839 void resetLightIdleManagementLocked() {
1840 cancelLightAlarmLocked();
1841 }
1842
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001843 void exitForceIdleLocked() {
1844 if (mForceIdle) {
1845 mForceIdle = false;
1846 if (mScreenOn || mCharging) {
Dianne Hackborn88c41352016-04-07 15:18:58 -07001847 becomeActiveLocked("exit-force", Process.myUid());
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001848 }
1849 }
1850 }
1851
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001852 void stepLightIdleStateLocked(String reason) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001853 if (mLightState == LIGHT_STATE_OVERRIDE) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001854 // If we are already in deep device idle mode, then
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001855 // there is nothing left to do for light mode.
1856 return;
1857 }
1858
1859 if (DEBUG) Slog.d(TAG, "stepLightIdleStateLocked: mLightState=" + mLightState);
1860 EventLogTags.writeDeviceIdleLightStep();
1861
1862 switch (mLightState) {
1863 case LIGHT_STATE_INACTIVE:
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001864 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
Dianne Hackborn953fc942016-03-29 15:36:24 -07001865 // Reset the upcoming idle delays.
1866 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001867 mMaintenanceStartTime = 0;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001868 if (!isOpsInactiveLocked()) {
1869 // We have some active ops going on... give them a chance to finish
1870 // before going in to our first idle.
1871 mLightState = LIGHT_STATE_PRE_IDLE;
1872 EventLogTags.writeDeviceIdleLight(mLightState, reason);
1873 scheduleLightAlarmLocked(mConstants.LIGHT_PRE_IDLE_TIMEOUT);
1874 break;
1875 }
1876 // Nothing active, fall through to immediately idle.
1877 case LIGHT_STATE_PRE_IDLE:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001878 case LIGHT_STATE_IDLE_MAINTENANCE:
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001879 if (mMaintenanceStartTime != 0) {
1880 long duration = SystemClock.elapsedRealtime() - mMaintenanceStartTime;
1881 if (duration < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
1882 // We didn't use up all of our minimum budget; add this to the reserve.
1883 mCurIdleBudget += (mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET-duration);
1884 } else {
1885 // We used more than our minimum budget; this comes out of the reserve.
1886 mCurIdleBudget -= (duration-mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET);
1887 }
1888 }
1889 mMaintenanceStartTime = 0;
Dianne Hackborn953fc942016-03-29 15:36:24 -07001890 scheduleLightAlarmLocked(mNextLightIdleDelay);
1891 mNextLightIdleDelay = Math.min(mConstants.LIGHT_MAX_IDLE_TIMEOUT,
1892 (long)(mNextLightIdleDelay * mConstants.LIGHT_IDLE_FACTOR));
1893 if (mNextLightIdleDelay < mConstants.LIGHT_IDLE_TIMEOUT) {
1894 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
1895 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001896 if (DEBUG) Slog.d(TAG, "Moved to LIGHT_STATE_IDLE.");
1897 mLightState = LIGHT_STATE_IDLE;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001898 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001899 addEvent(EVENT_LIGHT_IDLE);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001900 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON_LIGHT);
1901 break;
1902 case LIGHT_STATE_IDLE:
Dianne Hackborn88c41352016-04-07 15:18:58 -07001903 case LIGHT_STATE_WAITING_FOR_NETWORK:
1904 if (mNetworkConnected || mLightState == LIGHT_STATE_WAITING_FOR_NETWORK) {
1905 // We have been idling long enough, now it is time to do some work.
1906 mActiveIdleOpCount = 1;
1907 mActiveIdleWakeLock.acquire();
1908 mMaintenanceStartTime = SystemClock.elapsedRealtime();
1909 if (mCurIdleBudget < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
1910 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
1911 } else if (mCurIdleBudget > mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET) {
1912 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET;
1913 }
1914 scheduleLightAlarmLocked(mCurIdleBudget);
1915 if (DEBUG) Slog.d(TAG,
1916 "Moved from LIGHT_STATE_IDLE to LIGHT_STATE_IDLE_MAINTENANCE.");
1917 mLightState = LIGHT_STATE_IDLE_MAINTENANCE;
1918 EventLogTags.writeDeviceIdleLight(mLightState, reason);
1919 addEvent(EVENT_LIGHT_MAINTENANCE);
1920 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
1921 } else {
1922 // We'd like to do maintenance, but currently don't have network
1923 // connectivity... let's try to wait until the network comes back.
1924 // We'll only wait for another full idle period, however, and then give up.
1925 scheduleLightAlarmLocked(mNextLightIdleDelay);
1926 if (DEBUG) Slog.d(TAG, "Moved to LIGHT_WAITING_FOR_NETWORK.");
1927 mLightState = LIGHT_STATE_WAITING_FOR_NETWORK;
1928 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001929 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001930 break;
1931 }
1932 }
1933
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001934 void stepIdleStateLocked(String reason) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001935 if (DEBUG) Slog.d(TAG, "stepIdleStateLocked: mState=" + mState);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001936 EventLogTags.writeDeviceIdleStep();
1937
1938 final long now = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07001939 if ((now+mConstants.MIN_TIME_TO_ALARM) > mAlarmManager.getNextWakeFromIdleTime()) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001940 // Whoops, there is an upcoming alarm. We don't actually want to go idle.
1941 if (mState != STATE_ACTIVE) {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001942 becomeActiveLocked("alarm", Process.myUid());
Koji Fukui27b33302015-12-16 19:43:01 +09001943 becomeInactiveIfAppropriateLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001944 }
1945 return;
1946 }
1947
1948 switch (mState) {
1949 case STATE_INACTIVE:
1950 // We have now been inactive long enough, it is time to start looking
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001951 // for motion and sleep some more while doing so.
1952 startMonitoringMotionLocked();
Adam Lesinski31c05d12015-06-09 17:34:04 -07001953 scheduleAlarmLocked(mConstants.IDLE_AFTER_INACTIVE_TIMEOUT, false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001954 // Reset the upcoming idle delays.
Adam Lesinski31c05d12015-06-09 17:34:04 -07001955 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
1956 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001957 mState = STATE_IDLE_PENDING;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001958 if (DEBUG) Slog.d(TAG, "Moved from STATE_INACTIVE to STATE_IDLE_PENDING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001959 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001960 break;
1961 case STATE_IDLE_PENDING:
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001962 mState = STATE_SENSING;
1963 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE_PENDING to STATE_SENSING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001964 EventLogTags.writeDeviceIdle(mState, reason);
Kevin Gabayan92f15e62016-04-04 17:52:22 -07001965 scheduleSensingTimeoutAlarmLocked(mConstants.SENSING_TIMEOUT);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001966 cancelLocatingLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001967 mNotMoving = false;
1968 mLocated = false;
1969 mLastGenericLocation = null;
1970 mLastGpsLocation = null;
Kevin Gabayan92f15e62016-04-04 17:52:22 -07001971 mAnyMotionDetector.checkForAnyMotion();
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001972 break;
1973 case STATE_SENSING:
Kevin Gabayan92f15e62016-04-04 17:52:22 -07001974 cancelSensingTimeoutAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001975 mState = STATE_LOCATING;
1976 if (DEBUG) Slog.d(TAG, "Moved from STATE_SENSING to STATE_LOCATING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001977 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001978 scheduleAlarmLocked(mConstants.LOCATING_TIMEOUT, false);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001979 if (mLocationManager != null
1980 && mLocationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
1981 mLocationManager.requestLocationUpdates(mLocationRequest,
1982 mGenericLocationListener, mHandler.getLooper());
1983 mLocating = true;
1984 } else {
1985 mHasNetworkLocation = false;
1986 }
1987 if (mLocationManager != null
1988 && mLocationManager.getProvider(LocationManager.GPS_PROVIDER) != null) {
1989 mHasGps = true;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001990 mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 5,
1991 mGpsLocationListener, mHandler.getLooper());
Joe LaPenna23d681b2015-08-27 15:12:11 -07001992 mLocating = true;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001993 } else {
Joe LaPenna23d681b2015-08-27 15:12:11 -07001994 mHasGps = false;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001995 }
Joe LaPenna23d681b2015-08-27 15:12:11 -07001996 // If we have a location provider, we're all set, the listeners will move state
1997 // forward.
1998 if (mLocating) {
1999 break;
2000 }
2001
2002 // Otherwise, we have to move from locating into idle maintenance.
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002003 case STATE_LOCATING:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002004 cancelAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002005 cancelLocatingLocked();
2006 mAnyMotionDetector.stop();
Dianne Hackborn953fc942016-03-29 15:36:24 -07002007
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002008 case STATE_IDLE_MAINTENANCE:
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002009 scheduleAlarmLocked(mNextIdleDelay, true);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002010 if (DEBUG) Slog.d(TAG, "Moved to STATE_IDLE. Next alarm in " + mNextIdleDelay +
2011 " ms.");
Adam Lesinski31c05d12015-06-09 17:34:04 -07002012 mNextIdleDelay = (long)(mNextIdleDelay * mConstants.IDLE_FACTOR);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002013 if (DEBUG) Slog.d(TAG, "Setting mNextIdleDelay = " + mNextIdleDelay);
Adam Lesinski31c05d12015-06-09 17:34:04 -07002014 mNextIdleDelay = Math.min(mNextIdleDelay, mConstants.MAX_IDLE_TIMEOUT);
Dianne Hackborn953fc942016-03-29 15:36:24 -07002015 if (mNextIdleDelay < mConstants.IDLE_TIMEOUT) {
2016 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
2017 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002018 mState = STATE_IDLE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002019 if (mLightState != LIGHT_STATE_OVERRIDE) {
2020 mLightState = LIGHT_STATE_OVERRIDE;
2021 cancelLightAlarmLocked();
2022 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002023 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackbornb6843652016-02-22 12:20:13 -08002024 addEvent(EVENT_DEEP_IDLE);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002025 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON);
2026 break;
2027 case STATE_IDLE:
2028 // We have been idling long enough, now it is time to do some work.
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002029 mActiveIdleOpCount = 1;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002030 mActiveIdleWakeLock.acquire();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002031 scheduleAlarmLocked(mNextIdlePendingDelay, false);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002032 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE to STATE_IDLE_MAINTENANCE. " +
2033 "Next alarm in " + mNextIdlePendingDelay + " ms.");
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002034 mMaintenanceStartTime = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07002035 mNextIdlePendingDelay = Math.min(mConstants.MAX_IDLE_PENDING_TIMEOUT,
2036 (long)(mNextIdlePendingDelay * mConstants.IDLE_PENDING_FACTOR));
Dianne Hackborn953fc942016-03-29 15:36:24 -07002037 if (mNextIdlePendingDelay < mConstants.IDLE_PENDING_TIMEOUT) {
2038 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
2039 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002040 mState = STATE_IDLE_MAINTENANCE;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002041 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackbornb6843652016-02-22 12:20:13 -08002042 addEvent(EVENT_DEEP_MAINTENANCE);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002043 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
2044 break;
2045 }
2046 }
2047
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002048 void incActiveIdleOps() {
2049 synchronized (this) {
2050 mActiveIdleOpCount++;
2051 }
2052 }
2053
2054 void decActiveIdleOps() {
2055 synchronized (this) {
2056 mActiveIdleOpCount--;
2057 if (mActiveIdleOpCount <= 0) {
2058 exitMaintenanceEarlyIfNeededLocked();
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002059 mActiveIdleWakeLock.release();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002060 }
2061 }
2062 }
2063
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002064 void setJobsActive(boolean active) {
2065 synchronized (this) {
2066 mJobsActive = active;
Yao Chenca5edbb2016-01-13 14:44:36 -08002067 reportMaintenanceActivityIfNeededLocked();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002068 if (!active) {
2069 exitMaintenanceEarlyIfNeededLocked();
2070 }
2071 }
2072 }
2073
2074 void setAlarmsActive(boolean active) {
2075 synchronized (this) {
2076 mAlarmsActive = active;
2077 if (!active) {
2078 exitMaintenanceEarlyIfNeededLocked();
2079 }
2080 }
2081 }
2082
Yao Chenca5edbb2016-01-13 14:44:36 -08002083 boolean registerMaintenanceActivityListener(IMaintenanceActivityListener listener) {
2084 synchronized (this) {
2085 mMaintenanceActivityListeners.register(listener);
2086 return mReportedMaintenanceActivity;
2087 }
2088 }
2089
2090 void unregisterMaintenanceActivityListener(IMaintenanceActivityListener listener) {
2091 synchronized (this) {
2092 mMaintenanceActivityListeners.unregister(listener);
2093 }
2094 }
2095
2096 void reportMaintenanceActivityIfNeededLocked() {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07002097 boolean active = mJobsActive;
Yao Chenca5edbb2016-01-13 14:44:36 -08002098 if (active == mReportedMaintenanceActivity) {
2099 return;
2100 }
2101 mReportedMaintenanceActivity = active;
2102 Message msg = mHandler.obtainMessage(MSG_REPORT_MAINTENANCE_ACTIVITY,
2103 mReportedMaintenanceActivity ? 1 : 0, 0);
2104 mHandler.sendMessage(msg);
2105 }
2106
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002107 boolean isOpsInactiveLocked() {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07002108 return mActiveIdleOpCount <= 0 && !mJobsActive && !mAlarmsActive;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002109 }
2110
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002111 void exitMaintenanceEarlyIfNeededLocked() {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002112 if (mState == STATE_IDLE_MAINTENANCE || mLightState == LIGHT_STATE_IDLE_MAINTENANCE
2113 || mLightState == LIGHT_STATE_PRE_IDLE) {
2114 if (isOpsInactiveLocked()) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002115 final long now = SystemClock.elapsedRealtime();
2116 if (DEBUG) {
2117 StringBuilder sb = new StringBuilder();
2118 sb.append("Exit: start=");
2119 TimeUtils.formatDuration(mMaintenanceStartTime, sb);
2120 sb.append(" now=");
2121 TimeUtils.formatDuration(now, sb);
2122 Slog.d(TAG, sb.toString());
2123 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002124 if (mState == STATE_IDLE_MAINTENANCE) {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002125 stepIdleStateLocked("s:early");
2126 } else if (mLightState == LIGHT_STATE_PRE_IDLE) {
2127 stepLightIdleStateLocked("s:predone");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002128 } else {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002129 stepLightIdleStateLocked("s:early");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002130 }
2131 }
2132 }
2133 }
2134
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002135 void motionLocked() {
2136 if (DEBUG) Slog.d(TAG, "motionLocked()");
2137 // The motion sensor will have been disabled at this point
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002138 handleMotionDetectedLocked(mConstants.MOTION_INACTIVE_TIMEOUT, "motion");
2139 }
2140
2141 void handleMotionDetectedLocked(long timeout, String type) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002142 // The device is not yet active, so we want to go back to the pending idle
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002143 // state to wait again for no motion. Note that we only monitor for motion
2144 // after moving out of the inactive state, so no need to worry about that.
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002145 boolean becomeInactive = false;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002146 if (mState != STATE_ACTIVE) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002147 scheduleReportActiveLocked(type, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002148 mState = STATE_ACTIVE;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002149 mInactiveTimeout = timeout;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002150 mCurIdleBudget = 0;
2151 mMaintenanceStartTime = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002152 EventLogTags.writeDeviceIdle(mState, type);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002153 addEvent(EVENT_NORMAL);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002154 becomeInactive = true;
2155 }
2156 if (mLightState == LIGHT_STATE_OVERRIDE) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002157 // We went out of light idle mode because we had started deep idle mode... let's
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002158 // now go back and reset things so we resume light idling if appropriate.
2159 mLightState = STATE_ACTIVE;
2160 EventLogTags.writeDeviceIdleLight(mLightState, type);
2161 becomeInactive = true;
2162 }
2163 if (becomeInactive) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002164 becomeInactiveIfAppropriateLocked();
2165 }
2166 }
2167
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002168 void receivedGenericLocationLocked(Location location) {
2169 if (mState != STATE_LOCATING) {
2170 cancelLocatingLocked();
2171 return;
2172 }
2173 if (DEBUG) Slog.d(TAG, "Generic location: " + location);
2174 mLastGenericLocation = new Location(location);
Joe LaPenna23d681b2015-08-27 15:12:11 -07002175 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY && mHasGps) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002176 return;
2177 }
2178 mLocated = true;
2179 if (mNotMoving) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002180 stepIdleStateLocked("s:location");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002181 }
2182 }
2183
2184 void receivedGpsLocationLocked(Location location) {
2185 if (mState != STATE_LOCATING) {
2186 cancelLocatingLocked();
2187 return;
2188 }
2189 if (DEBUG) Slog.d(TAG, "GPS location: " + location);
2190 mLastGpsLocation = new Location(location);
2191 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY) {
2192 return;
2193 }
2194 mLocated = true;
2195 if (mNotMoving) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002196 stepIdleStateLocked("s:gps");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002197 }
2198 }
2199
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002200 void startMonitoringMotionLocked() {
2201 if (DEBUG) Slog.d(TAG, "startMonitoringMotionLocked()");
2202 if (mMotionSensor != null && !mMotionListener.active) {
2203 mMotionListener.registerLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002204 }
2205 }
2206
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002207 void stopMonitoringMotionLocked() {
2208 if (DEBUG) Slog.d(TAG, "stopMonitoringMotionLocked()");
2209 if (mMotionSensor != null && mMotionListener.active) {
2210 mMotionListener.unregisterLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002211 }
2212 }
2213
2214 void cancelAlarmLocked() {
2215 if (mNextAlarmTime != 0) {
2216 mNextAlarmTime = 0;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002217 mAlarmManager.cancel(mDeepAlarmListener);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002218 }
2219 }
2220
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002221 void cancelLightAlarmLocked() {
2222 if (mNextLightAlarmTime != 0) {
2223 mNextLightAlarmTime = 0;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002224 mAlarmManager.cancel(mLightAlarmListener);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002225 }
2226 }
2227
2228 void cancelLocatingLocked() {
2229 if (mLocating) {
2230 mLocationManager.removeUpdates(mGenericLocationListener);
2231 mLocationManager.removeUpdates(mGpsLocationListener);
2232 mLocating = false;
2233 }
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002234 }
2235
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002236 void cancelSensingTimeoutAlarmLocked() {
2237 if (mNextSensingTimeoutAlarmTime != 0) {
2238 mNextSensingTimeoutAlarmTime = 0;
2239 mAlarmManager.cancel(mSensingTimeoutAlarmListener);
2240 }
2241 }
2242
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002243 void scheduleAlarmLocked(long delay, boolean idleUntil) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002244 if (DEBUG) Slog.d(TAG, "scheduleAlarmLocked(" + delay + ", " + idleUntil + ")");
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002245 if (mMotionSensor == null) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07002246 // If there is no motion sensor on this device, then we won't schedule
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002247 // alarms, because we can't determine if the device is not moving. This effectively
Joe LaPenna23d681b2015-08-27 15:12:11 -07002248 // turns off normal execution of device idling, although it is still possible to
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002249 // manually poke it by pretending like the alarm is going off.
2250 return;
2251 }
2252 mNextAlarmTime = SystemClock.elapsedRealtime() + delay;
2253 if (idleUntil) {
2254 mAlarmManager.setIdleUntil(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002255 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002256 } else {
2257 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002258 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002259 }
2260 }
2261
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002262 void scheduleLightAlarmLocked(long delay) {
2263 if (DEBUG) Slog.d(TAG, "scheduleLightAlarmLocked(" + delay + ")");
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002264 mNextLightAlarmTime = SystemClock.elapsedRealtime() + delay;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002265 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002266 mNextLightAlarmTime, "DeviceIdleController.light", mLightAlarmListener, mHandler);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002267 }
2268
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002269 void scheduleSensingTimeoutAlarmLocked(long delay) {
2270 if (DEBUG) Slog.d(TAG, "scheduleSensingAlarmLocked(" + delay + ")");
2271 mNextSensingTimeoutAlarmTime = SystemClock.elapsedRealtime() + delay;
2272 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, mNextSensingTimeoutAlarmTime,
2273 "DeviceIdleController.sensing", mSensingTimeoutAlarmListener, mHandler);
2274 }
2275
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002276 private static int[] buildAppIdArray(ArrayMap<String, Integer> systemApps,
2277 ArrayMap<String, Integer> userApps, SparseBooleanArray outAppIds) {
2278 outAppIds.clear();
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002279 if (systemApps != null) {
2280 for (int i = 0; i < systemApps.size(); i++) {
2281 outAppIds.put(systemApps.valueAt(i), true);
2282 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002283 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002284 if (userApps != null) {
2285 for (int i = 0; i < userApps.size(); i++) {
2286 outAppIds.put(userApps.valueAt(i), true);
2287 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002288 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002289 int size = outAppIds.size();
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002290 int[] appids = new int[size];
2291 for (int i = 0; i < size; i++) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002292 appids[i] = outAppIds.keyAt(i);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002293 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002294 return appids;
2295 }
2296
2297 private void updateWhitelistAppIdsLocked() {
2298 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(mPowerSaveWhitelistAppsExceptIdle,
2299 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistExceptIdleAppIds);
2300 mPowerSaveWhitelistAllAppIdArray = buildAppIdArray(mPowerSaveWhitelistApps,
2301 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistAllAppIds);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002302 mPowerSaveWhitelistUserAppIdArray = buildAppIdArray(null,
2303 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistUserAppIds);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002304 if (mLocalPowerManager != null) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002305 if (DEBUG) {
2306 Slog.d(TAG, "Setting wakelock whitelist to "
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002307 + Arrays.toString(mPowerSaveWhitelistAllAppIdArray));
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002308 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002309 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002310 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002311 if (mLocalAlarmManager != null) {
2312 if (DEBUG) {
2313 Slog.d(TAG, "Setting alarm whitelist to "
2314 + Arrays.toString(mPowerSaveWhitelistUserAppIdArray));
2315 }
2316 mLocalAlarmManager.setDeviceIdleUserWhitelist(mPowerSaveWhitelistUserAppIdArray);
2317 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002318 }
2319
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002320 private void updateTempWhitelistAppIdsLocked() {
2321 final int size = mTempWhitelistAppIdEndTimes.size();
2322 if (mTempWhitelistAppIdArray.length != size) {
2323 mTempWhitelistAppIdArray = new int[size];
2324 }
2325 for (int i = 0; i < size; i++) {
2326 mTempWhitelistAppIdArray[i] = mTempWhitelistAppIdEndTimes.keyAt(i);
2327 }
2328 if (mLocalPowerManager != null) {
2329 if (DEBUG) {
2330 Slog.d(TAG, "Setting wakelock temp whitelist to "
2331 + Arrays.toString(mTempWhitelistAppIdArray));
2332 }
2333 mLocalPowerManager.setDeviceIdleTempWhitelist(mTempWhitelistAppIdArray);
2334 }
2335 }
2336
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002337 private void reportPowerSaveWhitelistChangedLocked() {
2338 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
2339 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Xiaohui Chene4de5a02015-09-22 15:33:31 -07002340 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002341 }
2342
2343 private void reportTempWhitelistChangedLocked() {
2344 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_TEMP_WHITELIST_CHANGED);
2345 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Xiaohui Chene4de5a02015-09-22 15:33:31 -07002346 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002347 }
2348
2349 void readConfigFileLocked() {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002350 if (DEBUG) Slog.d(TAG, "Reading config from " + mConfigFile.getBaseFile());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002351 mPowerSaveWhitelistUserApps.clear();
2352 FileInputStream stream;
2353 try {
2354 stream = mConfigFile.openRead();
2355 } catch (FileNotFoundException e) {
2356 return;
2357 }
2358 try {
2359 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002360 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002361 readConfigFileLocked(parser);
2362 } catch (XmlPullParserException e) {
2363 } finally {
2364 try {
2365 stream.close();
2366 } catch (IOException e) {
2367 }
2368 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002369 }
2370
2371 private void readConfigFileLocked(XmlPullParser parser) {
2372 final PackageManager pm = getContext().getPackageManager();
2373
2374 try {
2375 int type;
2376 while ((type = parser.next()) != XmlPullParser.START_TAG
2377 && type != XmlPullParser.END_DOCUMENT) {
2378 ;
2379 }
2380
2381 if (type != XmlPullParser.START_TAG) {
2382 throw new IllegalStateException("no start tag found");
2383 }
2384
2385 int outerDepth = parser.getDepth();
2386 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2387 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2388 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2389 continue;
2390 }
2391
2392 String tagName = parser.getName();
2393 if (tagName.equals("wl")) {
2394 String name = parser.getAttributeValue(null, "n");
2395 if (name != null) {
2396 try {
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07002397 ApplicationInfo ai = pm.getApplicationInfo(name,
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07002398 PackageManager.MATCH_UNINSTALLED_PACKAGES);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002399 mPowerSaveWhitelistUserApps.put(ai.packageName,
2400 UserHandle.getAppId(ai.uid));
2401 } catch (PackageManager.NameNotFoundException e) {
2402 }
2403 }
2404 } else {
2405 Slog.w(TAG, "Unknown element under <config>: "
2406 + parser.getName());
2407 XmlUtils.skipCurrentTag(parser);
2408 }
2409 }
2410
2411 } catch (IllegalStateException e) {
2412 Slog.w(TAG, "Failed parsing config " + e);
2413 } catch (NullPointerException e) {
2414 Slog.w(TAG, "Failed parsing config " + e);
2415 } catch (NumberFormatException e) {
2416 Slog.w(TAG, "Failed parsing config " + e);
2417 } catch (XmlPullParserException e) {
2418 Slog.w(TAG, "Failed parsing config " + e);
2419 } catch (IOException e) {
2420 Slog.w(TAG, "Failed parsing config " + e);
2421 } catch (IndexOutOfBoundsException e) {
2422 Slog.w(TAG, "Failed parsing config " + e);
2423 }
2424 }
2425
2426 void writeConfigFileLocked() {
2427 mHandler.removeMessages(MSG_WRITE_CONFIG);
2428 mHandler.sendEmptyMessageDelayed(MSG_WRITE_CONFIG, 5000);
2429 }
2430
2431 void handleWriteConfigFile() {
2432 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
2433
2434 try {
2435 synchronized (this) {
2436 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002437 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002438 writeConfigFileLocked(out);
2439 }
2440 } catch (IOException e) {
2441 }
2442
2443 synchronized (mConfigFile) {
2444 FileOutputStream stream = null;
2445 try {
2446 stream = mConfigFile.startWrite();
2447 memStream.writeTo(stream);
2448 stream.flush();
2449 FileUtils.sync(stream);
2450 stream.close();
2451 mConfigFile.finishWrite(stream);
2452 } catch (IOException e) {
2453 Slog.w(TAG, "Error writing config file", e);
2454 mConfigFile.failWrite(stream);
2455 }
2456 }
2457 }
2458
2459 void writeConfigFileLocked(XmlSerializer out) throws IOException {
2460 out.startDocument(null, true);
2461 out.startTag(null, "config");
2462 for (int i=0; i<mPowerSaveWhitelistUserApps.size(); i++) {
2463 String name = mPowerSaveWhitelistUserApps.keyAt(i);
2464 out.startTag(null, "wl");
2465 out.attribute(null, "n", name);
2466 out.endTag(null, "wl");
2467 }
2468 out.endTag(null, "config");
2469 out.endDocument();
2470 }
2471
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002472 static void dumpHelp(PrintWriter pw) {
2473 pw.println("Device idle controller (deviceidle) commands:");
2474 pw.println(" help");
2475 pw.println(" Print this help text.");
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002476 pw.println(" step [light|deep]");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002477 pw.println(" Immediately step to next state, without waiting for alarm.");
Dianne Hackborn88c41352016-04-07 15:18:58 -07002478 pw.println(" force-idle [light|deep]");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002479 pw.println(" Force directly into idle mode, regardless of other device state.");
Dianne Hackborn88c41352016-04-07 15:18:58 -07002480 pw.println(" force-inactive");
2481 pw.println(" Force to be inactive, ready to freely step idle states.");
2482 pw.println(" unforce");
2483 pw.println(" Resume normal functioning after force-idle or force-inactive.");
2484 pw.println(" get [light|deep|force|screen|charging|network]");
2485 pw.println(" Retrieve the current given state.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002486 pw.println(" disable [light|deep|all]");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002487 pw.println(" Completely disable device idle mode.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002488 pw.println(" enable [light|deep|all]");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002489 pw.println(" Re-enable device idle mode after it had previously been disabled.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002490 pw.println(" enabled [light|deep|all]");
Dianne Hackborn92617032015-06-19 15:32:19 -07002491 pw.println(" Print 1 if device idle mode is currently enabled, else 0.");
Dianne Hackborn1b139682015-07-06 15:13:37 -07002492 pw.println(" whitelist");
2493 pw.println(" Print currently whitelisted apps.");
Dianne Hackborn92617032015-06-19 15:32:19 -07002494 pw.println(" whitelist [package ...]");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002495 pw.println(" Add (prefix with +) or remove (prefix with -) packages.");
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002496 pw.println(" tempwhitelist");
2497 pw.println(" Print packages that are temporarily whitelisted.");
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002498 pw.println(" tempwhitelist [-u] [package ..]");
Dianne Hackborn92617032015-06-19 15:32:19 -07002499 pw.println(" Temporarily place packages in whitelist for 10 seconds.");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002500 }
2501
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002502 class Shell extends ShellCommand {
2503 int userId = UserHandle.USER_SYSTEM;
2504
2505 @Override
2506 public int onCommand(String cmd) {
2507 return onShellCommand(this, cmd);
2508 }
2509
2510 @Override
2511 public void onHelp() {
2512 PrintWriter pw = getOutPrintWriter();
2513 dumpHelp(pw);
2514 }
2515 }
2516
2517 int onShellCommand(Shell shell, String cmd) {
2518 PrintWriter pw = shell.getOutPrintWriter();
2519 if ("step".equals(cmd)) {
2520 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2521 null);
2522 synchronized (this) {
2523 long token = Binder.clearCallingIdentity();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002524 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002525 try {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002526 if (arg == null || "deep".equals(arg)) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002527 stepIdleStateLocked("s:shell");
2528 pw.print("Stepped to deep: ");
2529 pw.println(stateToString(mState));
2530 } else if ("light".equals(arg)) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002531 stepLightIdleStateLocked("s:shell");
2532 pw.print("Stepped to light: "); pw.println(lightStateToString(mLightState));
2533 } else {
2534 pw.println("Unknown idle mode: " + arg);
2535 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002536 } finally {
2537 Binder.restoreCallingIdentity(token);
2538 }
2539 }
2540 } else if ("force-idle".equals(cmd)) {
2541 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2542 null);
2543 synchronized (this) {
2544 long token = Binder.clearCallingIdentity();
Dianne Hackborn88c41352016-04-07 15:18:58 -07002545 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002546 try {
Dianne Hackborn88c41352016-04-07 15:18:58 -07002547 if (arg == null || "deep".equals(arg)) {
2548 if (!mDeepEnabled) {
2549 pw.println("Unable to go deep idle; not enabled");
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002550 return -1;
2551 }
Dianne Hackborn88c41352016-04-07 15:18:58 -07002552 mForceIdle = true;
2553 becomeInactiveIfAppropriateLocked();
2554 int curState = mState;
2555 while (curState != STATE_IDLE) {
2556 stepIdleStateLocked("s:shell");
2557 if (curState == mState) {
2558 pw.print("Unable to go deep idle; stopped at ");
2559 pw.println(stateToString(mState));
2560 exitForceIdleLocked();
2561 return -1;
2562 }
2563 curState = mState;
2564 }
2565 pw.println("Now forced in to deep idle mode");
2566 } else if ("light".equals(arg)) {
2567 mForceIdle = true;
2568 becomeInactiveIfAppropriateLocked();
2569 int curLightState = mLightState;
2570 while (curLightState != LIGHT_STATE_IDLE) {
2571 stepIdleStateLocked("s:shell");
2572 if (curLightState == mLightState) {
2573 pw.print("Unable to go light idle; stopped at ");
2574 pw.println(lightStateToString(mLightState));
2575 exitForceIdleLocked();
2576 return -1;
2577 }
2578 curLightState = mLightState;
2579 }
2580 pw.println("Now forced in to light idle mode");
2581 } else {
2582 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002583 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002584 } finally {
2585 Binder.restoreCallingIdentity(token);
2586 }
2587 }
Dianne Hackborn88c41352016-04-07 15:18:58 -07002588 } else if ("force-inactive".equals(cmd)) {
2589 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2590 null);
2591 synchronized (this) {
2592 long token = Binder.clearCallingIdentity();
2593 try {
2594 mForceIdle = true;
2595 becomeInactiveIfAppropriateLocked();
2596 pw.print("Light state: ");
2597 pw.print(lightStateToString(mLightState));
2598 pw.print(", deep state: ");
2599 pw.println(stateToString(mState));
2600 } finally {
2601 Binder.restoreCallingIdentity(token);
2602 }
2603 }
2604 } else if ("unforce".equals(cmd)) {
2605 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2606 null);
2607 synchronized (this) {
2608 long token = Binder.clearCallingIdentity();
2609 try {
2610 exitForceIdleLocked();
2611 pw.print("Light state: ");
2612 pw.print(lightStateToString(mLightState));
2613 pw.print(", deep state: ");
2614 pw.println(stateToString(mState));
2615 } finally {
2616 Binder.restoreCallingIdentity(token);
2617 }
2618 }
2619 } else if ("get".equals(cmd)) {
2620 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2621 null);
2622 synchronized (this) {
2623 String arg = shell.getNextArg();
2624 if (arg != null) {
2625 long token = Binder.clearCallingIdentity();
2626 try {
2627 switch (arg) {
2628 case "light": pw.println(lightStateToString(mLightState)); break;
2629 case "deep": pw.println(stateToString(mState)); break;
2630 case "force": pw.println(mForceIdle); break;
2631 case "screen": pw.println(mScreenOn); break;
2632 case "charging": pw.println(mCharging); break;
2633 case "network": pw.println(mNetworkConnected); break;
2634 default: pw.println("Unknown get option: " + arg); break;
2635 }
2636 } finally {
2637 Binder.restoreCallingIdentity(token);
2638 }
2639 } else {
2640 pw.println("Argument required");
2641 }
2642 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002643 } else if ("disable".equals(cmd)) {
2644 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2645 null);
2646 synchronized (this) {
2647 long token = Binder.clearCallingIdentity();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002648 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002649 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002650 boolean becomeActive = false;
2651 boolean valid = false;
2652 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
2653 valid = true;
2654 if (mDeepEnabled) {
2655 mDeepEnabled = false;
2656 becomeActive = true;
2657 pw.println("Deep idle mode disabled");
2658 }
2659 }
2660 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
2661 valid = true;
2662 if (mLightEnabled) {
2663 mLightEnabled = false;
2664 becomeActive = true;
2665 pw.println("Light idle mode disabled");
2666 }
2667 }
2668 if (becomeActive) {
2669 becomeActiveLocked((arg == null ? "all" : arg) + "-disabled",
2670 Process.myUid());
2671 }
2672 if (!valid) {
2673 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002674 }
2675 } finally {
2676 Binder.restoreCallingIdentity(token);
2677 }
2678 }
2679 } else if ("enable".equals(cmd)) {
2680 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2681 null);
2682 synchronized (this) {
2683 long token = Binder.clearCallingIdentity();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002684 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002685 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002686 boolean becomeInactive = false;
2687 boolean valid = false;
2688 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
2689 valid = true;
2690 if (!mDeepEnabled) {
2691 mDeepEnabled = true;
2692 becomeInactive = true;
2693 pw.println("Deep idle mode enabled");
2694 }
2695 }
2696 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
2697 valid = true;
2698 if (!mLightEnabled) {
2699 mLightEnabled = true;
2700 becomeInactive = true;
2701 pw.println("Light idle mode enable");
2702 }
2703 }
2704 if (becomeInactive) {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002705 becomeInactiveIfAppropriateLocked();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002706 }
2707 if (!valid) {
2708 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002709 }
2710 } finally {
2711 Binder.restoreCallingIdentity(token);
2712 }
2713 }
2714 } else if ("enabled".equals(cmd)) {
2715 synchronized (this) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002716 String arg = shell.getNextArg();
2717 if (arg == null || "all".equals(arg)) {
2718 pw.println(mDeepEnabled && mLightEnabled ? "1" : 0);
2719 } else if ("deep".equals(arg)) {
2720 pw.println(mDeepEnabled ? "1" : 0);
2721 } else if ("light".equals(arg)) {
2722 pw.println(mLightEnabled ? "1" : 0);
2723 } else {
2724 pw.println("Unknown idle mode: " + arg);
2725 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002726 }
2727 } else if ("whitelist".equals(cmd)) {
2728 long token = Binder.clearCallingIdentity();
2729 try {
2730 String arg = shell.getNextArg();
2731 if (arg != null) {
2732 getContext().enforceCallingOrSelfPermission(
2733 android.Manifest.permission.DEVICE_POWER, null);
2734 do {
2735 if (arg.length() < 1 || (arg.charAt(0) != '-'
Felipe Lemef8a46232016-02-10 13:51:54 -08002736 && arg.charAt(0) != '+' && arg.charAt(0) != '=')) {
2737 pw.println("Package must be prefixed with +, -, or =: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002738 return -1;
2739 }
2740 char op = arg.charAt(0);
2741 String pkg = arg.substring(1);
2742 if (op == '+') {
2743 if (addPowerSaveWhitelistAppInternal(pkg)) {
2744 pw.println("Added: " + pkg);
2745 } else {
2746 pw.println("Unknown package: " + pkg);
2747 }
Felipe Lemef8a46232016-02-10 13:51:54 -08002748 } else if (op == '-') {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002749 if (removePowerSaveWhitelistAppInternal(pkg)) {
2750 pw.println("Removed: " + pkg);
2751 }
Felipe Lemef8a46232016-02-10 13:51:54 -08002752 } else {
2753 pw.println(getPowerSaveWhitelistAppInternal(pkg));
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002754 }
2755 } while ((arg=shell.getNextArg()) != null);
2756 } else {
2757 synchronized (this) {
2758 for (int j=0; j<mPowerSaveWhitelistAppsExceptIdle.size(); j++) {
2759 pw.print("system-excidle,");
2760 pw.print(mPowerSaveWhitelistAppsExceptIdle.keyAt(j));
2761 pw.print(",");
2762 pw.println(mPowerSaveWhitelistAppsExceptIdle.valueAt(j));
2763 }
2764 for (int j=0; j<mPowerSaveWhitelistApps.size(); j++) {
2765 pw.print("system,");
2766 pw.print(mPowerSaveWhitelistApps.keyAt(j));
2767 pw.print(",");
2768 pw.println(mPowerSaveWhitelistApps.valueAt(j));
2769 }
2770 for (int j=0; j<mPowerSaveWhitelistUserApps.size(); j++) {
2771 pw.print("user,");
2772 pw.print(mPowerSaveWhitelistUserApps.keyAt(j));
2773 pw.print(",");
2774 pw.println(mPowerSaveWhitelistUserApps.valueAt(j));
2775 }
2776 }
2777 }
2778 } finally {
2779 Binder.restoreCallingIdentity(token);
2780 }
2781 } else if ("tempwhitelist".equals(cmd)) {
2782 String opt;
2783 while ((opt=shell.getNextOption()) != null) {
2784 if ("-u".equals(opt)) {
2785 opt = shell.getNextArg();
2786 if (opt == null) {
2787 pw.println("-u requires a user number");
2788 return -1;
2789 }
2790 shell.userId = Integer.parseInt(opt);
2791 }
2792 }
2793 String arg = shell.getNextArg();
2794 if (arg != null) {
2795 try {
2796 addPowerSaveTempWhitelistAppChecked(arg, 10000L, shell.userId, "shell");
2797 } catch (RemoteException re) {
2798 pw.println("Failed: " + re);
2799 }
2800 } else {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002801 dumpTempWhitelistSchedule(pw, false);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002802 }
2803 } else {
2804 return shell.handleDefaultCommands(cmd);
2805 }
2806 return 0;
2807 }
2808
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002809 void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2810 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2811 != PackageManager.PERMISSION_GRANTED) {
2812 pw.println("Permission Denial: can't dump DeviceIdleController from from pid="
2813 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2814 + " without permission " + android.Manifest.permission.DUMP);
2815 return;
2816 }
2817
2818 if (args != null) {
Xiaohui Chen7c696362015-09-16 09:56:14 -07002819 int userId = UserHandle.USER_SYSTEM;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002820 for (int i=0; i<args.length; i++) {
2821 String arg = args[i];
2822 if ("-h".equals(arg)) {
2823 dumpHelp(pw);
2824 return;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002825 } else if ("-u".equals(arg)) {
2826 i++;
2827 if (i < args.length) {
2828 arg = args[i];
2829 userId = Integer.parseInt(arg);
2830 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002831 } else if ("-a".equals(arg)) {
2832 // Ignore, we always dump all.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002833 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
2834 pw.println("Unknown option: " + arg);
2835 return;
2836 } else {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002837 Shell shell = new Shell();
2838 shell.userId = userId;
2839 String[] newArgs = new String[args.length-i];
2840 System.arraycopy(args, i, newArgs, 0, args.length-i);
2841 shell.exec(mBinderService, null, fd, null, newArgs, new ResultReceiver(null));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002842 return;
2843 }
2844 }
2845 }
2846
2847 synchronized (this) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002848 mConstants.dump(pw);
2849
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002850 if (mEventCmds[0] != EVENT_NULL) {
2851 pw.println(" Idling history:");
2852 long now = SystemClock.elapsedRealtime();
2853 for (int i=EVENT_BUFFER_SIZE-1; i>=0; i--) {
2854 int cmd = mEventCmds[i];
2855 if (cmd == EVENT_NULL) {
2856 continue;
2857 }
2858 String label;
2859 switch (mEventCmds[i]) {
2860 case EVENT_NORMAL: label = " normal"; break;
2861 case EVENT_LIGHT_IDLE: label = " light-idle"; break;
2862 case EVENT_LIGHT_MAINTENANCE: label = "light-maint"; break;
Dianne Hackbornb6843652016-02-22 12:20:13 -08002863 case EVENT_DEEP_IDLE: label = " deep-idle"; break;
2864 case EVENT_DEEP_MAINTENANCE: label = " deep-maint"; break;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002865 default: label = " ??"; break;
2866 }
2867 pw.print(" ");
2868 pw.print(label);
2869 pw.print(": ");
2870 TimeUtils.formatDuration(mEventTimes[i], now, pw);;
2871 pw.println();
2872 }
2873 }
2874
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002875 int size = mPowerSaveWhitelistAppsExceptIdle.size();
2876 if (size > 0) {
2877 pw.println(" Whitelist (except idle) system apps:");
2878 for (int i = 0; i < size; i++) {
2879 pw.print(" ");
2880 pw.println(mPowerSaveWhitelistAppsExceptIdle.keyAt(i));
2881 }
2882 }
2883 size = mPowerSaveWhitelistApps.size();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002884 if (size > 0) {
2885 pw.println(" Whitelist system apps:");
2886 for (int i = 0; i < size; i++) {
2887 pw.print(" ");
2888 pw.println(mPowerSaveWhitelistApps.keyAt(i));
2889 }
2890 }
2891 size = mPowerSaveWhitelistUserApps.size();
2892 if (size > 0) {
2893 pw.println(" Whitelist user apps:");
2894 for (int i = 0; i < size; i++) {
2895 pw.print(" ");
2896 pw.println(mPowerSaveWhitelistUserApps.keyAt(i));
2897 }
2898 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002899 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2900 if (size > 0) {
2901 pw.println(" Whitelist (except idle) all app ids:");
2902 for (int i = 0; i < size; i++) {
2903 pw.print(" ");
2904 pw.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2905 pw.println();
2906 }
2907 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002908 size = mPowerSaveWhitelistUserAppIds.size();
2909 if (size > 0) {
2910 pw.println(" Whitelist user app ids:");
2911 for (int i = 0; i < size; i++) {
2912 pw.print(" ");
2913 pw.print(mPowerSaveWhitelistUserAppIds.keyAt(i));
2914 pw.println();
2915 }
2916 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002917 size = mPowerSaveWhitelistAllAppIds.size();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002918 if (size > 0) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002919 pw.println(" Whitelist all app ids:");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002920 for (int i = 0; i < size; i++) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002921 pw.print(" ");
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002922 pw.print(mPowerSaveWhitelistAllAppIds.keyAt(i));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002923 pw.println();
2924 }
2925 }
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002926 dumpTempWhitelistSchedule(pw, true);
2927
Dianne Hackborna750a632015-06-16 17:18:23 -07002928 size = mTempWhitelistAppIdArray != null ? mTempWhitelistAppIdArray.length : 0;
2929 if (size > 0) {
2930 pw.println(" Temp whitelist app ids:");
2931 for (int i = 0; i < size; i++) {
2932 pw.print(" ");
2933 pw.print(mTempWhitelistAppIdArray[i]);
2934 pw.println();
2935 }
2936 }
Adam Lesinski31c05d12015-06-09 17:34:04 -07002937
Dianne Hackbornb6843652016-02-22 12:20:13 -08002938 pw.print(" mLightEnabled="); pw.print(mLightEnabled);
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002939 pw.print(" mDeepEnabled="); pw.println(mDeepEnabled);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002940 pw.print(" mForceIdle="); pw.println(mForceIdle);
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002941 pw.print(" mMotionSensor="); pw.println(mMotionSensor);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002942 pw.print(" mCurDisplay="); pw.println(mCurDisplay);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002943 pw.print(" mScreenOn="); pw.println(mScreenOn);
Dianne Hackborn88c41352016-04-07 15:18:58 -07002944 pw.print(" mNetworkConnected="); pw.println(mNetworkConnected);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002945 pw.print(" mCharging="); pw.println(mCharging);
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002946 pw.print(" mMotionActive="); pw.println(mMotionListener.active);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002947 pw.print(" mNotMoving="); pw.println(mNotMoving);
Joe LaPenna23d681b2015-08-27 15:12:11 -07002948 pw.print(" mLocating="); pw.print(mLocating); pw.print(" mHasGps=");
2949 pw.print(mHasGps); pw.print(" mHasNetwork=");
2950 pw.print(mHasNetworkLocation); pw.print(" mLocated="); pw.println(mLocated);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002951 if (mLastGenericLocation != null) {
2952 pw.print(" mLastGenericLocation="); pw.println(mLastGenericLocation);
2953 }
2954 if (mLastGpsLocation != null) {
2955 pw.print(" mLastGpsLocation="); pw.println(mLastGpsLocation);
2956 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002957 pw.print(" mState="); pw.print(stateToString(mState));
2958 pw.print(" mLightState=");
2959 pw.println(lightStateToString(mLightState));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002960 pw.print(" mInactiveTimeout="); TimeUtils.formatDuration(mInactiveTimeout, pw);
2961 pw.println();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002962 if (mActiveIdleOpCount != 0) {
2963 pw.print(" mActiveIdleOpCount="); pw.println(mActiveIdleOpCount);
2964 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002965 if (mNextAlarmTime != 0) {
2966 pw.print(" mNextAlarmTime=");
2967 TimeUtils.formatDuration(mNextAlarmTime, SystemClock.elapsedRealtime(), pw);
2968 pw.println();
2969 }
2970 if (mNextIdlePendingDelay != 0) {
2971 pw.print(" mNextIdlePendingDelay=");
2972 TimeUtils.formatDuration(mNextIdlePendingDelay, pw);
2973 pw.println();
2974 }
2975 if (mNextIdleDelay != 0) {
2976 pw.print(" mNextIdleDelay=");
2977 TimeUtils.formatDuration(mNextIdleDelay, pw);
2978 pw.println();
2979 }
Dianne Hackborn953fc942016-03-29 15:36:24 -07002980 if (mNextLightIdleDelay != 0) {
2981 pw.print(" mNextIdleDelay=");
2982 TimeUtils.formatDuration(mNextLightIdleDelay, pw);
2983 pw.println();
2984 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002985 if (mNextLightAlarmTime != 0) {
2986 pw.print(" mNextLightAlarmTime=");
2987 TimeUtils.formatDuration(mNextLightAlarmTime, SystemClock.elapsedRealtime(), pw);
2988 pw.println();
2989 }
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002990 if (mCurIdleBudget != 0) {
2991 pw.print(" mCurIdleBudget=");
2992 TimeUtils.formatDuration(mCurIdleBudget, pw);
2993 pw.println();
2994 }
2995 if (mMaintenanceStartTime != 0) {
2996 pw.print(" mMaintenanceStartTime=");
2997 TimeUtils.formatDuration(mMaintenanceStartTime, SystemClock.elapsedRealtime(), pw);
2998 pw.println();
2999 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003000 if (mJobsActive) {
3001 pw.print(" mJobsActive="); pw.println(mJobsActive);
3002 }
3003 if (mAlarmsActive) {
3004 pw.print(" mAlarmsActive="); pw.println(mAlarmsActive);
3005 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003006 }
3007 }
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003008
3009 void dumpTempWhitelistSchedule(PrintWriter pw, boolean printTitle) {
3010 final int size = mTempWhitelistAppIdEndTimes.size();
3011 if (size > 0) {
3012 String prefix = "";
3013 if (printTitle) {
3014 pw.println(" Temp whitelist schedule:");
3015 prefix = " ";
3016 }
3017 final long timeNow = SystemClock.elapsedRealtime();
3018 for (int i = 0; i < size; i++) {
3019 pw.print(prefix);
3020 pw.print("UID=");
3021 pw.print(mTempWhitelistAppIdEndTimes.keyAt(i));
3022 pw.print(": ");
3023 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.valueAt(i);
3024 TimeUtils.formatDuration(entry.first.value, timeNow, pw);
3025 pw.print(" - ");
3026 pw.println(entry.second);
3027 }
3028 }
3029 }
3030 }