blob: abbc89e45c993419ece9a4732368f33c04127878 [file] [log] [blame]
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Amith Yamasaniaf575b92015-05-29 15:35:26 -070019import android.Manifest;
Sudheer Shankadc589ac2016-11-10 15:30:17 -080020import android.app.ActivityManager;
Dianne Hackborn85e35642017-01-12 15:10:57 -080021import android.app.ActivityManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070022import android.app.AlarmManager;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070023import android.content.BroadcastReceiver;
Adam Lesinski31c05d12015-06-09 17:34:04 -070024import android.content.ContentResolver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070025import android.content.Context;
26import android.content.Intent;
27import android.content.IntentFilter;
28import android.content.pm.ApplicationInfo;
29import android.content.pm.PackageManager;
Amith Yamasaniaf575b92015-05-29 15:35:26 -070030import android.content.pm.PackageManager.NameNotFoundException;
Adam Lesinski31c05d12015-06-09 17:34:04 -070031import android.database.ContentObserver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070032import android.hardware.Sensor;
33import android.hardware.SensorManager;
Nick Vaccaro20feaea2015-09-17 17:22:44 -070034import android.hardware.SensorEvent;
35import android.hardware.SensorEventListener;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070036import android.hardware.TriggerEvent;
37import android.hardware.TriggerEventListener;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -070038import android.location.LocationRequest;
39import android.location.Location;
40import android.location.LocationListener;
41import android.location.LocationManager;
Dianne Hackborn88c41352016-04-07 15:18:58 -070042import android.net.ConnectivityManager;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070043import android.net.INetworkPolicyManager;
Dianne Hackborn88c41352016-04-07 15:18:58 -070044import android.net.NetworkInfo;
Adam Lesinski31c05d12015-06-09 17:34:04 -070045import android.net.Uri;
Dianne Hackbornfd854ee2015-07-13 18:00:37 -070046import android.os.BatteryStats;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070047import android.os.Binder;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -070048import android.os.Bundle;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070049import android.os.Environment;
50import android.os.FileUtils;
51import android.os.Handler;
52import android.os.IDeviceIdleController;
Yao Chenca5edbb2016-01-13 14:44:36 -080053import android.os.IMaintenanceActivityListener;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070054import android.os.Looper;
55import android.os.Message;
56import android.os.PowerManager;
57import android.os.PowerManagerInternal;
Dianne Hackbornb6683c42015-06-18 17:40:33 -070058import android.os.Process;
Yao Chenca5edbb2016-01-13 14:44:36 -080059import android.os.RemoteCallbackList;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070060import android.os.RemoteException;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -070061import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070062import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070063import android.os.ShellCallback;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -070064import android.os.ShellCommand;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070065import android.os.SystemClock;
66import android.os.UserHandle;
Adam Lesinski31c05d12015-06-09 17:34:04 -070067import android.provider.Settings;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070068import android.util.ArrayMap;
69import android.util.ArraySet;
Adam Lesinski31c05d12015-06-09 17:34:04 -070070import android.util.KeyValueListParser;
Dianne Hackbornfd854ee2015-07-13 18:00:37 -070071import android.util.MutableLong;
72import android.util.Pair;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070073import android.util.Slog;
Dianne Hackbornfd854ee2015-07-13 18:00:37 -070074import android.util.SparseArray;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070075import android.util.SparseBooleanArray;
76import android.util.TimeUtils;
77import android.util.Xml;
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;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060082import com.android.internal.util.DumpUtils;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070083import com.android.internal.util.FastXmlSerializer;
84import com.android.internal.util.XmlUtils;
85import com.android.server.am.BatteryStatsService;
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -070086import com.android.server.net.NetworkPolicyManagerInternal;
Amith Yamasani520d8f22015-05-08 16:36:21 -070087
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070088import org.xmlpull.v1.XmlPullParser;
89import org.xmlpull.v1.XmlPullParserException;
90import org.xmlpull.v1.XmlSerializer;
91
92import java.io.ByteArrayOutputStream;
93import java.io.File;
94import java.io.FileDescriptor;
95import java.io.FileInputStream;
96import java.io.FileNotFoundException;
97import java.io.FileOutputStream;
98import java.io.IOException;
99import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100100import java.nio.charset.StandardCharsets;
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700101import java.util.Arrays;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700102
103/**
104 * Keeps track of device idleness and drives low power mode based on that.
105 */
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700106public class DeviceIdleController extends SystemService
107 implements AnyMotionDetector.DeviceIdleCallback {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700108 private static final String TAG = "DeviceIdleController";
109
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700110 private static final boolean DEBUG = false;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700111
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700112 private static final boolean COMPRESS_TIME = false;
Amith Yamasani520d8f22015-05-08 16:36:21 -0700113
Dianne Hackborn953fc942016-03-29 15:36:24 -0700114 private static final int EVENT_BUFFER_SIZE = 100;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800115
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700116 private AlarmManager mAlarmManager;
117 private IBatteryStats mBatteryStats;
Dianne Hackborn85e35642017-01-12 15:10:57 -0800118 private ActivityManagerInternal mLocalActivityManager;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700119 private PowerManagerInternal mLocalPowerManager;
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700120 private PowerManager mPowerManager;
Dianne Hackborn88c41352016-04-07 15:18:58 -0700121 private ConnectivityService mConnectivityService;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -0800122 private AlarmManagerService.LocalService mLocalAlarmManager;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700123 private INetworkPolicyManager mNetworkPolicyManager;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700124 private SensorManager mSensorManager;
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700125 private Sensor mMotionSensor;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700126 private LocationManager mLocationManager;
127 private LocationRequest mLocationRequest;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700128 private Intent mIdleIntent;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700129 private Intent mLightIdleIntent;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700130 private AnyMotionDetector mAnyMotionDetector;
Dianne Hackbornb6843652016-02-22 12:20:13 -0800131 private boolean mLightEnabled;
132 private boolean mDeepEnabled;
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700133 private boolean mForceIdle;
Dianne Hackborn88c41352016-04-07 15:18:58 -0700134 private boolean mNetworkConnected;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700135 private boolean mScreenOn;
136 private boolean mCharging;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700137 private boolean mNotMoving;
138 private boolean mLocating;
139 private boolean mLocated;
Joe LaPenna23d681b2015-08-27 15:12:11 -0700140 private boolean mHasGps;
141 private boolean mHasNetworkLocation;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700142 private Location mLastGenericLocation;
143 private Location mLastGpsLocation;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700144
145 /** Device is currently active. */
146 private static final int STATE_ACTIVE = 0;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700147 /** Device is inactive (screen off, no motion) and we are waiting to for idle. */
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700148 private static final int STATE_INACTIVE = 1;
149 /** Device is past the initial inactive period, and waiting for the next idle period. */
150 private static final int STATE_IDLE_PENDING = 2;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700151 /** Device is currently sensing motion. */
152 private static final int STATE_SENSING = 3;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700153 /** Device is currently finding location (and may still be sensing). */
154 private static final int STATE_LOCATING = 4;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700155 /** Device is in the idle state, trying to stay asleep as much as possible. */
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700156 private static final int STATE_IDLE = 5;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700157 /** Device is in the idle state, but temporarily out of idle to do regular maintenance. */
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700158 private static final int STATE_IDLE_MAINTENANCE = 6;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700159 private static String stateToString(int state) {
160 switch (state) {
161 case STATE_ACTIVE: return "ACTIVE";
162 case STATE_INACTIVE: return "INACTIVE";
163 case STATE_IDLE_PENDING: return "IDLE_PENDING";
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700164 case STATE_SENSING: return "SENSING";
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700165 case STATE_LOCATING: return "LOCATING";
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700166 case STATE_IDLE: return "IDLE";
167 case STATE_IDLE_MAINTENANCE: return "IDLE_MAINTENANCE";
168 default: return Integer.toString(state);
169 }
170 }
171
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700172 /** Device is currently active. */
173 private static final int LIGHT_STATE_ACTIVE = 0;
174 /** Device is inactive (screen off) and we are waiting to for the first light idle. */
175 private static final int LIGHT_STATE_INACTIVE = 1;
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700176 /** Device is about to go idle for the first time, wait for current work to complete. */
177 private static final int LIGHT_STATE_PRE_IDLE = 3;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700178 /** Device is in the light idle state, trying to stay asleep as much as possible. */
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700179 private static final int LIGHT_STATE_IDLE = 4;
Dianne Hackborn88c41352016-04-07 15:18:58 -0700180 /** Device is in the light idle state, we want to go in to idle maintenance but are
181 * waiting for network connectivity before doing so. */
182 private static final int LIGHT_STATE_WAITING_FOR_NETWORK = 5;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700183 /** Device is in the light idle state, but temporarily out of idle to do regular maintenance. */
Dianne Hackborn88c41352016-04-07 15:18:58 -0700184 private static final int LIGHT_STATE_IDLE_MAINTENANCE = 6;
Dianne Hackbornb6843652016-02-22 12:20:13 -0800185 /** Device light idle state is overriden, now applying deep doze state. */
Dianne Hackborn88c41352016-04-07 15:18:58 -0700186 private static final int LIGHT_STATE_OVERRIDE = 7;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700187 private static String lightStateToString(int state) {
188 switch (state) {
189 case LIGHT_STATE_ACTIVE: return "ACTIVE";
190 case LIGHT_STATE_INACTIVE: return "INACTIVE";
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700191 case LIGHT_STATE_PRE_IDLE: return "PRE_IDLE";
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700192 case LIGHT_STATE_IDLE: return "IDLE";
Dianne Hackborn88c41352016-04-07 15:18:58 -0700193 case LIGHT_STATE_WAITING_FOR_NETWORK: return "WAITING_FOR_NETWORK";
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700194 case LIGHT_STATE_IDLE_MAINTENANCE: return "IDLE_MAINTENANCE";
195 case LIGHT_STATE_OVERRIDE: return "OVERRIDE";
196 default: return Integer.toString(state);
197 }
198 }
199
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700200 private int mState;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700201 private int mLightState;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700202
203 private long mInactiveTimeout;
204 private long mNextAlarmTime;
205 private long mNextIdlePendingDelay;
206 private long mNextIdleDelay;
Dianne Hackborn953fc942016-03-29 15:36:24 -0700207 private long mNextLightIdleDelay;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700208 private long mNextLightAlarmTime;
Kevin Gabayan92f15e62016-04-04 17:52:22 -0700209 private long mNextSensingTimeoutAlarmTime;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800210 private long mCurIdleBudget;
211 private long mMaintenanceStartTime;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700212
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800213 private int mActiveIdleOpCount;
Joe Onorato8f0e9ced2016-12-08 17:48:49 -0800214 private PowerManager.WakeLock mActiveIdleWakeLock; // held when there are operations in progress
215 private PowerManager.WakeLock mGoingIdleWakeLock; // held when we are going idle so hardware
216 // (especially NetworkPolicyManager) can shut
217 // down.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800218 private boolean mJobsActive;
219 private boolean mAlarmsActive;
Yao Chenca5edbb2016-01-13 14:44:36 -0800220 private boolean mReportedMaintenanceActivity;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800221
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700222 public final AtomicFile mConfigFile;
223
Yao Chenca5edbb2016-01-13 14:44:36 -0800224 private final RemoteCallbackList<IMaintenanceActivityListener> mMaintenanceActivityListeners =
225 new RemoteCallbackList<IMaintenanceActivityListener>();
226
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700227 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700228 * Package names the system has white-listed to opt out of power save restrictions,
229 * except for device idle mode.
230 */
231 private final ArrayMap<String, Integer> mPowerSaveWhitelistAppsExceptIdle = new ArrayMap<>();
232
233 /**
Sudheer Shanka3f4d7702017-04-28 17:38:03 -0700234 * Package names the user has white-listed using commandline option to opt out of
235 * power save restrictions, except for device idle mode.
236 */
237 private final ArraySet<String> mPowerSaveWhitelistUserAppsExceptIdle = new ArraySet<>();
238
239 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700240 * Package names the system has white-listed to opt out of power save restrictions for
241 * all modes.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700242 */
243 private final ArrayMap<String, Integer> mPowerSaveWhitelistApps = new ArrayMap<>();
244
245 /**
246 * Package names the user has white-listed to opt out of power save restrictions.
247 */
248 private final ArrayMap<String, Integer> mPowerSaveWhitelistUserApps = new ArrayMap<>();
249
250 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700251 * App IDs of built-in system apps that have been white-listed except for idle modes.
252 */
253 private final SparseBooleanArray mPowerSaveWhitelistSystemAppIdsExceptIdle
254 = new SparseBooleanArray();
255
256 /**
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700257 * App IDs of built-in system apps that have been white-listed.
258 */
259 private final SparseBooleanArray mPowerSaveWhitelistSystemAppIds = new SparseBooleanArray();
260
261 /**
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700262 * App IDs that have been white-listed to opt out of power save restrictions, except
263 * for device idle modes.
264 */
265 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
266
267 /**
268 * Current app IDs that are in the complete power save white list, but shouldn't be
269 * excluded from idle modes. This array can be shared with others because it will not be
270 * modified once set.
271 */
272 private int[] mPowerSaveWhitelistExceptIdleAppIdArray = new int[0];
273
274 /**
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700275 * App IDs that have been white-listed to opt out of power save restrictions.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700276 */
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700277 private final SparseBooleanArray mPowerSaveWhitelistAllAppIds = new SparseBooleanArray();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700278
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700279 /**
280 * Current app IDs that are in the complete power save white list. This array can
281 * be shared with others because it will not be modified once set.
282 */
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700283 private int[] mPowerSaveWhitelistAllAppIdArray = new int[0];
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700284
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700285 /**
Dianne Hackborn262ae5c2016-02-10 16:28:29 -0800286 * App IDs that have been white-listed by the user to opt out of power save restrictions.
287 */
288 private final SparseBooleanArray mPowerSaveWhitelistUserAppIds = new SparseBooleanArray();
289
290 /**
291 * Current app IDs that are in the user power save white list. This array can
292 * be shared with others because it will not be modified once set.
293 */
294 private int[] mPowerSaveWhitelistUserAppIdArray = new int[0];
295
296 /**
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700297 * List of end times for UIDs that are temporarily marked as being allowed to access
298 * the network and acquire wakelocks. Times are in milliseconds.
299 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700300 private final SparseArray<Pair<MutableLong, String>> mTempWhitelistAppIdEndTimes
301 = new SparseArray<>();
302
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -0700303 private NetworkPolicyManagerInternal mNetworkPolicyManagerInternal;
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700304
305 /**
306 * Current app IDs of temporarily whitelist apps for high-priority messages.
307 */
308 private int[] mTempWhitelistAppIdArray = new int[0];
309
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800310 private static final int EVENT_NULL = 0;
311 private static final int EVENT_NORMAL = 1;
312 private static final int EVENT_LIGHT_IDLE = 2;
313 private static final int EVENT_LIGHT_MAINTENANCE = 3;
Dianne Hackbornb6843652016-02-22 12:20:13 -0800314 private static final int EVENT_DEEP_IDLE = 4;
315 private static final int EVENT_DEEP_MAINTENANCE = 5;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800316
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -0700317 private final int[] mEventCmds = new int[EVENT_BUFFER_SIZE];
318 private final long[] mEventTimes = new long[EVENT_BUFFER_SIZE];
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800319
320 private void addEvent(int cmd) {
321 if (mEventCmds[0] != cmd) {
322 System.arraycopy(mEventCmds, 0, mEventCmds, 1, EVENT_BUFFER_SIZE - 1);
323 System.arraycopy(mEventTimes, 0, mEventTimes, 1, EVENT_BUFFER_SIZE - 1);
324 mEventCmds[0] = cmd;
325 mEventTimes[0] = SystemClock.elapsedRealtime();
326 }
327 }
328
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700329 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
330 @Override public void onReceive(Context context, Intent intent) {
Dianne Hackborn88c41352016-04-07 15:18:58 -0700331 switch (intent.getAction()) {
332 case ConnectivityManager.CONNECTIVITY_ACTION: {
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -0700333 updateConnectivityState(intent);
Dianne Hackborn88c41352016-04-07 15:18:58 -0700334 } break;
335 case Intent.ACTION_BATTERY_CHANGED: {
336 synchronized (DeviceIdleController.this) {
337 int plugged = intent.getIntExtra("plugged", 0);
338 updateChargingLocked(plugged != 0);
339 }
340 } break;
341 case Intent.ACTION_PACKAGE_REMOVED: {
342 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
343 Uri data = intent.getData();
344 String ssp;
345 if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
346 removePowerSaveWhitelistAppInternal(ssp);
347 }
348 }
349 } break;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700350 }
351 }
352 };
353
354 private final AlarmManager.OnAlarmListener mLightAlarmListener
355 = new AlarmManager.OnAlarmListener() {
356 @Override
357 public void onAlarm() {
358 synchronized (DeviceIdleController.this) {
359 stepLightIdleStateLocked("s:alarm");
360 }
361 }
362 };
363
Kevin Gabayan92f15e62016-04-04 17:52:22 -0700364 private final AlarmManager.OnAlarmListener mSensingTimeoutAlarmListener
365 = new AlarmManager.OnAlarmListener() {
366 @Override
367 public void onAlarm() {
368 if (mState == STATE_SENSING) {
369 synchronized (DeviceIdleController.this) {
370 becomeInactiveIfAppropriateLocked();
371 }
372 }
373 }
374 };
375
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700376 private final AlarmManager.OnAlarmListener mDeepAlarmListener
377 = new AlarmManager.OnAlarmListener() {
378 @Override
379 public void onAlarm() {
380 synchronized (DeviceIdleController.this) {
381 stepIdleStateLocked("s:alarm");
382 }
383 }
384 };
385
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800386 private final BroadcastReceiver mIdleStartedDoneReceiver = new BroadcastReceiver() {
387 @Override public void onReceive(Context context, Intent intent) {
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700388 // When coming out of a deep idle, we will add in some delay before we allow
389 // the system to settle down and finish the maintenance window. This is
390 // to give a chance for any pending work to be scheduled.
391 if (PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED.equals(intent.getAction())) {
392 mHandler.sendEmptyMessageDelayed(MSG_FINISH_IDLE_OP,
393 mConstants.MIN_DEEP_MAINTENANCE_TIME);
394 } else {
395 mHandler.sendEmptyMessageDelayed(MSG_FINISH_IDLE_OP,
396 mConstants.MIN_LIGHT_MAINTENANCE_TIME);
397 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800398 }
399 };
400
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -0700401 private final BroadcastReceiver mInteractivityReceiver = new BroadcastReceiver() {
402 @Override
403 public void onReceive(Context context, Intent intent) {
Dianne Hackborn9b5ebc92017-09-08 13:45:35 -0700404 synchronized (DeviceIdleController.this) {
405 updateInteractivityLocked();
406 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700407 }
408 };
409
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700410 private final class MotionListener extends TriggerEventListener
411 implements SensorEventListener {
412
413 boolean active = false;
414
415 @Override
416 public void onTrigger(TriggerEvent event) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700417 synchronized (DeviceIdleController.this) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700418 active = false;
419 motionLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700420 }
421 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700422
423 @Override
424 public void onSensorChanged(SensorEvent event) {
425 synchronized (DeviceIdleController.this) {
426 mSensorManager.unregisterListener(this, mMotionSensor);
427 active = false;
428 motionLocked();
429 }
430 }
431
432 @Override
433 public void onAccuracyChanged(Sensor sensor, int accuracy) {}
434
435 public boolean registerLocked() {
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700436 boolean success;
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700437 if (mMotionSensor.getReportingMode() == Sensor.REPORTING_MODE_ONE_SHOT) {
438 success = mSensorManager.requestTriggerSensor(mMotionListener, mMotionSensor);
439 } else {
440 success = mSensorManager.registerListener(
441 mMotionListener, mMotionSensor, SensorManager.SENSOR_DELAY_NORMAL);
442 }
443 if (success) {
444 active = true;
445 } else {
446 Slog.e(TAG, "Unable to register for " + mMotionSensor);
447 }
448 return success;
449 }
450
451 public void unregisterLocked() {
452 if (mMotionSensor.getReportingMode() == Sensor.REPORTING_MODE_ONE_SHOT) {
453 mSensorManager.cancelTriggerSensor(mMotionListener, mMotionSensor);
454 } else {
455 mSensorManager.unregisterListener(mMotionListener);
456 }
457 active = false;
458 }
459 }
460 private final MotionListener mMotionListener = new MotionListener();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700461
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700462 private final LocationListener mGenericLocationListener = new LocationListener() {
463 @Override
464 public void onLocationChanged(Location location) {
465 synchronized (DeviceIdleController.this) {
466 receivedGenericLocationLocked(location);
467 }
468 }
469
470 @Override
471 public void onStatusChanged(String provider, int status, Bundle extras) {
472 }
473
474 @Override
475 public void onProviderEnabled(String provider) {
476 }
477
478 @Override
479 public void onProviderDisabled(String provider) {
480 }
481 };
482
483 private final LocationListener mGpsLocationListener = new LocationListener() {
484 @Override
485 public void onLocationChanged(Location location) {
486 synchronized (DeviceIdleController.this) {
487 receivedGpsLocationLocked(location);
488 }
489 }
490
491 @Override
492 public void onStatusChanged(String provider, int status, Bundle extras) {
493 }
494
495 @Override
496 public void onProviderEnabled(String provider) {
497 }
498
499 @Override
500 public void onProviderDisabled(String provider) {
501 }
502 };
503
Adam Lesinski31c05d12015-06-09 17:34:04 -0700504 /**
505 * All times are in milliseconds. These constants are kept synchronized with the system
506 * global Settings. Any access to this class or its fields should be done while
507 * holding the DeviceIdleController lock.
508 */
Dianne Hackborna750a632015-06-16 17:18:23 -0700509 private final class Constants extends ContentObserver {
Adam Lesinski31c05d12015-06-09 17:34:04 -0700510 // Key names stored in the settings value.
Dianne Hackborn953fc942016-03-29 15:36:24 -0700511 private static final String KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT
512 = "light_after_inactive_to";
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700513 private static final String KEY_LIGHT_PRE_IDLE_TIMEOUT = "light_pre_idle_to";
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700514 private static final String KEY_LIGHT_IDLE_TIMEOUT = "light_idle_to";
Dianne Hackborn953fc942016-03-29 15:36:24 -0700515 private static final String KEY_LIGHT_IDLE_FACTOR = "light_idle_factor";
516 private static final String KEY_LIGHT_MAX_IDLE_TIMEOUT = "light_max_idle_to";
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800517 private static final String KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET
518 = "light_idle_maintenance_min_budget";
519 private static final String KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET
520 = "light_idle_maintenance_max_budget";
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700521 private static final String KEY_MIN_LIGHT_MAINTENANCE_TIME = "min_light_maintenance_time";
522 private static final String KEY_MIN_DEEP_MAINTENANCE_TIME = "min_deep_maintenance_time";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700523 private static final String KEY_INACTIVE_TIMEOUT = "inactive_to";
524 private static final String KEY_SENSING_TIMEOUT = "sensing_to";
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700525 private static final String KEY_LOCATING_TIMEOUT = "locating_to";
526 private static final String KEY_LOCATION_ACCURACY = "location_accuracy";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700527 private static final String KEY_MOTION_INACTIVE_TIMEOUT = "motion_inactive_to";
528 private static final String KEY_IDLE_AFTER_INACTIVE_TIMEOUT = "idle_after_inactive_to";
529 private static final String KEY_IDLE_PENDING_TIMEOUT = "idle_pending_to";
530 private static final String KEY_MAX_IDLE_PENDING_TIMEOUT = "max_idle_pending_to";
531 private static final String KEY_IDLE_PENDING_FACTOR = "idle_pending_factor";
532 private static final String KEY_IDLE_TIMEOUT = "idle_to";
533 private static final String KEY_MAX_IDLE_TIMEOUT = "max_idle_to";
534 private static final String KEY_IDLE_FACTOR = "idle_factor";
535 private static final String KEY_MIN_TIME_TO_ALARM = "min_time_to_alarm";
536 private static final String KEY_MAX_TEMP_APP_WHITELIST_DURATION =
537 "max_temp_app_whitelist_duration";
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700538 private static final String KEY_MMS_TEMP_APP_WHITELIST_DURATION =
539 "mms_temp_app_whitelist_duration";
Dianne Hackborn451c3462015-07-21 17:39:46 -0700540 private static final String KEY_SMS_TEMP_APP_WHITELIST_DURATION =
541 "sms_temp_app_whitelist_duration";
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700542 private static final String KEY_NOTIFICATION_WHITELIST_DURATION =
543 "notification_whitelist_duration";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700544
545 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700546 * This is the time, after becoming inactive, that we go in to the first
547 * light-weight idle mode.
548 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
549 * @see #KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT
550 */
551 public long LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT;
552
553 /**
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700554 * This is amount of time we will wait from the point where we decide we would
555 * like to go idle until we actually do, while waiting for jobs and other current
556 * activity to finish.
557 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
558 * @see #KEY_LIGHT_PRE_IDLE_TIMEOUT
559 */
560 public long LIGHT_PRE_IDLE_TIMEOUT;
561
562 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700563 * This is the initial time that we will run in idle maintenance mode.
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700564 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
565 * @see #KEY_LIGHT_IDLE_TIMEOUT
566 */
567 public long LIGHT_IDLE_TIMEOUT;
568
569 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700570 * Scaling factor to apply to the light idle mode time each time we complete a cycle.
571 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
572 * @see #KEY_LIGHT_IDLE_FACTOR
573 */
574 public float LIGHT_IDLE_FACTOR;
575
576 /**
577 * This is the maximum time we will run in idle maintenence mode.
578 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
579 * @see #KEY_LIGHT_MAX_IDLE_TIMEOUT
580 */
581 public long LIGHT_MAX_IDLE_TIMEOUT;
582
583 /**
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800584 * This is the minimum amount of time we want to make available for maintenance mode
585 * when lightly idling. That is, we will always have at least this amount of time
586 * available maintenance before timing out and cutting off maintenance mode.
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700587 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800588 * @see #KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700589 */
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800590 public long LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
591
592 /**
593 * This is the maximum amount of time we want to make available for maintenance mode
594 * when lightly idling. That is, if the system isn't using up its minimum maintenance
595 * budget and this time is being added to the budget reserve, this is the maximum
596 * reserve size we will allow to grow and thus the maximum amount of time we will
597 * allow for the maintenance window.
598 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
599 * @see #KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET
600 */
601 public long LIGHT_IDLE_MAINTENANCE_MAX_BUDGET;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700602
603 /**
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700604 * This is the minimum amount of time that we will stay in maintenance mode after
605 * a light doze. We have this minimum to allow various things to respond to switching
606 * in to maintenance mode and scheduling their work -- otherwise we may
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700607 * see there is nothing to do (no jobs pending) and go out of maintenance
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700608 * mode immediately.
609 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
610 * @see #KEY_MIN_LIGHT_MAINTENANCE_TIME
611 */
612 public long MIN_LIGHT_MAINTENANCE_TIME;
613
614 /**
615 * This is the minimum amount of time that we will stay in maintenance mode after
616 * a full doze. We have this minimum to allow various things to respond to switching
617 * in to maintenance mode and scheduling their work -- otherwise we may
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700618 * see there is nothing to do (no jobs pending) and go out of maintenance
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700619 * mode immediately.
620 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
621 * @see #KEY_MIN_DEEP_MAINTENANCE_TIME
622 */
623 public long MIN_DEEP_MAINTENANCE_TIME;
624
625 /**
Adam Lesinski31c05d12015-06-09 17:34:04 -0700626 * This is the time, after becoming inactive, at which we start looking at the
627 * motion sensor to determine if the device is being left alone. We don't do this
628 * immediately after going inactive just because we don't want to be continually running
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700629 * the motion sensor whenever the screen is off.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700630 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
631 * @see #KEY_INACTIVE_TIMEOUT
632 */
633 public long INACTIVE_TIMEOUT;
634
635 /**
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700636 * If we don't receive a callback from AnyMotion in this amount of time +
637 * {@link #LOCATING_TIMEOUT}, we will change from
Adam Lesinski31c05d12015-06-09 17:34:04 -0700638 * STATE_SENSING to STATE_INACTIVE, and any AnyMotion callbacks while not in STATE_SENSING
639 * will be ignored.
640 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
641 * @see #KEY_SENSING_TIMEOUT
642 */
643 public long SENSING_TIMEOUT;
644
645 /**
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700646 * This is how long we will wait to try to get a good location fix before going in to
647 * idle mode.
648 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
649 * @see #KEY_LOCATING_TIMEOUT
650 */
651 public long LOCATING_TIMEOUT;
652
653 /**
654 * The desired maximum accuracy (in meters) we consider the location to be good enough to go
655 * on to idle. We will be trying to get an accuracy fix at least this good or until
656 * {@link #LOCATING_TIMEOUT} expires.
657 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
658 * @see #KEY_LOCATION_ACCURACY
659 */
660 public float LOCATION_ACCURACY;
661
662 /**
Adam Lesinski31c05d12015-06-09 17:34:04 -0700663 * This is the time, after seeing motion, that we wait after becoming inactive from
664 * that until we start looking for motion again.
665 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
666 * @see #KEY_MOTION_INACTIVE_TIMEOUT
667 */
668 public long MOTION_INACTIVE_TIMEOUT;
669
670 /**
671 * This is the time, after the inactive timeout elapses, that we will wait looking
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700672 * for motion until we truly consider the device to be idle.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700673 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
674 * @see #KEY_IDLE_AFTER_INACTIVE_TIMEOUT
675 */
676 public long IDLE_AFTER_INACTIVE_TIMEOUT;
677
678 /**
679 * This is the initial time, after being idle, that we will allow ourself to be back
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700680 * in the IDLE_MAINTENANCE state allowing the system to run normally until we return to
681 * idle.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700682 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
683 * @see #KEY_IDLE_PENDING_TIMEOUT
684 */
685 public long IDLE_PENDING_TIMEOUT;
686
687 /**
688 * Maximum pending idle timeout (time spent running) we will be allowed to use.
689 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
690 * @see #KEY_MAX_IDLE_PENDING_TIMEOUT
691 */
692 public long MAX_IDLE_PENDING_TIMEOUT;
693
694 /**
695 * Scaling factor to apply to current pending idle timeout each time we cycle through
696 * that state.
697 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
698 * @see #KEY_IDLE_PENDING_FACTOR
699 */
700 public float IDLE_PENDING_FACTOR;
701
702 /**
703 * This is the initial time that we want to sit in the idle state before waking up
704 * again to return to pending idle and allowing normal work to run.
705 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
706 * @see #KEY_IDLE_TIMEOUT
707 */
708 public long IDLE_TIMEOUT;
709
710 /**
711 * Maximum idle duration we will be allowed to use.
712 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
713 * @see #KEY_MAX_IDLE_TIMEOUT
714 */
715 public long MAX_IDLE_TIMEOUT;
716
717 /**
718 * Scaling factor to apply to current idle timeout each time we cycle through that state.
719 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
720 * @see #KEY_IDLE_FACTOR
721 */
722 public float IDLE_FACTOR;
723
724 /**
725 * This is the minimum time we will allow until the next upcoming alarm for us to
726 * actually go in to idle mode.
727 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
728 * @see #KEY_MIN_TIME_TO_ALARM
729 */
730 public long MIN_TIME_TO_ALARM;
731
732 /**
733 * Max amount of time to temporarily whitelist an app when it receives a high priority
734 * tickle.
735 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
736 * @see #KEY_MAX_TEMP_APP_WHITELIST_DURATION
737 */
738 public long MAX_TEMP_APP_WHITELIST_DURATION;
739
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700740 /**
741 * Amount of time we would like to whitelist an app that is receiving an MMS.
742 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
743 * @see #KEY_MMS_TEMP_APP_WHITELIST_DURATION
744 */
745 public long MMS_TEMP_APP_WHITELIST_DURATION;
746
Dianne Hackborn451c3462015-07-21 17:39:46 -0700747 /**
748 * Amount of time we would like to whitelist an app that is receiving an SMS.
749 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
750 * @see #KEY_SMS_TEMP_APP_WHITELIST_DURATION
751 */
752 public long SMS_TEMP_APP_WHITELIST_DURATION;
753
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700754 /**
755 * Amount of time we would like to whitelist an app that is handling a
756 * {@link android.app.PendingIntent} triggered by a {@link android.app.Notification}.
757 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
758 * @see #KEY_NOTIFICATION_WHITELIST_DURATION
759 */
760 public long NOTIFICATION_WHITELIST_DURATION;
761
Adam Lesinski31c05d12015-06-09 17:34:04 -0700762 private final ContentResolver mResolver;
Joe LaPennaf33b5bf2016-03-23 15:19:47 -0700763 private final boolean mHasWatch;
Adam Lesinski31c05d12015-06-09 17:34:04 -0700764 private final KeyValueListParser mParser = new KeyValueListParser(',');
765
766 public Constants(Handler handler, ContentResolver resolver) {
767 super(handler);
768 mResolver = resolver;
Joe LaPennaf33b5bf2016-03-23 15:19:47 -0700769 mHasWatch = getContext().getPackageManager().hasSystemFeature(
770 PackageManager.FEATURE_WATCH);
771 mResolver.registerContentObserver(Settings.Global.getUriFor(
772 mHasWatch ? Settings.Global.DEVICE_IDLE_CONSTANTS_WATCH
773 : Settings.Global.DEVICE_IDLE_CONSTANTS),
774 false, this);
Adam Lesinski31c05d12015-06-09 17:34:04 -0700775 updateConstants();
776 }
777
778 @Override
779 public void onChange(boolean selfChange, Uri uri) {
780 updateConstants();
781 }
782
783 private void updateConstants() {
784 synchronized (DeviceIdleController.this) {
785 try {
786 mParser.setString(Settings.Global.getString(mResolver,
Joe LaPennaf33b5bf2016-03-23 15:19:47 -0700787 mHasWatch ? Settings.Global.DEVICE_IDLE_CONSTANTS_WATCH
788 : Settings.Global.DEVICE_IDLE_CONSTANTS));
Adam Lesinski31c05d12015-06-09 17:34:04 -0700789 } catch (IllegalArgumentException e) {
790 // Failed to parse the settings string, log this and move on
791 // with defaults.
792 Slog.e(TAG, "Bad device idle settings", e);
793 }
794
Dianne Hackborn953fc942016-03-29 15:36:24 -0700795 LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT = mParser.getLong(
796 KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT,
797 !COMPRESS_TIME ? 5 * 60 * 1000L : 15 * 1000L);
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700798 LIGHT_PRE_IDLE_TIMEOUT = mParser.getLong(KEY_LIGHT_PRE_IDLE_TIMEOUT,
799 !COMPRESS_TIME ? 10 * 60 * 1000L : 30 * 1000L);
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700800 LIGHT_IDLE_TIMEOUT = mParser.getLong(KEY_LIGHT_IDLE_TIMEOUT,
Dianne Hackborn953fc942016-03-29 15:36:24 -0700801 !COMPRESS_TIME ? 5 * 60 * 1000L : 15 * 1000L);
802 LIGHT_IDLE_FACTOR = mParser.getFloat(KEY_LIGHT_IDLE_FACTOR,
803 2f);
804 LIGHT_MAX_IDLE_TIMEOUT = mParser.getLong(KEY_LIGHT_MAX_IDLE_TIMEOUT,
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700805 !COMPRESS_TIME ? 15 * 60 * 1000L : 60 * 1000L);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800806 LIGHT_IDLE_MAINTENANCE_MIN_BUDGET = mParser.getLong(
807 KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET,
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700808 !COMPRESS_TIME ? 1 * 60 * 1000L : 15 * 1000L);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800809 LIGHT_IDLE_MAINTENANCE_MAX_BUDGET = mParser.getLong(
810 KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET,
811 !COMPRESS_TIME ? 5 * 60 * 1000L : 30 * 1000L);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700812 MIN_LIGHT_MAINTENANCE_TIME = mParser.getLong(
813 KEY_MIN_LIGHT_MAINTENANCE_TIME,
814 !COMPRESS_TIME ? 5 * 1000L : 1 * 1000L);
815 MIN_DEEP_MAINTENANCE_TIME = mParser.getLong(
816 KEY_MIN_DEEP_MAINTENANCE_TIME,
817 !COMPRESS_TIME ? 30 * 1000L : 5 * 1000L);
Joe LaPenna0c5d3e92016-03-24 13:29:56 -0700818 long inactiveTimeoutDefault = (mHasWatch ? 15 : 30) * 60 * 1000L;
Adam Lesinski31c05d12015-06-09 17:34:04 -0700819 INACTIVE_TIMEOUT = mParser.getLong(KEY_INACTIVE_TIMEOUT,
Joe LaPenna0c5d3e92016-03-24 13:29:56 -0700820 !COMPRESS_TIME ? inactiveTimeoutDefault : (inactiveTimeoutDefault / 10));
Adam Lesinski31c05d12015-06-09 17:34:04 -0700821 SENSING_TIMEOUT = mParser.getLong(KEY_SENSING_TIMEOUT,
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700822 !DEBUG ? 4 * 60 * 1000L : 60 * 1000L);
823 LOCATING_TIMEOUT = mParser.getLong(KEY_LOCATING_TIMEOUT,
824 !DEBUG ? 30 * 1000L : 15 * 1000L);
825 LOCATION_ACCURACY = mParser.getFloat(KEY_LOCATION_ACCURACY, 20);
Adam Lesinski31c05d12015-06-09 17:34:04 -0700826 MOTION_INACTIVE_TIMEOUT = mParser.getLong(KEY_MOTION_INACTIVE_TIMEOUT,
827 !COMPRESS_TIME ? 10 * 60 * 1000L : 60 * 1000L);
Joe LaPenna0c5d3e92016-03-24 13:29:56 -0700828 long idleAfterInactiveTimeout = (mHasWatch ? 15 : 30) * 60 * 1000L;
Adam Lesinski31c05d12015-06-09 17:34:04 -0700829 IDLE_AFTER_INACTIVE_TIMEOUT = mParser.getLong(KEY_IDLE_AFTER_INACTIVE_TIMEOUT,
Joe LaPenna0c5d3e92016-03-24 13:29:56 -0700830 !COMPRESS_TIME ? idleAfterInactiveTimeout
831 : (idleAfterInactiveTimeout / 10));
Adam Lesinski31c05d12015-06-09 17:34:04 -0700832 IDLE_PENDING_TIMEOUT = mParser.getLong(KEY_IDLE_PENDING_TIMEOUT,
833 !COMPRESS_TIME ? 5 * 60 * 1000L : 30 * 1000L);
834 MAX_IDLE_PENDING_TIMEOUT = mParser.getLong(KEY_MAX_IDLE_PENDING_TIMEOUT,
835 !COMPRESS_TIME ? 10 * 60 * 1000L : 60 * 1000L);
836 IDLE_PENDING_FACTOR = mParser.getFloat(KEY_IDLE_PENDING_FACTOR,
837 2f);
838 IDLE_TIMEOUT = mParser.getLong(KEY_IDLE_TIMEOUT,
839 !COMPRESS_TIME ? 60 * 60 * 1000L : 6 * 60 * 1000L);
840 MAX_IDLE_TIMEOUT = mParser.getLong(KEY_MAX_IDLE_TIMEOUT,
841 !COMPRESS_TIME ? 6 * 60 * 60 * 1000L : 30 * 60 * 1000L);
842 IDLE_FACTOR = mParser.getFloat(KEY_IDLE_FACTOR,
843 2f);
844 MIN_TIME_TO_ALARM = mParser.getLong(KEY_MIN_TIME_TO_ALARM,
845 !COMPRESS_TIME ? 60 * 60 * 1000L : 6 * 60 * 1000L);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700846 MAX_TEMP_APP_WHITELIST_DURATION = mParser.getLong(
847 KEY_MAX_TEMP_APP_WHITELIST_DURATION, 5 * 60 * 1000L);
848 MMS_TEMP_APP_WHITELIST_DURATION = mParser.getLong(
Dianne Hackborn0b6134b2015-07-14 18:48:07 -0700849 KEY_MMS_TEMP_APP_WHITELIST_DURATION, 60 * 1000L);
Dianne Hackborn451c3462015-07-21 17:39:46 -0700850 SMS_TEMP_APP_WHITELIST_DURATION = mParser.getLong(
851 KEY_SMS_TEMP_APP_WHITELIST_DURATION, 20 * 1000L);
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700852 NOTIFICATION_WHITELIST_DURATION = mParser.getLong(
853 KEY_NOTIFICATION_WHITELIST_DURATION, 30 * 1000L);
Adam Lesinski31c05d12015-06-09 17:34:04 -0700854 }
855 }
856
857 void dump(PrintWriter pw) {
858 pw.println(" Settings:");
859
Dianne Hackborn953fc942016-03-29 15:36:24 -0700860 pw.print(" "); pw.print(KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT); pw.print("=");
861 TimeUtils.formatDuration(LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT, pw);
862 pw.println();
863
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700864 pw.print(" "); pw.print(KEY_LIGHT_PRE_IDLE_TIMEOUT); pw.print("=");
865 TimeUtils.formatDuration(LIGHT_PRE_IDLE_TIMEOUT, pw);
866 pw.println();
867
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700868 pw.print(" "); pw.print(KEY_LIGHT_IDLE_TIMEOUT); pw.print("=");
869 TimeUtils.formatDuration(LIGHT_IDLE_TIMEOUT, pw);
870 pw.println();
871
Dianne Hackborn953fc942016-03-29 15:36:24 -0700872 pw.print(" "); pw.print(KEY_LIGHT_IDLE_FACTOR); pw.print("=");
873 pw.print(LIGHT_IDLE_FACTOR);
874 pw.println();
875
876 pw.print(" "); pw.print(KEY_LIGHT_MAX_IDLE_TIMEOUT); pw.print("=");
877 TimeUtils.formatDuration(LIGHT_MAX_IDLE_TIMEOUT, pw);
878 pw.println();
879
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800880 pw.print(" "); pw.print(KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET); pw.print("=");
881 TimeUtils.formatDuration(LIGHT_IDLE_MAINTENANCE_MIN_BUDGET, pw);
882 pw.println();
883
884 pw.print(" "); pw.print(KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET); pw.print("=");
885 TimeUtils.formatDuration(LIGHT_IDLE_MAINTENANCE_MAX_BUDGET, pw);
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700886 pw.println();
887
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700888 pw.print(" "); pw.print(KEY_MIN_LIGHT_MAINTENANCE_TIME); pw.print("=");
889 TimeUtils.formatDuration(MIN_LIGHT_MAINTENANCE_TIME, pw);
890 pw.println();
891
892 pw.print(" "); pw.print(KEY_MIN_DEEP_MAINTENANCE_TIME); pw.print("=");
893 TimeUtils.formatDuration(MIN_DEEP_MAINTENANCE_TIME, pw);
894 pw.println();
895
Dianne Hackborna750a632015-06-16 17:18:23 -0700896 pw.print(" "); pw.print(KEY_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700897 TimeUtils.formatDuration(INACTIVE_TIMEOUT, pw);
898 pw.println();
899
Dianne Hackborna750a632015-06-16 17:18:23 -0700900 pw.print(" "); pw.print(KEY_SENSING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700901 TimeUtils.formatDuration(SENSING_TIMEOUT, pw);
902 pw.println();
903
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700904 pw.print(" "); pw.print(KEY_LOCATING_TIMEOUT); pw.print("=");
905 TimeUtils.formatDuration(LOCATING_TIMEOUT, pw);
906 pw.println();
907
908 pw.print(" "); pw.print(KEY_LOCATION_ACCURACY); pw.print("=");
909 pw.print(LOCATION_ACCURACY); pw.print("m");
910 pw.println();
911
Dianne Hackborna750a632015-06-16 17:18:23 -0700912 pw.print(" "); pw.print(KEY_MOTION_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700913 TimeUtils.formatDuration(MOTION_INACTIVE_TIMEOUT, pw);
914 pw.println();
915
Dianne Hackborna750a632015-06-16 17:18:23 -0700916 pw.print(" "); pw.print(KEY_IDLE_AFTER_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700917 TimeUtils.formatDuration(IDLE_AFTER_INACTIVE_TIMEOUT, pw);
918 pw.println();
919
Dianne Hackborna750a632015-06-16 17:18:23 -0700920 pw.print(" "); pw.print(KEY_IDLE_PENDING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700921 TimeUtils.formatDuration(IDLE_PENDING_TIMEOUT, pw);
922 pw.println();
923
Dianne Hackborna750a632015-06-16 17:18:23 -0700924 pw.print(" "); pw.print(KEY_MAX_IDLE_PENDING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700925 TimeUtils.formatDuration(MAX_IDLE_PENDING_TIMEOUT, pw);
926 pw.println();
927
Dianne Hackborna750a632015-06-16 17:18:23 -0700928 pw.print(" "); pw.print(KEY_IDLE_PENDING_FACTOR); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700929 pw.println(IDLE_PENDING_FACTOR);
930
Dianne Hackborna750a632015-06-16 17:18:23 -0700931 pw.print(" "); pw.print(KEY_IDLE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700932 TimeUtils.formatDuration(IDLE_TIMEOUT, pw);
933 pw.println();
934
Dianne Hackborna750a632015-06-16 17:18:23 -0700935 pw.print(" "); pw.print(KEY_MAX_IDLE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700936 TimeUtils.formatDuration(MAX_IDLE_TIMEOUT, pw);
937 pw.println();
938
Dianne Hackborna750a632015-06-16 17:18:23 -0700939 pw.print(" "); pw.print(KEY_IDLE_FACTOR); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700940 pw.println(IDLE_FACTOR);
941
Dianne Hackborna750a632015-06-16 17:18:23 -0700942 pw.print(" "); pw.print(KEY_MIN_TIME_TO_ALARM); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700943 TimeUtils.formatDuration(MIN_TIME_TO_ALARM, pw);
944 pw.println();
945
Dianne Hackborna750a632015-06-16 17:18:23 -0700946 pw.print(" "); pw.print(KEY_MAX_TEMP_APP_WHITELIST_DURATION); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700947 TimeUtils.formatDuration(MAX_TEMP_APP_WHITELIST_DURATION, pw);
948 pw.println();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700949
950 pw.print(" "); pw.print(KEY_MMS_TEMP_APP_WHITELIST_DURATION); pw.print("=");
951 TimeUtils.formatDuration(MMS_TEMP_APP_WHITELIST_DURATION, pw);
952 pw.println();
Dianne Hackborn451c3462015-07-21 17:39:46 -0700953
954 pw.print(" "); pw.print(KEY_SMS_TEMP_APP_WHITELIST_DURATION); pw.print("=");
955 TimeUtils.formatDuration(SMS_TEMP_APP_WHITELIST_DURATION, pw);
956 pw.println();
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700957
958 pw.print(" "); pw.print(KEY_NOTIFICATION_WHITELIST_DURATION); pw.print("=");
959 TimeUtils.formatDuration(NOTIFICATION_WHITELIST_DURATION, pw);
960 pw.println();
Adam Lesinski31c05d12015-06-09 17:34:04 -0700961 }
962 }
963
964 private Constants mConstants;
965
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700966 @Override
967 public void onAnyMotionResult(int result) {
968 if (DEBUG) Slog.d(TAG, "onAnyMotionResult(" + result + ")");
Kevin Gabayan92f15e62016-04-04 17:52:22 -0700969 if (result != AnyMotionDetector.RESULT_UNKNOWN) {
970 synchronized (this) {
971 cancelSensingTimeoutAlarmLocked();
972 }
973 }
Kevin Gabayandcf47012016-07-08 10:41:24 -0700974 if ((result == AnyMotionDetector.RESULT_MOVED) ||
975 (result == AnyMotionDetector.RESULT_UNKNOWN)) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700976 synchronized (this) {
Kevin Gabayandcf47012016-07-08 10:41:24 -0700977 handleMotionDetectedLocked(mConstants.INACTIVE_TIMEOUT, "non_stationary");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700978 }
979 } else if (result == AnyMotionDetector.RESULT_STATIONARY) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700980 if (mState == STATE_SENSING) {
981 // If we are currently sensing, it is time to move to locating.
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700982 synchronized (this) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700983 mNotMoving = true;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800984 stepIdleStateLocked("s:stationary");
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700985 }
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700986 } else if (mState == STATE_LOCATING) {
987 // If we are currently locating, note that we are not moving and step
988 // if we have located the position.
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700989 synchronized (this) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700990 mNotMoving = true;
991 if (mLocated) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800992 stepIdleStateLocked("s:stationary");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700993 }
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700994 }
995 }
996 }
997 }
998
Joe Onorato8f0e9ced2016-12-08 17:48:49 -0800999 private static final int MSG_WRITE_CONFIG = 1;
1000 private static final int MSG_REPORT_IDLE_ON = 2;
1001 private static final int MSG_REPORT_IDLE_ON_LIGHT = 3;
1002 private static final int MSG_REPORT_IDLE_OFF = 4;
1003 private static final int MSG_REPORT_ACTIVE = 5;
1004 private static final int MSG_TEMP_APP_WHITELIST_TIMEOUT = 6;
1005 private static final int MSG_REPORT_MAINTENANCE_ACTIVITY = 7;
1006 private static final int MSG_FINISH_IDLE_OP = 8;
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001007 private static final int MSG_REPORT_TEMP_APP_WHITELIST_CHANGED = 9;
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: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001018 // Does not hold a wakelock. Just let this happen whenever.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001019 handleWriteConfigFile();
1020 } break;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001021 case MSG_REPORT_IDLE_ON:
1022 case MSG_REPORT_IDLE_ON_LIGHT: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001023 // mGoingIdleWakeLock is held at this point
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001024 EventLogTags.writeDeviceIdleOnStart();
Dianne Hackbornb6843652016-02-22 12:20:13 -08001025 final boolean deepChanged;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001026 final boolean lightChanged;
1027 if (msg.what == MSG_REPORT_IDLE_ON) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001028 deepChanged = mLocalPowerManager.setDeviceIdleMode(true);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001029 lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
1030 } else {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001031 deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001032 lightChanged = mLocalPowerManager.setLightDeviceIdleMode(true);
1033 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001034 try {
1035 mNetworkPolicyManager.setDeviceIdleMode(true);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001036 mBatteryStats.noteDeviceIdleMode(msg.what == MSG_REPORT_IDLE_ON
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07001037 ? BatteryStats.DEVICE_IDLE_MODE_DEEP
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001038 : BatteryStats.DEVICE_IDLE_MODE_LIGHT, null, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001039 } catch (RemoteException e) {
1040 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001041 if (deepChanged) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001042 getContext().sendBroadcastAsUser(mIdleIntent, UserHandle.ALL);
1043 }
1044 if (lightChanged) {
1045 getContext().sendBroadcastAsUser(mLightIdleIntent, UserHandle.ALL);
1046 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001047 EventLogTags.writeDeviceIdleOnComplete();
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001048 mGoingIdleWakeLock.release();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001049 } break;
1050 case MSG_REPORT_IDLE_OFF: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001051 // mActiveIdleWakeLock is held at this point
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001052 EventLogTags.writeDeviceIdleOffStart("unknown");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001053 final boolean deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001054 final boolean lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001055 try {
1056 mNetworkPolicyManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001057 mBatteryStats.noteDeviceIdleMode(BatteryStats.DEVICE_IDLE_MODE_OFF,
1058 null, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001059 } catch (RemoteException e) {
1060 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001061 if (deepChanged) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001062 incActiveIdleOps();
1063 getContext().sendOrderedBroadcastAsUser(mIdleIntent, UserHandle.ALL,
1064 null, mIdleStartedDoneReceiver, null, 0, null, null);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001065 }
1066 if (lightChanged) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001067 incActiveIdleOps();
1068 getContext().sendOrderedBroadcastAsUser(mLightIdleIntent, UserHandle.ALL,
1069 null, mIdleStartedDoneReceiver, null, 0, null, null);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001070 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001071 // Always start with one active op for the message being sent here.
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001072 // Now we are done!
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001073 decActiveIdleOps();
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001074 EventLogTags.writeDeviceIdleOffComplete();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001075 } break;
1076 case MSG_REPORT_ACTIVE: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001077 // The device is awake at this point, so no wakelock necessary.
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001078 String activeReason = (String)msg.obj;
1079 int activeUid = msg.arg1;
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001080 EventLogTags.writeDeviceIdleOffStart(
1081 activeReason != null ? activeReason : "unknown");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001082 final boolean deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001083 final boolean lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001084 try {
1085 mNetworkPolicyManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001086 mBatteryStats.noteDeviceIdleMode(BatteryStats.DEVICE_IDLE_MODE_OFF,
1087 activeReason, activeUid);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001088 } catch (RemoteException e) {
1089 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001090 if (deepChanged) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001091 getContext().sendBroadcastAsUser(mIdleIntent, UserHandle.ALL);
1092 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001093 if (lightChanged) {
1094 getContext().sendBroadcastAsUser(mLightIdleIntent, UserHandle.ALL);
1095 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001096 EventLogTags.writeDeviceIdleOffComplete();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001097 } break;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001098 case MSG_TEMP_APP_WHITELIST_TIMEOUT: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001099 // TODO: What is keeping the device awake at this point? Does it need to be?
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001100 int uid = msg.arg1;
1101 checkTempAppWhitelistTimeout(uid);
1102 } break;
Yao Chenca5edbb2016-01-13 14:44:36 -08001103 case MSG_REPORT_MAINTENANCE_ACTIVITY: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001104 // TODO: What is keeping the device awake at this point? Does it need to be?
Yao Chenca5edbb2016-01-13 14:44:36 -08001105 boolean active = (msg.arg1 == 1);
1106 final int size = mMaintenanceActivityListeners.beginBroadcast();
1107 try {
1108 for (int i = 0; i < size; i++) {
1109 try {
1110 mMaintenanceActivityListeners.getBroadcastItem(i)
1111 .onMaintenanceActivityChanged(active);
1112 } catch (RemoteException ignored) {
1113 }
1114 }
1115 } finally {
1116 mMaintenanceActivityListeners.finishBroadcast();
1117 }
1118 } break;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001119 case MSG_FINISH_IDLE_OP: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001120 // mActiveIdleWakeLock is held at this point
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001121 decActiveIdleOps();
1122 } break;
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001123 case MSG_REPORT_TEMP_APP_WHITELIST_CHANGED: {
1124 final int appId = msg.arg1;
1125 final boolean added = (msg.arg2 == 1);
1126 mNetworkPolicyManagerInternal.onTempPowerSaveWhitelistChange(appId, added);
1127 } break;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001128 }
1129 }
1130 }
1131
1132 final MyHandler mHandler;
1133
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001134 BinderService mBinderService;
1135
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001136 private final class BinderService extends IDeviceIdleController.Stub {
1137 @Override public void addPowerSaveWhitelistApp(String name) {
Eugene Susla6a7006a2017-03-13 12:57:58 -07001138 if (DEBUG) {
1139 Slog.i(TAG, "addPowerSaveWhitelistApp(name = " + name + ")");
1140 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001141 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1142 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001143 long ident = Binder.clearCallingIdentity();
1144 try {
1145 addPowerSaveWhitelistAppInternal(name);
1146 } finally {
1147 Binder.restoreCallingIdentity(ident);
1148 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001149 }
1150
1151 @Override public void removePowerSaveWhitelistApp(String name) {
Eugene Susla6a7006a2017-03-13 12:57:58 -07001152 if (DEBUG) {
1153 Slog.i(TAG, "removePowerSaveWhitelistApp(name = " + name + ")");
1154 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001155 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1156 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001157 long ident = Binder.clearCallingIdentity();
1158 try {
1159 removePowerSaveWhitelistAppInternal(name);
1160 } finally {
1161 Binder.restoreCallingIdentity(ident);
1162 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001163 }
1164
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001165 @Override public String[] getSystemPowerWhitelistExceptIdle() {
1166 return getSystemPowerWhitelistExceptIdleInternal();
1167 }
1168
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001169 @Override public String[] getSystemPowerWhitelist() {
1170 return getSystemPowerWhitelistInternal();
1171 }
1172
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001173 @Override public String[] getUserPowerWhitelist() {
1174 return getUserPowerWhitelistInternal();
1175 }
1176
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001177 @Override public String[] getFullPowerWhitelistExceptIdle() {
1178 return getFullPowerWhitelistExceptIdleInternal();
1179 }
1180
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001181 @Override public String[] getFullPowerWhitelist() {
1182 return getFullPowerWhitelistInternal();
1183 }
1184
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001185 @Override public int[] getAppIdWhitelistExceptIdle() {
1186 return getAppIdWhitelistExceptIdleInternal();
1187 }
1188
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001189 @Override public int[] getAppIdWhitelist() {
1190 return getAppIdWhitelistInternal();
1191 }
1192
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001193 @Override public int[] getAppIdUserWhitelist() {
1194 return getAppIdUserWhitelistInternal();
1195 }
1196
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001197 @Override public int[] getAppIdTempWhitelist() {
1198 return getAppIdTempWhitelistInternal();
1199 }
1200
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001201 @Override public boolean isPowerSaveWhitelistExceptIdleApp(String name) {
1202 return isPowerSaveWhitelistExceptIdleAppInternal(name);
1203 }
1204
Amith Yamasani06bf8242015-05-08 16:36:21 -07001205 @Override public boolean isPowerSaveWhitelistApp(String name) {
1206 return isPowerSaveWhitelistAppInternal(name);
1207 }
1208
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001209 @Override public void addPowerSaveTempWhitelistApp(String packageName, long duration,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001210 int userId, String reason) throws RemoteException {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001211 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001212 }
1213
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001214 @Override public long addPowerSaveTempWhitelistAppForMms(String packageName,
1215 int userId, String reason) throws RemoteException {
1216 long duration = mConstants.MMS_TEMP_APP_WHITELIST_DURATION;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001217 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001218 return duration;
1219 }
1220
Dianne Hackborn451c3462015-07-21 17:39:46 -07001221 @Override public long addPowerSaveTempWhitelistAppForSms(String packageName,
1222 int userId, String reason) throws RemoteException {
1223 long duration = mConstants.SMS_TEMP_APP_WHITELIST_DURATION;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001224 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Dianne Hackborn451c3462015-07-21 17:39:46 -07001225 return duration;
1226 }
1227
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001228 @Override public void exitIdle(String reason) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001229 getContext().enforceCallingOrSelfPermission(Manifest.permission.DEVICE_POWER,
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001230 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001231 long ident = Binder.clearCallingIdentity();
1232 try {
1233 exitIdleInternal(reason);
1234 } finally {
1235 Binder.restoreCallingIdentity(ident);
1236 }
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001237 }
1238
Yao Chenca5edbb2016-01-13 14:44:36 -08001239 @Override public boolean registerMaintenanceActivityListener(
1240 IMaintenanceActivityListener listener) {
1241 return DeviceIdleController.this.registerMaintenanceActivityListener(listener);
1242 }
1243
1244 @Override public void unregisterMaintenanceActivityListener(
1245 IMaintenanceActivityListener listener) {
1246 DeviceIdleController.this.unregisterMaintenanceActivityListener(listener);
1247 }
1248
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001249 @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1250 DeviceIdleController.this.dump(fd, pw, args);
1251 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001252
1253 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07001254 FileDescriptor err, String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
1255 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001256 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001257 }
1258
Felipe Lemeef134662016-08-10 14:46:39 -07001259 public class LocalService {
Christopher Tatee0be7e82017-02-08 17:38:20 -08001260 // duration in milliseconds
1261 public void addPowerSaveTempWhitelistApp(int callingUid, String packageName,
1262 long duration, int userId, boolean sync, String reason) {
1263 addPowerSaveTempWhitelistAppInternal(callingUid, packageName, duration,
1264 userId, sync, reason);
1265 }
1266
1267 // duration in milliseconds
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001268 public void addPowerSaveTempWhitelistAppDirect(int appId, long duration, boolean sync,
1269 String reason) {
1270 addPowerSaveTempWhitelistAppDirectInternal(0, appId, duration, sync, reason);
1271 }
1272
Christopher Tatee0be7e82017-02-08 17:38:20 -08001273 // duration in milliseconds
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001274 public long getNotificationWhitelistDuration() {
1275 return mConstants.NOTIFICATION_WHITELIST_DURATION;
1276 }
1277
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001278 public void setJobsActive(boolean active) {
1279 DeviceIdleController.this.setJobsActive(active);
1280 }
1281
1282 // Up-call from alarm manager.
1283 public void setAlarmsActive(boolean active) {
1284 DeviceIdleController.this.setAlarmsActive(active);
1285 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001286
Christopher Tate42a386b2016-11-07 12:21:21 -08001287 /** Is the app on any of the power save whitelists, whether system or user? */
1288 public boolean isAppOnWhitelist(int appid) {
1289 return DeviceIdleController.this.isAppOnWhitelistInternal(appid);
1290 }
1291
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001292 /**
1293 * Returns the array of app ids whitelisted by user. Take care not to
1294 * modify this, as it is a reference to the original copy. But the reference
1295 * can change when the list changes, so it needs to be re-acquired when
1296 * {@link PowerManager#ACTION_POWER_SAVE_WHITELIST_CHANGED} is sent.
1297 */
1298 public int[] getPowerSaveWhitelistUserAppIds() {
1299 return DeviceIdleController.this.getPowerSaveWhitelistUserAppIds();
1300 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001301 }
1302
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001303 public DeviceIdleController(Context context) {
1304 super(context);
1305 mConfigFile = new AtomicFile(new File(getSystemDir(), "deviceidle.xml"));
1306 mHandler = new MyHandler(BackgroundThread.getHandler().getLooper());
1307 }
1308
Christopher Tate42a386b2016-11-07 12:21:21 -08001309 boolean isAppOnWhitelistInternal(int appid) {
1310 synchronized (this) {
1311 return Arrays.binarySearch(mPowerSaveWhitelistAllAppIdArray, appid) >= 0;
1312 }
1313 }
1314
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001315 int[] getPowerSaveWhitelistUserAppIds() {
1316 synchronized (this) {
1317 return mPowerSaveWhitelistUserAppIdArray;
1318 }
1319 }
1320
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001321 private static File getSystemDir() {
1322 return new File(Environment.getDataDirectory(), "system");
1323 }
1324
1325 @Override
1326 public void onStart() {
1327 final PackageManager pm = getContext().getPackageManager();
1328
1329 synchronized (this) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001330 mLightEnabled = mDeepEnabled = getContext().getResources().getBoolean(
Dianne Hackborn92617032015-06-19 15:32:19 -07001331 com.android.internal.R.bool.config_enableAutoPowerModes);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001332 SystemConfig sysConfig = SystemConfig.getInstance();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001333 ArraySet<String> allowPowerExceptIdle = sysConfig.getAllowInPowerSaveExceptIdle();
1334 for (int i=0; i<allowPowerExceptIdle.size(); i++) {
1335 String pkg = allowPowerExceptIdle.valueAt(i);
1336 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001337 ApplicationInfo ai = pm.getApplicationInfo(pkg,
1338 PackageManager.MATCH_SYSTEM_ONLY);
1339 int appid = UserHandle.getAppId(ai.uid);
1340 mPowerSaveWhitelistAppsExceptIdle.put(ai.packageName, appid);
1341 mPowerSaveWhitelistSystemAppIdsExceptIdle.put(appid, true);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001342 } catch (PackageManager.NameNotFoundException e) {
1343 }
1344 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001345 ArraySet<String> allowPower = sysConfig.getAllowInPowerSave();
1346 for (int i=0; i<allowPower.size(); i++) {
1347 String pkg = allowPower.valueAt(i);
1348 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001349 ApplicationInfo ai = pm.getApplicationInfo(pkg,
1350 PackageManager.MATCH_SYSTEM_ONLY);
1351 int appid = UserHandle.getAppId(ai.uid);
1352 // These apps are on both the whitelist-except-idle as well
1353 // as the full whitelist, so they apply in all cases.
1354 mPowerSaveWhitelistAppsExceptIdle.put(ai.packageName, appid);
1355 mPowerSaveWhitelistSystemAppIdsExceptIdle.put(appid, true);
1356 mPowerSaveWhitelistApps.put(ai.packageName, appid);
1357 mPowerSaveWhitelistSystemAppIds.put(appid, true);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001358 } catch (PackageManager.NameNotFoundException e) {
1359 }
1360 }
1361
Adam Lesinski31c05d12015-06-09 17:34:04 -07001362 mConstants = new Constants(mHandler, getContext().getContentResolver());
1363
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001364 readConfigFileLocked();
1365 updateWhitelistAppIdsLocked();
1366
Dianne Hackborn88c41352016-04-07 15:18:58 -07001367 mNetworkConnected = true;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001368 mScreenOn = true;
1369 // Start out assuming we are charging. If we aren't, we will at least get
1370 // a battery update the next time the level drops.
1371 mCharging = true;
1372 mState = STATE_ACTIVE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001373 mLightState = LIGHT_STATE_ACTIVE;
Adam Lesinski31c05d12015-06-09 17:34:04 -07001374 mInactiveTimeout = mConstants.INACTIVE_TIMEOUT;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001375 }
1376
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001377 mBinderService = new BinderService();
1378 publishBinderService(Context.DEVICE_IDLE_CONTROLLER, mBinderService);
Dianne Hackborna750a632015-06-16 17:18:23 -07001379 publishLocalService(LocalService.class, new LocalService());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001380 }
1381
1382 @Override
1383 public void onBootPhase(int phase) {
1384 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1385 synchronized (this) {
1386 mAlarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
1387 mBatteryStats = BatteryStatsService.getService();
Dianne Hackborn85e35642017-01-12 15:10:57 -08001388 mLocalActivityManager = getLocalService(ActivityManagerInternal.class);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001389 mLocalPowerManager = getLocalService(PowerManagerInternal.class);
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001390 mPowerManager = getContext().getSystemService(PowerManager.class);
1391 mActiveIdleWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
1392 "deviceidle_maint");
1393 mActiveIdleWakeLock.setReferenceCounted(false);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001394 mGoingIdleWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
1395 "deviceidle_going_idle");
1396 mGoingIdleWakeLock.setReferenceCounted(true);
Dianne Hackborn88c41352016-04-07 15:18:58 -07001397 mConnectivityService = (ConnectivityService)ServiceManager.getService(
1398 Context.CONNECTIVITY_SERVICE);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001399 mLocalAlarmManager = getLocalService(AlarmManagerService.LocalService.class);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001400 mNetworkPolicyManager = INetworkPolicyManager.Stub.asInterface(
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001401 ServiceManager.getService(Context.NETWORK_POLICY_SERVICE));
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001402 mNetworkPolicyManagerInternal = getLocalService(NetworkPolicyManagerInternal.class);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001403 mSensorManager = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001404 int sigMotionSensorId = getContext().getResources().getInteger(
1405 com.android.internal.R.integer.config_autoPowerModeAnyMotionSensor);
1406 if (sigMotionSensorId > 0) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001407 mMotionSensor = mSensorManager.getDefaultSensor(sigMotionSensorId, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001408 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001409 if (mMotionSensor == null && getContext().getResources().getBoolean(
Joe LaPenna23d681b2015-08-27 15:12:11 -07001410 com.android.internal.R.bool.config_autoPowerModePreferWristTilt)) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001411 mMotionSensor = mSensorManager.getDefaultSensor(
1412 Sensor.TYPE_WRIST_TILT_GESTURE, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001413 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001414 if (mMotionSensor == null) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07001415 // As a last ditch, fall back to SMD.
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001416 mMotionSensor = mSensorManager.getDefaultSensor(
1417 Sensor.TYPE_SIGNIFICANT_MOTION, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001418 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001419
Joe LaPenna23d681b2015-08-27 15:12:11 -07001420 if (getContext().getResources().getBoolean(
1421 com.android.internal.R.bool.config_autoPowerModePrefetchLocation)) {
1422 mLocationManager = (LocationManager) getContext().getSystemService(
1423 Context.LOCATION_SERVICE);
1424 mLocationRequest = new LocationRequest()
1425 .setQuality(LocationRequest.ACCURACY_FINE)
1426 .setInterval(0)
1427 .setFastestInterval(0)
1428 .setNumUpdates(1);
1429 }
1430
1431 float angleThreshold = getContext().getResources().getInteger(
1432 com.android.internal.R.integer.config_autoPowerModeThresholdAngle) / 100f;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001433 mAnyMotionDetector = new AnyMotionDetector(
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001434 (PowerManager) getContext().getSystemService(Context.POWER_SERVICE),
Joe LaPenna23d681b2015-08-27 15:12:11 -07001435 mHandler, mSensorManager, this, angleThreshold);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001436
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001437 mIdleIntent = new Intent(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001438 mIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1439 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001440 mLightIdleIntent = new Intent(PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED);
1441 mLightIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1442 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001443
1444 IntentFilter filter = new IntentFilter();
1445 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001446 getContext().registerReceiver(mReceiver, filter);
Amith Yamasaniac59f75e2016-05-05 12:38:17 -07001447
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001448 filter = new IntentFilter();
1449 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1450 filter.addDataScheme("package");
Amith Yamasaniac59f75e2016-05-05 12:38:17 -07001451 getContext().registerReceiver(mReceiver, filter);
1452
Dianne Hackborn88c41352016-04-07 15:18:58 -07001453 filter = new IntentFilter();
1454 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001455 getContext().registerReceiver(mReceiver, filter);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001456
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -07001457 filter = new IntentFilter();
1458 filter.addAction(Intent.ACTION_SCREEN_OFF);
1459 filter.addAction(Intent.ACTION_SCREEN_ON);
1460 getContext().registerReceiver(mInteractivityReceiver, filter);
1461
Dianne Hackborn85e35642017-01-12 15:10:57 -08001462 mLocalActivityManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001463 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001464 mLocalAlarmManager.setDeviceIdleUserWhitelist(mPowerSaveWhitelistUserAppIdArray);
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -07001465
1466 updateInteractivityLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001467 }
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -07001468 updateConnectivityState(null);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001469 }
1470 }
1471
1472 public boolean addPowerSaveWhitelistAppInternal(String name) {
1473 synchronized (this) {
1474 try {
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001475 ApplicationInfo ai = getContext().getPackageManager().getApplicationInfo(name,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07001476 PackageManager.MATCH_ANY_USER);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001477 if (mPowerSaveWhitelistUserApps.put(name, UserHandle.getAppId(ai.uid)) == null) {
1478 reportPowerSaveWhitelistChangedLocked();
1479 updateWhitelistAppIdsLocked();
1480 writeConfigFileLocked();
1481 }
1482 return true;
1483 } catch (PackageManager.NameNotFoundException e) {
1484 return false;
1485 }
1486 }
1487 }
1488
1489 public boolean removePowerSaveWhitelistAppInternal(String name) {
1490 synchronized (this) {
1491 if (mPowerSaveWhitelistUserApps.remove(name) != null) {
1492 reportPowerSaveWhitelistChangedLocked();
1493 updateWhitelistAppIdsLocked();
1494 writeConfigFileLocked();
1495 return true;
1496 }
1497 }
1498 return false;
1499 }
1500
Felipe Lemef8a46232016-02-10 13:51:54 -08001501 public boolean getPowerSaveWhitelistAppInternal(String name) {
1502 synchronized (this) {
1503 return mPowerSaveWhitelistUserApps.containsKey(name);
1504 }
1505 }
1506
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07001507 public boolean addPowerSaveWhitelistExceptIdleInternal(String name) {
1508 synchronized (this) {
1509 try {
1510 final ApplicationInfo ai = getContext().getPackageManager().getApplicationInfo(name,
1511 PackageManager.MATCH_ANY_USER);
1512 if (mPowerSaveWhitelistAppsExceptIdle.put(name, UserHandle.getAppId(ai.uid))
1513 == null) {
1514 mPowerSaveWhitelistUserAppsExceptIdle.add(name);
1515 reportPowerSaveWhitelistChangedLocked();
1516 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(
1517 mPowerSaveWhitelistAppsExceptIdle, mPowerSaveWhitelistUserApps,
1518 mPowerSaveWhitelistExceptIdleAppIds);
1519 }
1520 return true;
1521 } catch (PackageManager.NameNotFoundException e) {
1522 return false;
1523 }
1524 }
1525 }
1526
1527 public void resetPowerSaveWhitelistExceptIdleInternal() {
1528 synchronized (this) {
1529 if (mPowerSaveWhitelistAppsExceptIdle.removeAll(
1530 mPowerSaveWhitelistUserAppsExceptIdle)) {
1531 reportPowerSaveWhitelistChangedLocked();
1532 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(
1533 mPowerSaveWhitelistAppsExceptIdle, mPowerSaveWhitelistUserApps,
1534 mPowerSaveWhitelistExceptIdleAppIds);
1535 mPowerSaveWhitelistUserAppsExceptIdle.clear();
1536 }
1537 }
1538 }
1539
1540 public boolean getPowerSaveWhitelistExceptIdleInternal(String name) {
1541 synchronized (this) {
1542 return mPowerSaveWhitelistAppsExceptIdle.containsKey(name);
1543 }
1544 }
1545
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001546 public String[] getSystemPowerWhitelistExceptIdleInternal() {
1547 synchronized (this) {
1548 int size = mPowerSaveWhitelistAppsExceptIdle.size();
1549 String[] apps = new String[size];
1550 for (int i = 0; i < size; i++) {
1551 apps[i] = mPowerSaveWhitelistAppsExceptIdle.keyAt(i);
1552 }
1553 return apps;
1554 }
1555 }
1556
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001557 public String[] getSystemPowerWhitelistInternal() {
1558 synchronized (this) {
1559 int size = mPowerSaveWhitelistApps.size();
1560 String[] apps = new String[size];
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001561 for (int i = 0; i < size; i++) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001562 apps[i] = mPowerSaveWhitelistApps.keyAt(i);
1563 }
1564 return apps;
1565 }
1566 }
1567
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001568 public String[] getUserPowerWhitelistInternal() {
1569 synchronized (this) {
1570 int size = mPowerSaveWhitelistUserApps.size();
1571 String[] apps = new String[size];
1572 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1573 apps[i] = mPowerSaveWhitelistUserApps.keyAt(i);
1574 }
1575 return apps;
1576 }
1577 }
1578
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001579 public String[] getFullPowerWhitelistExceptIdleInternal() {
1580 synchronized (this) {
1581 int size = mPowerSaveWhitelistAppsExceptIdle.size() + mPowerSaveWhitelistUserApps.size();
1582 String[] apps = new String[size];
1583 int cur = 0;
1584 for (int i = 0; i < mPowerSaveWhitelistAppsExceptIdle.size(); i++) {
1585 apps[cur] = mPowerSaveWhitelistAppsExceptIdle.keyAt(i);
1586 cur++;
1587 }
1588 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1589 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
1590 cur++;
1591 }
1592 return apps;
1593 }
1594 }
1595
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001596 public String[] getFullPowerWhitelistInternal() {
1597 synchronized (this) {
1598 int size = mPowerSaveWhitelistApps.size() + mPowerSaveWhitelistUserApps.size();
1599 String[] apps = new String[size];
1600 int cur = 0;
1601 for (int i = 0; i < mPowerSaveWhitelistApps.size(); i++) {
1602 apps[cur] = mPowerSaveWhitelistApps.keyAt(i);
1603 cur++;
1604 }
1605 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1606 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
1607 cur++;
1608 }
1609 return apps;
1610 }
1611 }
1612
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001613 public boolean isPowerSaveWhitelistExceptIdleAppInternal(String packageName) {
1614 synchronized (this) {
1615 return mPowerSaveWhitelistAppsExceptIdle.containsKey(packageName)
1616 || mPowerSaveWhitelistUserApps.containsKey(packageName);
1617 }
1618 }
1619
Amith Yamasani06bf8242015-05-08 16:36:21 -07001620 public boolean isPowerSaveWhitelistAppInternal(String packageName) {
1621 synchronized (this) {
1622 return mPowerSaveWhitelistApps.containsKey(packageName)
1623 || mPowerSaveWhitelistUserApps.containsKey(packageName);
1624 }
1625 }
1626
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001627 public int[] getAppIdWhitelistExceptIdleInternal() {
1628 synchronized (this) {
1629 return mPowerSaveWhitelistExceptIdleAppIdArray;
1630 }
1631 }
1632
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001633 public int[] getAppIdWhitelistInternal() {
1634 synchronized (this) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001635 return mPowerSaveWhitelistAllAppIdArray;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001636 }
1637 }
1638
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001639 public int[] getAppIdUserWhitelistInternal() {
1640 synchronized (this) {
1641 return mPowerSaveWhitelistUserAppIdArray;
1642 }
1643 }
1644
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001645 public int[] getAppIdTempWhitelistInternal() {
1646 synchronized (this) {
1647 return mTempWhitelistAppIdArray;
1648 }
1649 }
1650
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001651 void addPowerSaveTempWhitelistAppChecked(String packageName, long duration,
1652 int userId, String reason) throws RemoteException {
1653 getContext().enforceCallingPermission(
1654 Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
1655 "No permission to change device idle whitelist");
1656 final int callingUid = Binder.getCallingUid();
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001657 userId = ActivityManager.getService().handleIncomingUser(
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001658 Binder.getCallingPid(),
1659 callingUid,
1660 userId,
1661 /*allowAll=*/ false,
1662 /*requireFull=*/ false,
1663 "addPowerSaveTempWhitelistApp", null);
1664 final long token = Binder.clearCallingIdentity();
1665 try {
1666 addPowerSaveTempWhitelistAppInternal(callingUid,
1667 packageName, duration, userId, true, reason);
1668 } finally {
1669 Binder.restoreCallingIdentity(token);
1670 }
1671 }
1672
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001673 /**
1674 * Adds an app to the temporary whitelist and resets the endTime for granting the
1675 * app an exemption to access network and acquire wakelocks.
1676 */
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001677 void addPowerSaveTempWhitelistAppInternal(int callingUid, String packageName,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001678 long duration, int userId, boolean sync, String reason) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001679 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001680 int uid = getContext().getPackageManager().getPackageUidAsUser(packageName, userId);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001681 int appId = UserHandle.getAppId(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001682 addPowerSaveTempWhitelistAppDirectInternal(callingUid, appId, duration, sync, reason);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001683 } catch (NameNotFoundException e) {
1684 }
1685 }
1686
Dianne Hackborna750a632015-06-16 17:18:23 -07001687 /**
1688 * Adds an app to the temporary whitelist and resets the endTime for granting the
1689 * app an exemption to access network and acquire wakelocks.
1690 */
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001691 void addPowerSaveTempWhitelistAppDirectInternal(int callingUid, int appId,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001692 long duration, boolean sync, String reason) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001693 final long timeNow = SystemClock.elapsedRealtime();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001694 boolean informWhitelistChanged = false;
Dianne Hackborna750a632015-06-16 17:18:23 -07001695 synchronized (this) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001696 int callingAppId = UserHandle.getAppId(callingUid);
1697 if (callingAppId >= Process.FIRST_APPLICATION_UID) {
1698 if (!mPowerSaveWhitelistSystemAppIds.get(callingAppId)) {
1699 throw new SecurityException("Calling app " + UserHandle.formatUid(callingUid)
1700 + " is not on whitelist");
1701 }
1702 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001703 duration = Math.min(duration, mConstants.MAX_TEMP_APP_WHITELIST_DURATION);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001704 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.get(appId);
1705 final boolean newEntry = entry == null;
Dianne Hackborna750a632015-06-16 17:18:23 -07001706 // Set the new end time
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001707 if (newEntry) {
1708 entry = new Pair<>(new MutableLong(0), reason);
1709 mTempWhitelistAppIdEndTimes.put(appId, entry);
1710 }
1711 entry.first.value = timeNow + duration;
Dianne Hackborna750a632015-06-16 17:18:23 -07001712 if (DEBUG) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001713 Slog.d(TAG, "Adding AppId " + appId + " to temp whitelist. New entry: " + newEntry);
Dianne Hackborna750a632015-06-16 17:18:23 -07001714 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001715 if (newEntry) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001716 // No pending timeout for the app id, post a delayed message
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001717 try {
1718 mBatteryStats.noteEvent(BatteryStats.HistoryItem.EVENT_TEMP_WHITELIST_START,
1719 reason, appId);
1720 } catch (RemoteException e) {
1721 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001722 postTempActiveTimeoutMessage(appId, duration);
Dianne Hackborn85e35642017-01-12 15:10:57 -08001723 updateTempWhitelistAppIdsLocked(appId, true);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001724 if (sync) {
1725 informWhitelistChanged = true;
1726 } else {
1727 mHandler.obtainMessage(MSG_REPORT_TEMP_APP_WHITELIST_CHANGED, appId, 1)
1728 .sendToTarget();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001729 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001730 reportTempWhitelistChangedLocked();
1731 }
1732 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001733 if (informWhitelistChanged) {
1734 mNetworkPolicyManagerInternal.onTempPowerSaveWhitelistChange(appId, true);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001735 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001736 }
1737
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001738 private void postTempActiveTimeoutMessage(int uid, long delay) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001739 if (DEBUG) {
1740 Slog.d(TAG, "postTempActiveTimeoutMessage: uid=" + uid + ", delay=" + delay);
1741 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001742 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_TEMP_APP_WHITELIST_TIMEOUT, uid, 0),
1743 delay);
1744 }
1745
1746 void checkTempAppWhitelistTimeout(int uid) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001747 final long timeNow = SystemClock.elapsedRealtime();
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001748 if (DEBUG) {
1749 Slog.d(TAG, "checkTempAppWhitelistTimeout: uid=" + uid + ", timeNow=" + timeNow);
1750 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001751 synchronized (this) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001752 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.get(uid);
1753 if (entry == null) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001754 // Nothing to do
1755 return;
1756 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001757 if (timeNow >= entry.first.value) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001758 mTempWhitelistAppIdEndTimes.delete(uid);
1759 if (DEBUG) {
1760 Slog.d(TAG, "Removing UID " + uid + " from temp whitelist");
1761 }
Dianne Hackborn85e35642017-01-12 15:10:57 -08001762 updateTempWhitelistAppIdsLocked(uid, false);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001763 mHandler.obtainMessage(MSG_REPORT_TEMP_APP_WHITELIST_CHANGED, uid, 0)
1764 .sendToTarget();
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001765 reportTempWhitelistChangedLocked();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001766 try {
1767 mBatteryStats.noteEvent(BatteryStats.HistoryItem.EVENT_TEMP_WHITELIST_FINISH,
1768 entry.second, uid);
1769 } catch (RemoteException e) {
1770 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001771 } else {
1772 // Need more time
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001773 if (DEBUG) {
1774 Slog.d(TAG, "Time to remove UID " + uid + ": " + entry.first.value);
1775 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001776 postTempActiveTimeoutMessage(uid, entry.first.value - timeNow);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001777 }
1778 }
1779 }
1780
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001781 public void exitIdleInternal(String reason) {
1782 synchronized (this) {
1783 becomeActiveLocked(reason, Binder.getCallingUid());
1784 }
1785 }
1786
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -07001787 void updateConnectivityState(Intent connIntent) {
1788 ConnectivityService cm;
1789 synchronized (this) {
1790 cm = mConnectivityService;
1791 }
1792 if (cm == null) {
1793 return;
1794 }
1795 // Note: can't call out to ConnectivityService with our lock held.
1796 NetworkInfo ni = cm.getActiveNetworkInfo();
1797 synchronized (this) {
Dianne Hackborn88c41352016-04-07 15:18:58 -07001798 boolean conn;
1799 if (ni == null) {
1800 conn = false;
1801 } else {
1802 if (connIntent == null) {
1803 conn = ni.isConnected();
1804 } else {
1805 final int networkType =
1806 connIntent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1807 ConnectivityManager.TYPE_NONE);
1808 if (ni.getType() != networkType) {
1809 return;
1810 }
1811 conn = !connIntent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,
1812 false);
1813 }
1814 }
1815 if (conn != mNetworkConnected) {
1816 mNetworkConnected = conn;
1817 if (conn && mLightState == LIGHT_STATE_WAITING_FOR_NETWORK) {
1818 stepLightIdleStateLocked("network");
1819 }
1820 }
1821 }
1822 }
1823
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -07001824 void updateInteractivityLocked() {
1825 // The interactivity state from the power manager tells us whether the display is
1826 // in a state that we need to keep things running so they will update at a normal
1827 // frequency.
1828 boolean screenOn = mPowerManager.isInteractive();
1829 if (DEBUG) Slog.d(TAG, "updateInteractivityLocked: screenOn=" + screenOn);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001830 if (!screenOn && mScreenOn) {
1831 mScreenOn = false;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001832 if (!mForceIdle) {
1833 becomeInactiveIfAppropriateLocked();
1834 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001835 } else if (screenOn) {
1836 mScreenOn = true;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001837 if (!mForceIdle) {
1838 becomeActiveLocked("screen", Process.myUid());
1839 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001840 }
1841 }
1842
1843 void updateChargingLocked(boolean charging) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001844 if (DEBUG) Slog.i(TAG, "updateChargingLocked: charging=" + charging);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001845 if (!charging && mCharging) {
1846 mCharging = false;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001847 if (!mForceIdle) {
1848 becomeInactiveIfAppropriateLocked();
1849 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001850 } else if (charging) {
1851 mCharging = charging;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001852 if (!mForceIdle) {
1853 becomeActiveLocked("charging", Process.myUid());
1854 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001855 }
1856 }
1857
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001858 void scheduleReportActiveLocked(String activeReason, int activeUid) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001859 Message msg = mHandler.obtainMessage(MSG_REPORT_ACTIVE, activeUid, 0, activeReason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001860 mHandler.sendMessage(msg);
1861 }
1862
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001863 void becomeActiveLocked(String activeReason, int activeUid) {
1864 if (DEBUG) Slog.i(TAG, "becomeActiveLocked, reason = " + activeReason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001865 if (mState != STATE_ACTIVE || mLightState != STATE_ACTIVE) {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001866 EventLogTags.writeDeviceIdle(STATE_ACTIVE, activeReason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001867 EventLogTags.writeDeviceIdleLight(LIGHT_STATE_ACTIVE, activeReason);
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001868 scheduleReportActiveLocked(activeReason, activeUid);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001869 mState = STATE_ACTIVE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001870 mLightState = LIGHT_STATE_ACTIVE;
Adam Lesinski31c05d12015-06-09 17:34:04 -07001871 mInactiveTimeout = mConstants.INACTIVE_TIMEOUT;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001872 mCurIdleBudget = 0;
1873 mMaintenanceStartTime = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001874 resetIdleManagementLocked();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001875 resetLightIdleManagementLocked();
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001876 addEvent(EVENT_NORMAL);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001877 }
1878 }
1879
1880 void becomeInactiveIfAppropriateLocked() {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001881 if (DEBUG) Slog.d(TAG, "becomeInactiveIfAppropriateLocked()");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001882 if ((!mScreenOn && !mCharging) || mForceIdle) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001883 // Screen has turned off; we are now going to become inactive and start
1884 // waiting to see if we will ultimately go idle.
Dianne Hackbornb6843652016-02-22 12:20:13 -08001885 if (mState == STATE_ACTIVE && mDeepEnabled) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001886 mState = STATE_INACTIVE;
1887 if (DEBUG) Slog.d(TAG, "Moved from STATE_ACTIVE to STATE_INACTIVE");
1888 resetIdleManagementLocked();
1889 scheduleAlarmLocked(mInactiveTimeout, false);
1890 EventLogTags.writeDeviceIdle(mState, "no activity");
1891 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001892 if (mLightState == LIGHT_STATE_ACTIVE && mLightEnabled) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001893 mLightState = LIGHT_STATE_INACTIVE;
1894 if (DEBUG) Slog.d(TAG, "Moved from LIGHT_STATE_ACTIVE to LIGHT_STATE_INACTIVE");
1895 resetLightIdleManagementLocked();
Dianne Hackborn953fc942016-03-29 15:36:24 -07001896 scheduleLightAlarmLocked(mConstants.LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001897 EventLogTags.writeDeviceIdleLight(mLightState, "no activity");
1898 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001899 }
1900 }
1901
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001902 void resetIdleManagementLocked() {
1903 mNextIdlePendingDelay = 0;
1904 mNextIdleDelay = 0;
Dianne Hackborn953fc942016-03-29 15:36:24 -07001905 mNextLightIdleDelay = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001906 cancelAlarmLocked();
Kevin Gabayan92f15e62016-04-04 17:52:22 -07001907 cancelSensingTimeoutAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001908 cancelLocatingLocked();
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001909 stopMonitoringMotionLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001910 mAnyMotionDetector.stop();
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001911 }
1912
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001913 void resetLightIdleManagementLocked() {
1914 cancelLightAlarmLocked();
1915 }
1916
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001917 void exitForceIdleLocked() {
1918 if (mForceIdle) {
1919 mForceIdle = false;
1920 if (mScreenOn || mCharging) {
Dianne Hackborn88c41352016-04-07 15:18:58 -07001921 becomeActiveLocked("exit-force", Process.myUid());
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001922 }
1923 }
1924 }
1925
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001926 void stepLightIdleStateLocked(String reason) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001927 if (mLightState == LIGHT_STATE_OVERRIDE) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001928 // If we are already in deep device idle mode, then
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001929 // there is nothing left to do for light mode.
1930 return;
1931 }
1932
1933 if (DEBUG) Slog.d(TAG, "stepLightIdleStateLocked: mLightState=" + mLightState);
1934 EventLogTags.writeDeviceIdleLightStep();
1935
1936 switch (mLightState) {
1937 case LIGHT_STATE_INACTIVE:
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001938 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
Dianne Hackborn953fc942016-03-29 15:36:24 -07001939 // Reset the upcoming idle delays.
1940 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001941 mMaintenanceStartTime = 0;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001942 if (!isOpsInactiveLocked()) {
1943 // We have some active ops going on... give them a chance to finish
1944 // before going in to our first idle.
1945 mLightState = LIGHT_STATE_PRE_IDLE;
1946 EventLogTags.writeDeviceIdleLight(mLightState, reason);
1947 scheduleLightAlarmLocked(mConstants.LIGHT_PRE_IDLE_TIMEOUT);
1948 break;
1949 }
1950 // Nothing active, fall through to immediately idle.
1951 case LIGHT_STATE_PRE_IDLE:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001952 case LIGHT_STATE_IDLE_MAINTENANCE:
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001953 if (mMaintenanceStartTime != 0) {
1954 long duration = SystemClock.elapsedRealtime() - mMaintenanceStartTime;
1955 if (duration < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
1956 // We didn't use up all of our minimum budget; add this to the reserve.
1957 mCurIdleBudget += (mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET-duration);
1958 } else {
1959 // We used more than our minimum budget; this comes out of the reserve.
1960 mCurIdleBudget -= (duration-mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET);
1961 }
1962 }
1963 mMaintenanceStartTime = 0;
Dianne Hackborn953fc942016-03-29 15:36:24 -07001964 scheduleLightAlarmLocked(mNextLightIdleDelay);
1965 mNextLightIdleDelay = Math.min(mConstants.LIGHT_MAX_IDLE_TIMEOUT,
1966 (long)(mNextLightIdleDelay * mConstants.LIGHT_IDLE_FACTOR));
1967 if (mNextLightIdleDelay < mConstants.LIGHT_IDLE_TIMEOUT) {
1968 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
1969 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001970 if (DEBUG) Slog.d(TAG, "Moved to LIGHT_STATE_IDLE.");
1971 mLightState = LIGHT_STATE_IDLE;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001972 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001973 addEvent(EVENT_LIGHT_IDLE);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001974 mGoingIdleWakeLock.acquire();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001975 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON_LIGHT);
1976 break;
1977 case LIGHT_STATE_IDLE:
Dianne Hackborn88c41352016-04-07 15:18:58 -07001978 case LIGHT_STATE_WAITING_FOR_NETWORK:
1979 if (mNetworkConnected || mLightState == LIGHT_STATE_WAITING_FOR_NETWORK) {
1980 // We have been idling long enough, now it is time to do some work.
1981 mActiveIdleOpCount = 1;
1982 mActiveIdleWakeLock.acquire();
1983 mMaintenanceStartTime = SystemClock.elapsedRealtime();
1984 if (mCurIdleBudget < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
1985 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
1986 } else if (mCurIdleBudget > mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET) {
1987 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET;
1988 }
1989 scheduleLightAlarmLocked(mCurIdleBudget);
1990 if (DEBUG) Slog.d(TAG,
1991 "Moved from LIGHT_STATE_IDLE to LIGHT_STATE_IDLE_MAINTENANCE.");
1992 mLightState = LIGHT_STATE_IDLE_MAINTENANCE;
1993 EventLogTags.writeDeviceIdleLight(mLightState, reason);
1994 addEvent(EVENT_LIGHT_MAINTENANCE);
1995 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
1996 } else {
1997 // We'd like to do maintenance, but currently don't have network
1998 // connectivity... let's try to wait until the network comes back.
1999 // We'll only wait for another full idle period, however, and then give up.
2000 scheduleLightAlarmLocked(mNextLightIdleDelay);
2001 if (DEBUG) Slog.d(TAG, "Moved to LIGHT_WAITING_FOR_NETWORK.");
2002 mLightState = LIGHT_STATE_WAITING_FOR_NETWORK;
2003 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002004 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002005 break;
2006 }
2007 }
2008
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002009 void stepIdleStateLocked(String reason) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002010 if (DEBUG) Slog.d(TAG, "stepIdleStateLocked: mState=" + mState);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002011 EventLogTags.writeDeviceIdleStep();
2012
2013 final long now = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07002014 if ((now+mConstants.MIN_TIME_TO_ALARM) > mAlarmManager.getNextWakeFromIdleTime()) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002015 // Whoops, there is an upcoming alarm. We don't actually want to go idle.
2016 if (mState != STATE_ACTIVE) {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002017 becomeActiveLocked("alarm", Process.myUid());
Koji Fukui27b33302015-12-16 19:43:01 +09002018 becomeInactiveIfAppropriateLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002019 }
2020 return;
2021 }
2022
2023 switch (mState) {
2024 case STATE_INACTIVE:
2025 // We have now been inactive long enough, it is time to start looking
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002026 // for motion and sleep some more while doing so.
2027 startMonitoringMotionLocked();
Adam Lesinski31c05d12015-06-09 17:34:04 -07002028 scheduleAlarmLocked(mConstants.IDLE_AFTER_INACTIVE_TIMEOUT, false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002029 // Reset the upcoming idle delays.
Adam Lesinski31c05d12015-06-09 17:34:04 -07002030 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
2031 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002032 mState = STATE_IDLE_PENDING;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002033 if (DEBUG) Slog.d(TAG, "Moved from STATE_INACTIVE to STATE_IDLE_PENDING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002034 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002035 break;
2036 case STATE_IDLE_PENDING:
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002037 mState = STATE_SENSING;
2038 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE_PENDING to STATE_SENSING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002039 EventLogTags.writeDeviceIdle(mState, reason);
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002040 scheduleSensingTimeoutAlarmLocked(mConstants.SENSING_TIMEOUT);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002041 cancelLocatingLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002042 mNotMoving = false;
2043 mLocated = false;
2044 mLastGenericLocation = null;
2045 mLastGpsLocation = null;
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002046 mAnyMotionDetector.checkForAnyMotion();
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002047 break;
2048 case STATE_SENSING:
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002049 cancelSensingTimeoutAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002050 mState = STATE_LOCATING;
2051 if (DEBUG) Slog.d(TAG, "Moved from STATE_SENSING to STATE_LOCATING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002052 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002053 scheduleAlarmLocked(mConstants.LOCATING_TIMEOUT, false);
Joe LaPenna23d681b2015-08-27 15:12:11 -07002054 if (mLocationManager != null
2055 && mLocationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
2056 mLocationManager.requestLocationUpdates(mLocationRequest,
2057 mGenericLocationListener, mHandler.getLooper());
2058 mLocating = true;
2059 } else {
2060 mHasNetworkLocation = false;
2061 }
2062 if (mLocationManager != null
2063 && mLocationManager.getProvider(LocationManager.GPS_PROVIDER) != null) {
2064 mHasGps = true;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002065 mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 5,
2066 mGpsLocationListener, mHandler.getLooper());
Joe LaPenna23d681b2015-08-27 15:12:11 -07002067 mLocating = true;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002068 } else {
Joe LaPenna23d681b2015-08-27 15:12:11 -07002069 mHasGps = false;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002070 }
Joe LaPenna23d681b2015-08-27 15:12:11 -07002071 // If we have a location provider, we're all set, the listeners will move state
2072 // forward.
2073 if (mLocating) {
2074 break;
2075 }
2076
2077 // Otherwise, we have to move from locating into idle maintenance.
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002078 case STATE_LOCATING:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002079 cancelAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002080 cancelLocatingLocked();
2081 mAnyMotionDetector.stop();
Dianne Hackborn953fc942016-03-29 15:36:24 -07002082
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002083 case STATE_IDLE_MAINTENANCE:
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002084 scheduleAlarmLocked(mNextIdleDelay, true);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002085 if (DEBUG) Slog.d(TAG, "Moved to STATE_IDLE. Next alarm in " + mNextIdleDelay +
2086 " ms.");
Adam Lesinski31c05d12015-06-09 17:34:04 -07002087 mNextIdleDelay = (long)(mNextIdleDelay * mConstants.IDLE_FACTOR);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002088 if (DEBUG) Slog.d(TAG, "Setting mNextIdleDelay = " + mNextIdleDelay);
Adam Lesinski31c05d12015-06-09 17:34:04 -07002089 mNextIdleDelay = Math.min(mNextIdleDelay, mConstants.MAX_IDLE_TIMEOUT);
Dianne Hackborn953fc942016-03-29 15:36:24 -07002090 if (mNextIdleDelay < mConstants.IDLE_TIMEOUT) {
2091 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
2092 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002093 mState = STATE_IDLE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002094 if (mLightState != LIGHT_STATE_OVERRIDE) {
2095 mLightState = LIGHT_STATE_OVERRIDE;
2096 cancelLightAlarmLocked();
2097 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002098 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackbornb6843652016-02-22 12:20:13 -08002099 addEvent(EVENT_DEEP_IDLE);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08002100 mGoingIdleWakeLock.acquire();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002101 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON);
2102 break;
2103 case STATE_IDLE:
2104 // We have been idling long enough, now it is time to do some work.
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002105 mActiveIdleOpCount = 1;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002106 mActiveIdleWakeLock.acquire();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002107 scheduleAlarmLocked(mNextIdlePendingDelay, false);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002108 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE to STATE_IDLE_MAINTENANCE. " +
2109 "Next alarm in " + mNextIdlePendingDelay + " ms.");
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002110 mMaintenanceStartTime = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07002111 mNextIdlePendingDelay = Math.min(mConstants.MAX_IDLE_PENDING_TIMEOUT,
2112 (long)(mNextIdlePendingDelay * mConstants.IDLE_PENDING_FACTOR));
Dianne Hackborn953fc942016-03-29 15:36:24 -07002113 if (mNextIdlePendingDelay < mConstants.IDLE_PENDING_TIMEOUT) {
2114 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
2115 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002116 mState = STATE_IDLE_MAINTENANCE;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002117 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackbornb6843652016-02-22 12:20:13 -08002118 addEvent(EVENT_DEEP_MAINTENANCE);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002119 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
2120 break;
2121 }
2122 }
2123
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002124 void incActiveIdleOps() {
2125 synchronized (this) {
2126 mActiveIdleOpCount++;
2127 }
2128 }
2129
2130 void decActiveIdleOps() {
2131 synchronized (this) {
2132 mActiveIdleOpCount--;
2133 if (mActiveIdleOpCount <= 0) {
2134 exitMaintenanceEarlyIfNeededLocked();
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002135 mActiveIdleWakeLock.release();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002136 }
2137 }
2138 }
2139
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002140 void setJobsActive(boolean active) {
2141 synchronized (this) {
2142 mJobsActive = active;
Yao Chenca5edbb2016-01-13 14:44:36 -08002143 reportMaintenanceActivityIfNeededLocked();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002144 if (!active) {
2145 exitMaintenanceEarlyIfNeededLocked();
2146 }
2147 }
2148 }
2149
2150 void setAlarmsActive(boolean active) {
2151 synchronized (this) {
2152 mAlarmsActive = active;
2153 if (!active) {
2154 exitMaintenanceEarlyIfNeededLocked();
2155 }
2156 }
2157 }
2158
Yao Chenca5edbb2016-01-13 14:44:36 -08002159 boolean registerMaintenanceActivityListener(IMaintenanceActivityListener listener) {
2160 synchronized (this) {
2161 mMaintenanceActivityListeners.register(listener);
2162 return mReportedMaintenanceActivity;
2163 }
2164 }
2165
2166 void unregisterMaintenanceActivityListener(IMaintenanceActivityListener listener) {
2167 synchronized (this) {
2168 mMaintenanceActivityListeners.unregister(listener);
2169 }
2170 }
2171
2172 void reportMaintenanceActivityIfNeededLocked() {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07002173 boolean active = mJobsActive;
Yao Chenca5edbb2016-01-13 14:44:36 -08002174 if (active == mReportedMaintenanceActivity) {
2175 return;
2176 }
2177 mReportedMaintenanceActivity = active;
2178 Message msg = mHandler.obtainMessage(MSG_REPORT_MAINTENANCE_ACTIVITY,
2179 mReportedMaintenanceActivity ? 1 : 0, 0);
2180 mHandler.sendMessage(msg);
2181 }
2182
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002183 boolean isOpsInactiveLocked() {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07002184 return mActiveIdleOpCount <= 0 && !mJobsActive && !mAlarmsActive;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002185 }
2186
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002187 void exitMaintenanceEarlyIfNeededLocked() {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002188 if (mState == STATE_IDLE_MAINTENANCE || mLightState == LIGHT_STATE_IDLE_MAINTENANCE
2189 || mLightState == LIGHT_STATE_PRE_IDLE) {
2190 if (isOpsInactiveLocked()) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002191 final long now = SystemClock.elapsedRealtime();
2192 if (DEBUG) {
2193 StringBuilder sb = new StringBuilder();
2194 sb.append("Exit: start=");
2195 TimeUtils.formatDuration(mMaintenanceStartTime, sb);
2196 sb.append(" now=");
2197 TimeUtils.formatDuration(now, sb);
2198 Slog.d(TAG, sb.toString());
2199 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002200 if (mState == STATE_IDLE_MAINTENANCE) {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002201 stepIdleStateLocked("s:early");
2202 } else if (mLightState == LIGHT_STATE_PRE_IDLE) {
2203 stepLightIdleStateLocked("s:predone");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002204 } else {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002205 stepLightIdleStateLocked("s:early");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002206 }
2207 }
2208 }
2209 }
2210
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002211 void motionLocked() {
2212 if (DEBUG) Slog.d(TAG, "motionLocked()");
2213 // The motion sensor will have been disabled at this point
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002214 handleMotionDetectedLocked(mConstants.MOTION_INACTIVE_TIMEOUT, "motion");
2215 }
2216
2217 void handleMotionDetectedLocked(long timeout, String type) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002218 // The device is not yet active, so we want to go back to the pending idle
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002219 // state to wait again for no motion. Note that we only monitor for motion
2220 // after moving out of the inactive state, so no need to worry about that.
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002221 boolean becomeInactive = false;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002222 if (mState != STATE_ACTIVE) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002223 scheduleReportActiveLocked(type, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002224 mState = STATE_ACTIVE;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002225 mInactiveTimeout = timeout;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002226 mCurIdleBudget = 0;
2227 mMaintenanceStartTime = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002228 EventLogTags.writeDeviceIdle(mState, type);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002229 addEvent(EVENT_NORMAL);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002230 becomeInactive = true;
2231 }
2232 if (mLightState == LIGHT_STATE_OVERRIDE) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002233 // We went out of light idle mode because we had started deep idle mode... let's
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002234 // now go back and reset things so we resume light idling if appropriate.
2235 mLightState = STATE_ACTIVE;
2236 EventLogTags.writeDeviceIdleLight(mLightState, type);
2237 becomeInactive = true;
2238 }
2239 if (becomeInactive) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002240 becomeInactiveIfAppropriateLocked();
2241 }
2242 }
2243
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002244 void receivedGenericLocationLocked(Location location) {
2245 if (mState != STATE_LOCATING) {
2246 cancelLocatingLocked();
2247 return;
2248 }
2249 if (DEBUG) Slog.d(TAG, "Generic location: " + location);
2250 mLastGenericLocation = new Location(location);
Joe LaPenna23d681b2015-08-27 15:12:11 -07002251 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY && mHasGps) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002252 return;
2253 }
2254 mLocated = true;
2255 if (mNotMoving) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002256 stepIdleStateLocked("s:location");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002257 }
2258 }
2259
2260 void receivedGpsLocationLocked(Location location) {
2261 if (mState != STATE_LOCATING) {
2262 cancelLocatingLocked();
2263 return;
2264 }
2265 if (DEBUG) Slog.d(TAG, "GPS location: " + location);
2266 mLastGpsLocation = new Location(location);
2267 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY) {
2268 return;
2269 }
2270 mLocated = true;
2271 if (mNotMoving) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002272 stepIdleStateLocked("s:gps");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002273 }
2274 }
2275
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002276 void startMonitoringMotionLocked() {
2277 if (DEBUG) Slog.d(TAG, "startMonitoringMotionLocked()");
2278 if (mMotionSensor != null && !mMotionListener.active) {
2279 mMotionListener.registerLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002280 }
2281 }
2282
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002283 void stopMonitoringMotionLocked() {
2284 if (DEBUG) Slog.d(TAG, "stopMonitoringMotionLocked()");
2285 if (mMotionSensor != null && mMotionListener.active) {
2286 mMotionListener.unregisterLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002287 }
2288 }
2289
2290 void cancelAlarmLocked() {
2291 if (mNextAlarmTime != 0) {
2292 mNextAlarmTime = 0;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002293 mAlarmManager.cancel(mDeepAlarmListener);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002294 }
2295 }
2296
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002297 void cancelLightAlarmLocked() {
2298 if (mNextLightAlarmTime != 0) {
2299 mNextLightAlarmTime = 0;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002300 mAlarmManager.cancel(mLightAlarmListener);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002301 }
2302 }
2303
2304 void cancelLocatingLocked() {
2305 if (mLocating) {
2306 mLocationManager.removeUpdates(mGenericLocationListener);
2307 mLocationManager.removeUpdates(mGpsLocationListener);
2308 mLocating = false;
2309 }
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002310 }
2311
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002312 void cancelSensingTimeoutAlarmLocked() {
2313 if (mNextSensingTimeoutAlarmTime != 0) {
2314 mNextSensingTimeoutAlarmTime = 0;
2315 mAlarmManager.cancel(mSensingTimeoutAlarmListener);
2316 }
2317 }
2318
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002319 void scheduleAlarmLocked(long delay, boolean idleUntil) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002320 if (DEBUG) Slog.d(TAG, "scheduleAlarmLocked(" + delay + ", " + idleUntil + ")");
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002321 if (mMotionSensor == null) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07002322 // If there is no motion sensor on this device, then we won't schedule
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002323 // alarms, because we can't determine if the device is not moving. This effectively
Joe LaPenna23d681b2015-08-27 15:12:11 -07002324 // turns off normal execution of device idling, although it is still possible to
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002325 // manually poke it by pretending like the alarm is going off.
2326 return;
2327 }
2328 mNextAlarmTime = SystemClock.elapsedRealtime() + delay;
2329 if (idleUntil) {
2330 mAlarmManager.setIdleUntil(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002331 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002332 } else {
2333 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002334 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002335 }
2336 }
2337
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002338 void scheduleLightAlarmLocked(long delay) {
2339 if (DEBUG) Slog.d(TAG, "scheduleLightAlarmLocked(" + delay + ")");
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002340 mNextLightAlarmTime = SystemClock.elapsedRealtime() + delay;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002341 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002342 mNextLightAlarmTime, "DeviceIdleController.light", mLightAlarmListener, mHandler);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002343 }
2344
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002345 void scheduleSensingTimeoutAlarmLocked(long delay) {
2346 if (DEBUG) Slog.d(TAG, "scheduleSensingAlarmLocked(" + delay + ")");
2347 mNextSensingTimeoutAlarmTime = SystemClock.elapsedRealtime() + delay;
2348 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, mNextSensingTimeoutAlarmTime,
2349 "DeviceIdleController.sensing", mSensingTimeoutAlarmListener, mHandler);
2350 }
2351
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002352 private static int[] buildAppIdArray(ArrayMap<String, Integer> systemApps,
2353 ArrayMap<String, Integer> userApps, SparseBooleanArray outAppIds) {
2354 outAppIds.clear();
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002355 if (systemApps != null) {
2356 for (int i = 0; i < systemApps.size(); i++) {
2357 outAppIds.put(systemApps.valueAt(i), true);
2358 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002359 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002360 if (userApps != null) {
2361 for (int i = 0; i < userApps.size(); i++) {
2362 outAppIds.put(userApps.valueAt(i), true);
2363 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002364 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002365 int size = outAppIds.size();
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002366 int[] appids = new int[size];
2367 for (int i = 0; i < size; i++) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002368 appids[i] = outAppIds.keyAt(i);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002369 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002370 return appids;
2371 }
2372
2373 private void updateWhitelistAppIdsLocked() {
2374 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(mPowerSaveWhitelistAppsExceptIdle,
2375 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistExceptIdleAppIds);
2376 mPowerSaveWhitelistAllAppIdArray = buildAppIdArray(mPowerSaveWhitelistApps,
2377 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistAllAppIds);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002378 mPowerSaveWhitelistUserAppIdArray = buildAppIdArray(null,
2379 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistUserAppIds);
Dianne Hackborn85e35642017-01-12 15:10:57 -08002380 if (mLocalActivityManager != null) {
2381 if (DEBUG) {
2382 Slog.d(TAG, "Setting activity manager whitelist to "
2383 + Arrays.toString(mPowerSaveWhitelistAllAppIdArray));
2384 }
2385 mLocalActivityManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
2386 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002387 if (mLocalPowerManager != null) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002388 if (DEBUG) {
2389 Slog.d(TAG, "Setting wakelock whitelist to "
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002390 + Arrays.toString(mPowerSaveWhitelistAllAppIdArray));
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002391 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002392 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002393 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002394 if (mLocalAlarmManager != null) {
2395 if (DEBUG) {
2396 Slog.d(TAG, "Setting alarm whitelist to "
2397 + Arrays.toString(mPowerSaveWhitelistUserAppIdArray));
2398 }
2399 mLocalAlarmManager.setDeviceIdleUserWhitelist(mPowerSaveWhitelistUserAppIdArray);
2400 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002401 }
2402
Dianne Hackborn85e35642017-01-12 15:10:57 -08002403 private void updateTempWhitelistAppIdsLocked(int appId, boolean adding) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002404 final int size = mTempWhitelistAppIdEndTimes.size();
2405 if (mTempWhitelistAppIdArray.length != size) {
2406 mTempWhitelistAppIdArray = new int[size];
2407 }
2408 for (int i = 0; i < size; i++) {
2409 mTempWhitelistAppIdArray[i] = mTempWhitelistAppIdEndTimes.keyAt(i);
2410 }
Dianne Hackborn85e35642017-01-12 15:10:57 -08002411 if (mLocalActivityManager != null) {
2412 if (DEBUG) {
2413 Slog.d(TAG, "Setting activity manager temp whitelist to "
2414 + Arrays.toString(mTempWhitelistAppIdArray));
2415 }
2416 mLocalActivityManager.updateDeviceIdleTempWhitelist(mTempWhitelistAppIdArray, appId,
2417 adding);
2418 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002419 if (mLocalPowerManager != null) {
2420 if (DEBUG) {
2421 Slog.d(TAG, "Setting wakelock temp whitelist to "
2422 + Arrays.toString(mTempWhitelistAppIdArray));
2423 }
2424 mLocalPowerManager.setDeviceIdleTempWhitelist(mTempWhitelistAppIdArray);
2425 }
2426 }
2427
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002428 private void reportPowerSaveWhitelistChangedLocked() {
2429 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
2430 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Xiaohui Chene4de5a02015-09-22 15:33:31 -07002431 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002432 }
2433
2434 private void reportTempWhitelistChangedLocked() {
2435 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_TEMP_WHITELIST_CHANGED);
2436 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Xiaohui Chene4de5a02015-09-22 15:33:31 -07002437 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002438 }
2439
2440 void readConfigFileLocked() {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002441 if (DEBUG) Slog.d(TAG, "Reading config from " + mConfigFile.getBaseFile());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002442 mPowerSaveWhitelistUserApps.clear();
2443 FileInputStream stream;
2444 try {
2445 stream = mConfigFile.openRead();
2446 } catch (FileNotFoundException e) {
2447 return;
2448 }
2449 try {
2450 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002451 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002452 readConfigFileLocked(parser);
2453 } catch (XmlPullParserException e) {
2454 } finally {
2455 try {
2456 stream.close();
2457 } catch (IOException e) {
2458 }
2459 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002460 }
2461
2462 private void readConfigFileLocked(XmlPullParser parser) {
2463 final PackageManager pm = getContext().getPackageManager();
2464
2465 try {
2466 int type;
2467 while ((type = parser.next()) != XmlPullParser.START_TAG
2468 && type != XmlPullParser.END_DOCUMENT) {
2469 ;
2470 }
2471
2472 if (type != XmlPullParser.START_TAG) {
2473 throw new IllegalStateException("no start tag found");
2474 }
2475
2476 int outerDepth = parser.getDepth();
2477 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2478 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2479 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2480 continue;
2481 }
2482
2483 String tagName = parser.getName();
2484 if (tagName.equals("wl")) {
2485 String name = parser.getAttributeValue(null, "n");
2486 if (name != null) {
2487 try {
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07002488 ApplicationInfo ai = pm.getApplicationInfo(name,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002489 PackageManager.MATCH_ANY_USER);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002490 mPowerSaveWhitelistUserApps.put(ai.packageName,
2491 UserHandle.getAppId(ai.uid));
2492 } catch (PackageManager.NameNotFoundException e) {
2493 }
2494 }
2495 } else {
2496 Slog.w(TAG, "Unknown element under <config>: "
2497 + parser.getName());
2498 XmlUtils.skipCurrentTag(parser);
2499 }
2500 }
2501
2502 } catch (IllegalStateException e) {
2503 Slog.w(TAG, "Failed parsing config " + e);
2504 } catch (NullPointerException e) {
2505 Slog.w(TAG, "Failed parsing config " + e);
2506 } catch (NumberFormatException e) {
2507 Slog.w(TAG, "Failed parsing config " + e);
2508 } catch (XmlPullParserException e) {
2509 Slog.w(TAG, "Failed parsing config " + e);
2510 } catch (IOException e) {
2511 Slog.w(TAG, "Failed parsing config " + e);
2512 } catch (IndexOutOfBoundsException e) {
2513 Slog.w(TAG, "Failed parsing config " + e);
2514 }
2515 }
2516
2517 void writeConfigFileLocked() {
2518 mHandler.removeMessages(MSG_WRITE_CONFIG);
2519 mHandler.sendEmptyMessageDelayed(MSG_WRITE_CONFIG, 5000);
2520 }
2521
2522 void handleWriteConfigFile() {
2523 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
2524
2525 try {
2526 synchronized (this) {
2527 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002528 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002529 writeConfigFileLocked(out);
2530 }
2531 } catch (IOException e) {
2532 }
2533
2534 synchronized (mConfigFile) {
2535 FileOutputStream stream = null;
2536 try {
2537 stream = mConfigFile.startWrite();
2538 memStream.writeTo(stream);
2539 stream.flush();
2540 FileUtils.sync(stream);
2541 stream.close();
2542 mConfigFile.finishWrite(stream);
2543 } catch (IOException e) {
2544 Slog.w(TAG, "Error writing config file", e);
2545 mConfigFile.failWrite(stream);
2546 }
2547 }
2548 }
2549
2550 void writeConfigFileLocked(XmlSerializer out) throws IOException {
2551 out.startDocument(null, true);
2552 out.startTag(null, "config");
2553 for (int i=0; i<mPowerSaveWhitelistUserApps.size(); i++) {
2554 String name = mPowerSaveWhitelistUserApps.keyAt(i);
2555 out.startTag(null, "wl");
2556 out.attribute(null, "n", name);
2557 out.endTag(null, "wl");
2558 }
2559 out.endTag(null, "config");
2560 out.endDocument();
2561 }
2562
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002563 static void dumpHelp(PrintWriter pw) {
2564 pw.println("Device idle controller (deviceidle) commands:");
2565 pw.println(" help");
2566 pw.println(" Print this help text.");
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002567 pw.println(" step [light|deep]");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002568 pw.println(" Immediately step to next state, without waiting for alarm.");
Dianne Hackborn88c41352016-04-07 15:18:58 -07002569 pw.println(" force-idle [light|deep]");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002570 pw.println(" Force directly into idle mode, regardless of other device state.");
Dianne Hackborn88c41352016-04-07 15:18:58 -07002571 pw.println(" force-inactive");
2572 pw.println(" Force to be inactive, ready to freely step idle states.");
2573 pw.println(" unforce");
2574 pw.println(" Resume normal functioning after force-idle or force-inactive.");
2575 pw.println(" get [light|deep|force|screen|charging|network]");
2576 pw.println(" Retrieve the current given state.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002577 pw.println(" disable [light|deep|all]");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002578 pw.println(" Completely disable device idle mode.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002579 pw.println(" enable [light|deep|all]");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002580 pw.println(" Re-enable device idle mode after it had previously been disabled.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002581 pw.println(" enabled [light|deep|all]");
Dianne Hackborn92617032015-06-19 15:32:19 -07002582 pw.println(" Print 1 if device idle mode is currently enabled, else 0.");
Dianne Hackborn1b139682015-07-06 15:13:37 -07002583 pw.println(" whitelist");
2584 pw.println(" Print currently whitelisted apps.");
Dianne Hackborn92617032015-06-19 15:32:19 -07002585 pw.println(" whitelist [package ...]");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002586 pw.println(" Add (prefix with +) or remove (prefix with -) packages.");
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07002587 pw.println(" except-idle-whitelist [package ...|reset]");
2588 pw.println(" Prefix the package with '+' to add it to whitelist or "
2589 + "'=' to check if it is already whitelisted");
2590 pw.println(" [reset] will reset the whitelist to it's original state");
2591 pw.println(" Note that unlike <whitelist> cmd, "
2592 + "changes made using this won't be persisted across boots");
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002593 pw.println(" tempwhitelist");
2594 pw.println(" Print packages that are temporarily whitelisted.");
Dianne Hackborn85e35642017-01-12 15:10:57 -08002595 pw.println(" tempwhitelist [-u USER] [-d DURATION] [package ..]");
2596 pw.println(" Temporarily place packages in whitelist for DURATION milliseconds.");
2597 pw.println(" If no DURATION is specified, 10 seconds is used");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002598 }
2599
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002600 class Shell extends ShellCommand {
2601 int userId = UserHandle.USER_SYSTEM;
2602
2603 @Override
2604 public int onCommand(String cmd) {
2605 return onShellCommand(this, cmd);
2606 }
2607
2608 @Override
2609 public void onHelp() {
2610 PrintWriter pw = getOutPrintWriter();
2611 dumpHelp(pw);
2612 }
2613 }
2614
2615 int onShellCommand(Shell shell, String cmd) {
2616 PrintWriter pw = shell.getOutPrintWriter();
2617 if ("step".equals(cmd)) {
2618 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2619 null);
2620 synchronized (this) {
2621 long token = Binder.clearCallingIdentity();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002622 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002623 try {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002624 if (arg == null || "deep".equals(arg)) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002625 stepIdleStateLocked("s:shell");
2626 pw.print("Stepped to deep: ");
2627 pw.println(stateToString(mState));
2628 } else if ("light".equals(arg)) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002629 stepLightIdleStateLocked("s:shell");
2630 pw.print("Stepped to light: "); pw.println(lightStateToString(mLightState));
2631 } else {
2632 pw.println("Unknown idle mode: " + arg);
2633 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002634 } finally {
2635 Binder.restoreCallingIdentity(token);
2636 }
2637 }
2638 } else if ("force-idle".equals(cmd)) {
2639 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2640 null);
2641 synchronized (this) {
2642 long token = Binder.clearCallingIdentity();
Dianne Hackborn88c41352016-04-07 15:18:58 -07002643 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002644 try {
Dianne Hackborn88c41352016-04-07 15:18:58 -07002645 if (arg == null || "deep".equals(arg)) {
2646 if (!mDeepEnabled) {
2647 pw.println("Unable to go deep idle; not enabled");
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002648 return -1;
2649 }
Dianne Hackborn88c41352016-04-07 15:18:58 -07002650 mForceIdle = true;
2651 becomeInactiveIfAppropriateLocked();
2652 int curState = mState;
2653 while (curState != STATE_IDLE) {
2654 stepIdleStateLocked("s:shell");
2655 if (curState == mState) {
2656 pw.print("Unable to go deep idle; stopped at ");
2657 pw.println(stateToString(mState));
2658 exitForceIdleLocked();
2659 return -1;
2660 }
2661 curState = mState;
2662 }
2663 pw.println("Now forced in to deep idle mode");
2664 } else if ("light".equals(arg)) {
2665 mForceIdle = true;
2666 becomeInactiveIfAppropriateLocked();
2667 int curLightState = mLightState;
2668 while (curLightState != LIGHT_STATE_IDLE) {
2669 stepIdleStateLocked("s:shell");
2670 if (curLightState == mLightState) {
2671 pw.print("Unable to go light idle; stopped at ");
2672 pw.println(lightStateToString(mLightState));
2673 exitForceIdleLocked();
2674 return -1;
2675 }
2676 curLightState = mLightState;
2677 }
2678 pw.println("Now forced in to light idle mode");
2679 } else {
2680 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002681 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002682 } finally {
2683 Binder.restoreCallingIdentity(token);
2684 }
2685 }
Dianne Hackborn88c41352016-04-07 15:18:58 -07002686 } else if ("force-inactive".equals(cmd)) {
2687 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2688 null);
2689 synchronized (this) {
2690 long token = Binder.clearCallingIdentity();
2691 try {
2692 mForceIdle = true;
2693 becomeInactiveIfAppropriateLocked();
2694 pw.print("Light state: ");
2695 pw.print(lightStateToString(mLightState));
2696 pw.print(", deep state: ");
2697 pw.println(stateToString(mState));
2698 } finally {
2699 Binder.restoreCallingIdentity(token);
2700 }
2701 }
2702 } else if ("unforce".equals(cmd)) {
2703 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2704 null);
2705 synchronized (this) {
2706 long token = Binder.clearCallingIdentity();
2707 try {
2708 exitForceIdleLocked();
2709 pw.print("Light state: ");
2710 pw.print(lightStateToString(mLightState));
2711 pw.print(", deep state: ");
2712 pw.println(stateToString(mState));
2713 } finally {
2714 Binder.restoreCallingIdentity(token);
2715 }
2716 }
2717 } else if ("get".equals(cmd)) {
2718 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2719 null);
2720 synchronized (this) {
2721 String arg = shell.getNextArg();
2722 if (arg != null) {
2723 long token = Binder.clearCallingIdentity();
2724 try {
2725 switch (arg) {
2726 case "light": pw.println(lightStateToString(mLightState)); break;
2727 case "deep": pw.println(stateToString(mState)); break;
2728 case "force": pw.println(mForceIdle); break;
2729 case "screen": pw.println(mScreenOn); break;
2730 case "charging": pw.println(mCharging); break;
2731 case "network": pw.println(mNetworkConnected); break;
2732 default: pw.println("Unknown get option: " + arg); break;
2733 }
2734 } finally {
2735 Binder.restoreCallingIdentity(token);
2736 }
2737 } else {
2738 pw.println("Argument required");
2739 }
2740 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002741 } else if ("disable".equals(cmd)) {
2742 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2743 null);
2744 synchronized (this) {
2745 long token = Binder.clearCallingIdentity();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002746 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002747 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002748 boolean becomeActive = false;
2749 boolean valid = false;
2750 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
2751 valid = true;
2752 if (mDeepEnabled) {
2753 mDeepEnabled = false;
2754 becomeActive = true;
2755 pw.println("Deep idle mode disabled");
2756 }
2757 }
2758 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
2759 valid = true;
2760 if (mLightEnabled) {
2761 mLightEnabled = false;
2762 becomeActive = true;
2763 pw.println("Light idle mode disabled");
2764 }
2765 }
2766 if (becomeActive) {
2767 becomeActiveLocked((arg == null ? "all" : arg) + "-disabled",
2768 Process.myUid());
2769 }
2770 if (!valid) {
2771 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002772 }
2773 } finally {
2774 Binder.restoreCallingIdentity(token);
2775 }
2776 }
2777 } else if ("enable".equals(cmd)) {
2778 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2779 null);
2780 synchronized (this) {
2781 long token = Binder.clearCallingIdentity();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002782 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002783 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002784 boolean becomeInactive = false;
2785 boolean valid = false;
2786 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
2787 valid = true;
2788 if (!mDeepEnabled) {
2789 mDeepEnabled = true;
2790 becomeInactive = true;
2791 pw.println("Deep idle mode enabled");
2792 }
2793 }
2794 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
2795 valid = true;
2796 if (!mLightEnabled) {
2797 mLightEnabled = true;
2798 becomeInactive = true;
2799 pw.println("Light idle mode enable");
2800 }
2801 }
2802 if (becomeInactive) {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002803 becomeInactiveIfAppropriateLocked();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002804 }
2805 if (!valid) {
2806 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002807 }
2808 } finally {
2809 Binder.restoreCallingIdentity(token);
2810 }
2811 }
2812 } else if ("enabled".equals(cmd)) {
2813 synchronized (this) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002814 String arg = shell.getNextArg();
2815 if (arg == null || "all".equals(arg)) {
2816 pw.println(mDeepEnabled && mLightEnabled ? "1" : 0);
2817 } else if ("deep".equals(arg)) {
2818 pw.println(mDeepEnabled ? "1" : 0);
2819 } else if ("light".equals(arg)) {
2820 pw.println(mLightEnabled ? "1" : 0);
2821 } else {
2822 pw.println("Unknown idle mode: " + arg);
2823 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002824 }
2825 } else if ("whitelist".equals(cmd)) {
Dianne Hackborneb909e32016-09-29 14:35:15 -07002826 String arg = shell.getNextArg();
2827 if (arg != null) {
2828 getContext().enforceCallingOrSelfPermission(
2829 android.Manifest.permission.DEVICE_POWER, null);
2830 long token = Binder.clearCallingIdentity();
2831 try {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002832 do {
2833 if (arg.length() < 1 || (arg.charAt(0) != '-'
Felipe Lemef8a46232016-02-10 13:51:54 -08002834 && arg.charAt(0) != '+' && arg.charAt(0) != '=')) {
2835 pw.println("Package must be prefixed with +, -, or =: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002836 return -1;
2837 }
2838 char op = arg.charAt(0);
2839 String pkg = arg.substring(1);
2840 if (op == '+') {
2841 if (addPowerSaveWhitelistAppInternal(pkg)) {
2842 pw.println("Added: " + pkg);
2843 } else {
2844 pw.println("Unknown package: " + pkg);
2845 }
Felipe Lemef8a46232016-02-10 13:51:54 -08002846 } else if (op == '-') {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002847 if (removePowerSaveWhitelistAppInternal(pkg)) {
2848 pw.println("Removed: " + pkg);
2849 }
Felipe Lemef8a46232016-02-10 13:51:54 -08002850 } else {
2851 pw.println(getPowerSaveWhitelistAppInternal(pkg));
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002852 }
2853 } while ((arg=shell.getNextArg()) != null);
Dianne Hackborneb909e32016-09-29 14:35:15 -07002854 } finally {
2855 Binder.restoreCallingIdentity(token);
2856 }
2857 } else {
2858 synchronized (this) {
2859 for (int j=0; j<mPowerSaveWhitelistAppsExceptIdle.size(); j++) {
2860 pw.print("system-excidle,");
2861 pw.print(mPowerSaveWhitelistAppsExceptIdle.keyAt(j));
2862 pw.print(",");
2863 pw.println(mPowerSaveWhitelistAppsExceptIdle.valueAt(j));
2864 }
2865 for (int j=0; j<mPowerSaveWhitelistApps.size(); j++) {
2866 pw.print("system,");
2867 pw.print(mPowerSaveWhitelistApps.keyAt(j));
2868 pw.print(",");
2869 pw.println(mPowerSaveWhitelistApps.valueAt(j));
2870 }
2871 for (int j=0; j<mPowerSaveWhitelistUserApps.size(); j++) {
2872 pw.print("user,");
2873 pw.print(mPowerSaveWhitelistUserApps.keyAt(j));
2874 pw.print(",");
2875 pw.println(mPowerSaveWhitelistUserApps.valueAt(j));
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002876 }
2877 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002878 }
2879 } else if ("tempwhitelist".equals(cmd)) {
Dianne Hackborn85e35642017-01-12 15:10:57 -08002880 long duration = 10000;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002881 String opt;
2882 while ((opt=shell.getNextOption()) != null) {
2883 if ("-u".equals(opt)) {
2884 opt = shell.getNextArg();
2885 if (opt == null) {
2886 pw.println("-u requires a user number");
2887 return -1;
2888 }
2889 shell.userId = Integer.parseInt(opt);
Dianne Hackborn85e35642017-01-12 15:10:57 -08002890 } else if ("-d".equals(opt)) {
2891 opt = shell.getNextArg();
2892 if (opt == null) {
2893 pw.println("-d requires a duration");
2894 return -1;
2895 }
2896 duration = Long.parseLong(opt);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002897 }
2898 }
2899 String arg = shell.getNextArg();
2900 if (arg != null) {
2901 try {
Dianne Hackborn85e35642017-01-12 15:10:57 -08002902 addPowerSaveTempWhitelistAppChecked(arg, duration, shell.userId, "shell");
Christopher Tateec3a9f32017-03-21 17:43:47 -07002903 } catch (Exception e) {
2904 pw.println("Failed: " + e);
2905 return -1;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002906 }
2907 } else {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002908 dumpTempWhitelistSchedule(pw, false);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002909 }
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07002910 } else if ("except-idle-whitelist".equals(cmd)) {
2911 getContext().enforceCallingOrSelfPermission(
2912 android.Manifest.permission.DEVICE_POWER, null);
2913 final long token = Binder.clearCallingIdentity();
2914 try {
2915 String arg = shell.getNextArg();
2916 if (arg == null) {
2917 pw.println("No arguments given");
2918 return -1;
2919 } else if ("reset".equals(arg)) {
2920 resetPowerSaveWhitelistExceptIdleInternal();
2921 } else {
2922 do {
2923 if (arg.length() < 1 || (arg.charAt(0) != '-'
2924 && arg.charAt(0) != '+' && arg.charAt(0) != '=')) {
2925 pw.println("Package must be prefixed with +, -, or =: " + arg);
2926 return -1;
2927 }
2928 char op = arg.charAt(0);
2929 String pkg = arg.substring(1);
2930 if (op == '+') {
2931 if (addPowerSaveWhitelistExceptIdleInternal(pkg)) {
2932 pw.println("Added: " + pkg);
2933 } else {
2934 pw.println("Unknown package: " + pkg);
2935 }
2936 } else if (op == '=') {
2937 pw.println(getPowerSaveWhitelistExceptIdleInternal(pkg));
2938 } else {
2939 pw.println("Unknown argument: " + arg);
2940 return -1;
2941 }
2942 } while ((arg = shell.getNextArg()) != null);
2943 }
2944 } finally {
2945 Binder.restoreCallingIdentity(token);
2946 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002947 } else {
2948 return shell.handleDefaultCommands(cmd);
2949 }
2950 return 0;
2951 }
2952
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002953 void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002954 if (!DumpUtils.checkDumpPermission(getContext(), TAG, pw)) return;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002955
2956 if (args != null) {
Xiaohui Chen7c696362015-09-16 09:56:14 -07002957 int userId = UserHandle.USER_SYSTEM;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002958 for (int i=0; i<args.length; i++) {
2959 String arg = args[i];
2960 if ("-h".equals(arg)) {
2961 dumpHelp(pw);
2962 return;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002963 } else if ("-u".equals(arg)) {
2964 i++;
2965 if (i < args.length) {
2966 arg = args[i];
2967 userId = Integer.parseInt(arg);
2968 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002969 } else if ("-a".equals(arg)) {
2970 // Ignore, we always dump all.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002971 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
2972 pw.println("Unknown option: " + arg);
2973 return;
2974 } else {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002975 Shell shell = new Shell();
2976 shell.userId = userId;
2977 String[] newArgs = new String[args.length-i];
2978 System.arraycopy(args, i, newArgs, 0, args.length-i);
Dianne Hackborn354736e2016-08-22 17:00:05 -07002979 shell.exec(mBinderService, null, fd, null, newArgs, null,
2980 new ResultReceiver(null));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002981 return;
2982 }
2983 }
2984 }
2985
2986 synchronized (this) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002987 mConstants.dump(pw);
2988
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002989 if (mEventCmds[0] != EVENT_NULL) {
2990 pw.println(" Idling history:");
2991 long now = SystemClock.elapsedRealtime();
2992 for (int i=EVENT_BUFFER_SIZE-1; i>=0; i--) {
2993 int cmd = mEventCmds[i];
2994 if (cmd == EVENT_NULL) {
2995 continue;
2996 }
2997 String label;
2998 switch (mEventCmds[i]) {
2999 case EVENT_NORMAL: label = " normal"; break;
3000 case EVENT_LIGHT_IDLE: label = " light-idle"; break;
3001 case EVENT_LIGHT_MAINTENANCE: label = "light-maint"; break;
Dianne Hackbornb6843652016-02-22 12:20:13 -08003002 case EVENT_DEEP_IDLE: label = " deep-idle"; break;
3003 case EVENT_DEEP_MAINTENANCE: label = " deep-maint"; break;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08003004 default: label = " ??"; break;
3005 }
3006 pw.print(" ");
3007 pw.print(label);
3008 pw.print(": ");
3009 TimeUtils.formatDuration(mEventTimes[i], now, pw);;
3010 pw.println();
3011 }
3012 }
3013
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003014 int size = mPowerSaveWhitelistAppsExceptIdle.size();
3015 if (size > 0) {
3016 pw.println(" Whitelist (except idle) system apps:");
3017 for (int i = 0; i < size; i++) {
3018 pw.print(" ");
3019 pw.println(mPowerSaveWhitelistAppsExceptIdle.keyAt(i));
3020 }
3021 }
3022 size = mPowerSaveWhitelistApps.size();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003023 if (size > 0) {
3024 pw.println(" Whitelist system apps:");
3025 for (int i = 0; i < size; i++) {
3026 pw.print(" ");
3027 pw.println(mPowerSaveWhitelistApps.keyAt(i));
3028 }
3029 }
3030 size = mPowerSaveWhitelistUserApps.size();
3031 if (size > 0) {
3032 pw.println(" Whitelist user apps:");
3033 for (int i = 0; i < size; i++) {
3034 pw.print(" ");
3035 pw.println(mPowerSaveWhitelistUserApps.keyAt(i));
3036 }
3037 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003038 size = mPowerSaveWhitelistExceptIdleAppIds.size();
3039 if (size > 0) {
3040 pw.println(" Whitelist (except idle) all app ids:");
3041 for (int i = 0; i < size; i++) {
3042 pw.print(" ");
3043 pw.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
3044 pw.println();
3045 }
3046 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08003047 size = mPowerSaveWhitelistUserAppIds.size();
3048 if (size > 0) {
3049 pw.println(" Whitelist user app ids:");
3050 for (int i = 0; i < size; i++) {
3051 pw.print(" ");
3052 pw.print(mPowerSaveWhitelistUserAppIds.keyAt(i));
3053 pw.println();
3054 }
3055 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07003056 size = mPowerSaveWhitelistAllAppIds.size();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003057 if (size > 0) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07003058 pw.println(" Whitelist all app ids:");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003059 for (int i = 0; i < size; i++) {
Dianne Hackborna750a632015-06-16 17:18:23 -07003060 pw.print(" ");
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07003061 pw.print(mPowerSaveWhitelistAllAppIds.keyAt(i));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003062 pw.println();
3063 }
3064 }
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003065 dumpTempWhitelistSchedule(pw, true);
3066
Dianne Hackborna750a632015-06-16 17:18:23 -07003067 size = mTempWhitelistAppIdArray != null ? mTempWhitelistAppIdArray.length : 0;
3068 if (size > 0) {
3069 pw.println(" Temp whitelist app ids:");
3070 for (int i = 0; i < size; i++) {
3071 pw.print(" ");
3072 pw.print(mTempWhitelistAppIdArray[i]);
3073 pw.println();
3074 }
3075 }
Adam Lesinski31c05d12015-06-09 17:34:04 -07003076
Dianne Hackbornb6843652016-02-22 12:20:13 -08003077 pw.print(" mLightEnabled="); pw.print(mLightEnabled);
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003078 pw.print(" mDeepEnabled="); pw.println(mDeepEnabled);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003079 pw.print(" mForceIdle="); pw.println(mForceIdle);
Nick Vaccaro20feaea2015-09-17 17:22:44 -07003080 pw.print(" mMotionSensor="); pw.println(mMotionSensor);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003081 pw.print(" mScreenOn="); pw.println(mScreenOn);
Dianne Hackborn88c41352016-04-07 15:18:58 -07003082 pw.print(" mNetworkConnected="); pw.println(mNetworkConnected);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003083 pw.print(" mCharging="); pw.println(mCharging);
Nick Vaccaro20feaea2015-09-17 17:22:44 -07003084 pw.print(" mMotionActive="); pw.println(mMotionListener.active);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003085 pw.print(" mNotMoving="); pw.println(mNotMoving);
Joe LaPenna23d681b2015-08-27 15:12:11 -07003086 pw.print(" mLocating="); pw.print(mLocating); pw.print(" mHasGps=");
3087 pw.print(mHasGps); pw.print(" mHasNetwork=");
3088 pw.print(mHasNetworkLocation); pw.print(" mLocated="); pw.println(mLocated);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07003089 if (mLastGenericLocation != null) {
3090 pw.print(" mLastGenericLocation="); pw.println(mLastGenericLocation);
3091 }
3092 if (mLastGpsLocation != null) {
3093 pw.print(" mLastGpsLocation="); pw.println(mLastGpsLocation);
3094 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003095 pw.print(" mState="); pw.print(stateToString(mState));
3096 pw.print(" mLightState=");
3097 pw.println(lightStateToString(mLightState));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003098 pw.print(" mInactiveTimeout="); TimeUtils.formatDuration(mInactiveTimeout, pw);
3099 pw.println();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003100 if (mActiveIdleOpCount != 0) {
3101 pw.print(" mActiveIdleOpCount="); pw.println(mActiveIdleOpCount);
3102 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003103 if (mNextAlarmTime != 0) {
3104 pw.print(" mNextAlarmTime=");
3105 TimeUtils.formatDuration(mNextAlarmTime, SystemClock.elapsedRealtime(), pw);
3106 pw.println();
3107 }
3108 if (mNextIdlePendingDelay != 0) {
3109 pw.print(" mNextIdlePendingDelay=");
3110 TimeUtils.formatDuration(mNextIdlePendingDelay, pw);
3111 pw.println();
3112 }
3113 if (mNextIdleDelay != 0) {
3114 pw.print(" mNextIdleDelay=");
3115 TimeUtils.formatDuration(mNextIdleDelay, pw);
3116 pw.println();
3117 }
Dianne Hackborn953fc942016-03-29 15:36:24 -07003118 if (mNextLightIdleDelay != 0) {
3119 pw.print(" mNextIdleDelay=");
3120 TimeUtils.formatDuration(mNextLightIdleDelay, pw);
3121 pw.println();
3122 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003123 if (mNextLightAlarmTime != 0) {
3124 pw.print(" mNextLightAlarmTime=");
3125 TimeUtils.formatDuration(mNextLightAlarmTime, SystemClock.elapsedRealtime(), pw);
3126 pw.println();
3127 }
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08003128 if (mCurIdleBudget != 0) {
3129 pw.print(" mCurIdleBudget=");
3130 TimeUtils.formatDuration(mCurIdleBudget, pw);
3131 pw.println();
3132 }
3133 if (mMaintenanceStartTime != 0) {
3134 pw.print(" mMaintenanceStartTime=");
3135 TimeUtils.formatDuration(mMaintenanceStartTime, SystemClock.elapsedRealtime(), pw);
3136 pw.println();
3137 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003138 if (mJobsActive) {
3139 pw.print(" mJobsActive="); pw.println(mJobsActive);
3140 }
3141 if (mAlarmsActive) {
3142 pw.print(" mAlarmsActive="); pw.println(mAlarmsActive);
3143 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003144 }
3145 }
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003146
3147 void dumpTempWhitelistSchedule(PrintWriter pw, boolean printTitle) {
3148 final int size = mTempWhitelistAppIdEndTimes.size();
3149 if (size > 0) {
3150 String prefix = "";
3151 if (printTitle) {
3152 pw.println(" Temp whitelist schedule:");
3153 prefix = " ";
3154 }
3155 final long timeNow = SystemClock.elapsedRealtime();
3156 for (int i = 0; i < size; i++) {
3157 pw.print(prefix);
3158 pw.print("UID=");
3159 pw.print(mTempWhitelistAppIdEndTimes.keyAt(i));
3160 pw.print(": ");
3161 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.valueAt(i);
3162 TimeUtils.formatDuration(entry.first.value, timeNow, pw);
3163 pw.print(" - ");
3164 pw.println(entry.second);
3165 }
3166 }
3167 }
3168 }