blob: 0921a00b242f52bc16bd200382d60c16292e46f4 [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
Suprabh Shukla08105642017-09-26 14:45:30 -0700310 /**
311 * Apps in the system whitelist that have been taken out (probably because the user wanted to).
312 * They can be restored back by calling restoreAppToSystemWhitelist(String).
313 */
314 private ArrayMap<String, Integer> mRemovedFromSystemWhitelistApps = new ArrayMap<>();
315
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800316 private static final int EVENT_NULL = 0;
317 private static final int EVENT_NORMAL = 1;
318 private static final int EVENT_LIGHT_IDLE = 2;
319 private static final int EVENT_LIGHT_MAINTENANCE = 3;
Dianne Hackbornb6843652016-02-22 12:20:13 -0800320 private static final int EVENT_DEEP_IDLE = 4;
321 private static final int EVENT_DEEP_MAINTENANCE = 5;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800322
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -0700323 private final int[] mEventCmds = new int[EVENT_BUFFER_SIZE];
324 private final long[] mEventTimes = new long[EVENT_BUFFER_SIZE];
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800325
326 private void addEvent(int cmd) {
327 if (mEventCmds[0] != cmd) {
328 System.arraycopy(mEventCmds, 0, mEventCmds, 1, EVENT_BUFFER_SIZE - 1);
329 System.arraycopy(mEventTimes, 0, mEventTimes, 1, EVENT_BUFFER_SIZE - 1);
330 mEventCmds[0] = cmd;
331 mEventTimes[0] = SystemClock.elapsedRealtime();
332 }
333 }
334
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700335 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
336 @Override public void onReceive(Context context, Intent intent) {
Dianne Hackborn88c41352016-04-07 15:18:58 -0700337 switch (intent.getAction()) {
338 case ConnectivityManager.CONNECTIVITY_ACTION: {
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -0700339 updateConnectivityState(intent);
Dianne Hackborn88c41352016-04-07 15:18:58 -0700340 } break;
341 case Intent.ACTION_BATTERY_CHANGED: {
342 synchronized (DeviceIdleController.this) {
343 int plugged = intent.getIntExtra("plugged", 0);
344 updateChargingLocked(plugged != 0);
345 }
346 } break;
347 case Intent.ACTION_PACKAGE_REMOVED: {
348 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
349 Uri data = intent.getData();
350 String ssp;
351 if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
352 removePowerSaveWhitelistAppInternal(ssp);
353 }
354 }
355 } break;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700356 }
357 }
358 };
359
360 private final AlarmManager.OnAlarmListener mLightAlarmListener
361 = new AlarmManager.OnAlarmListener() {
362 @Override
363 public void onAlarm() {
364 synchronized (DeviceIdleController.this) {
365 stepLightIdleStateLocked("s:alarm");
366 }
367 }
368 };
369
Kevin Gabayan92f15e62016-04-04 17:52:22 -0700370 private final AlarmManager.OnAlarmListener mSensingTimeoutAlarmListener
371 = new AlarmManager.OnAlarmListener() {
372 @Override
373 public void onAlarm() {
374 if (mState == STATE_SENSING) {
375 synchronized (DeviceIdleController.this) {
376 becomeInactiveIfAppropriateLocked();
377 }
378 }
379 }
380 };
381
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700382 private final AlarmManager.OnAlarmListener mDeepAlarmListener
383 = new AlarmManager.OnAlarmListener() {
384 @Override
385 public void onAlarm() {
386 synchronized (DeviceIdleController.this) {
387 stepIdleStateLocked("s:alarm");
388 }
389 }
390 };
391
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800392 private final BroadcastReceiver mIdleStartedDoneReceiver = new BroadcastReceiver() {
393 @Override public void onReceive(Context context, Intent intent) {
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700394 // When coming out of a deep idle, we will add in some delay before we allow
395 // the system to settle down and finish the maintenance window. This is
396 // to give a chance for any pending work to be scheduled.
397 if (PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED.equals(intent.getAction())) {
398 mHandler.sendEmptyMessageDelayed(MSG_FINISH_IDLE_OP,
399 mConstants.MIN_DEEP_MAINTENANCE_TIME);
400 } else {
401 mHandler.sendEmptyMessageDelayed(MSG_FINISH_IDLE_OP,
402 mConstants.MIN_LIGHT_MAINTENANCE_TIME);
403 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800404 }
405 };
406
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -0700407 private final BroadcastReceiver mInteractivityReceiver = new BroadcastReceiver() {
408 @Override
409 public void onReceive(Context context, Intent intent) {
Dianne Hackborn9b5ebc92017-09-08 13:45:35 -0700410 synchronized (DeviceIdleController.this) {
411 updateInteractivityLocked();
412 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700413 }
414 };
415
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700416 private final class MotionListener extends TriggerEventListener
417 implements SensorEventListener {
418
419 boolean active = false;
420
421 @Override
422 public void onTrigger(TriggerEvent event) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700423 synchronized (DeviceIdleController.this) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700424 active = false;
425 motionLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700426 }
427 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700428
429 @Override
430 public void onSensorChanged(SensorEvent event) {
431 synchronized (DeviceIdleController.this) {
432 mSensorManager.unregisterListener(this, mMotionSensor);
433 active = false;
434 motionLocked();
435 }
436 }
437
438 @Override
439 public void onAccuracyChanged(Sensor sensor, int accuracy) {}
440
441 public boolean registerLocked() {
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700442 boolean success;
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700443 if (mMotionSensor.getReportingMode() == Sensor.REPORTING_MODE_ONE_SHOT) {
444 success = mSensorManager.requestTriggerSensor(mMotionListener, mMotionSensor);
445 } else {
446 success = mSensorManager.registerListener(
447 mMotionListener, mMotionSensor, SensorManager.SENSOR_DELAY_NORMAL);
448 }
449 if (success) {
450 active = true;
451 } else {
452 Slog.e(TAG, "Unable to register for " + mMotionSensor);
453 }
454 return success;
455 }
456
457 public void unregisterLocked() {
458 if (mMotionSensor.getReportingMode() == Sensor.REPORTING_MODE_ONE_SHOT) {
459 mSensorManager.cancelTriggerSensor(mMotionListener, mMotionSensor);
460 } else {
461 mSensorManager.unregisterListener(mMotionListener);
462 }
463 active = false;
464 }
465 }
466 private final MotionListener mMotionListener = new MotionListener();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700467
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700468 private final LocationListener mGenericLocationListener = new LocationListener() {
469 @Override
470 public void onLocationChanged(Location location) {
471 synchronized (DeviceIdleController.this) {
472 receivedGenericLocationLocked(location);
473 }
474 }
475
476 @Override
477 public void onStatusChanged(String provider, int status, Bundle extras) {
478 }
479
480 @Override
481 public void onProviderEnabled(String provider) {
482 }
483
484 @Override
485 public void onProviderDisabled(String provider) {
486 }
487 };
488
489 private final LocationListener mGpsLocationListener = new LocationListener() {
490 @Override
491 public void onLocationChanged(Location location) {
492 synchronized (DeviceIdleController.this) {
493 receivedGpsLocationLocked(location);
494 }
495 }
496
497 @Override
498 public void onStatusChanged(String provider, int status, Bundle extras) {
499 }
500
501 @Override
502 public void onProviderEnabled(String provider) {
503 }
504
505 @Override
506 public void onProviderDisabled(String provider) {
507 }
508 };
509
Adam Lesinski31c05d12015-06-09 17:34:04 -0700510 /**
511 * All times are in milliseconds. These constants are kept synchronized with the system
512 * global Settings. Any access to this class or its fields should be done while
513 * holding the DeviceIdleController lock.
514 */
Dianne Hackborna750a632015-06-16 17:18:23 -0700515 private final class Constants extends ContentObserver {
Adam Lesinski31c05d12015-06-09 17:34:04 -0700516 // Key names stored in the settings value.
Dianne Hackborn953fc942016-03-29 15:36:24 -0700517 private static final String KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT
518 = "light_after_inactive_to";
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700519 private static final String KEY_LIGHT_PRE_IDLE_TIMEOUT = "light_pre_idle_to";
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700520 private static final String KEY_LIGHT_IDLE_TIMEOUT = "light_idle_to";
Dianne Hackborn953fc942016-03-29 15:36:24 -0700521 private static final String KEY_LIGHT_IDLE_FACTOR = "light_idle_factor";
522 private static final String KEY_LIGHT_MAX_IDLE_TIMEOUT = "light_max_idle_to";
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800523 private static final String KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET
524 = "light_idle_maintenance_min_budget";
525 private static final String KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET
526 = "light_idle_maintenance_max_budget";
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700527 private static final String KEY_MIN_LIGHT_MAINTENANCE_TIME = "min_light_maintenance_time";
528 private static final String KEY_MIN_DEEP_MAINTENANCE_TIME = "min_deep_maintenance_time";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700529 private static final String KEY_INACTIVE_TIMEOUT = "inactive_to";
530 private static final String KEY_SENSING_TIMEOUT = "sensing_to";
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700531 private static final String KEY_LOCATING_TIMEOUT = "locating_to";
532 private static final String KEY_LOCATION_ACCURACY = "location_accuracy";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700533 private static final String KEY_MOTION_INACTIVE_TIMEOUT = "motion_inactive_to";
534 private static final String KEY_IDLE_AFTER_INACTIVE_TIMEOUT = "idle_after_inactive_to";
535 private static final String KEY_IDLE_PENDING_TIMEOUT = "idle_pending_to";
536 private static final String KEY_MAX_IDLE_PENDING_TIMEOUT = "max_idle_pending_to";
537 private static final String KEY_IDLE_PENDING_FACTOR = "idle_pending_factor";
538 private static final String KEY_IDLE_TIMEOUT = "idle_to";
539 private static final String KEY_MAX_IDLE_TIMEOUT = "max_idle_to";
540 private static final String KEY_IDLE_FACTOR = "idle_factor";
541 private static final String KEY_MIN_TIME_TO_ALARM = "min_time_to_alarm";
542 private static final String KEY_MAX_TEMP_APP_WHITELIST_DURATION =
543 "max_temp_app_whitelist_duration";
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700544 private static final String KEY_MMS_TEMP_APP_WHITELIST_DURATION =
545 "mms_temp_app_whitelist_duration";
Dianne Hackborn451c3462015-07-21 17:39:46 -0700546 private static final String KEY_SMS_TEMP_APP_WHITELIST_DURATION =
547 "sms_temp_app_whitelist_duration";
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700548 private static final String KEY_NOTIFICATION_WHITELIST_DURATION =
549 "notification_whitelist_duration";
Adam Lesinski31c05d12015-06-09 17:34:04 -0700550
551 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700552 * This is the time, after becoming inactive, that we go in to the first
553 * light-weight idle mode.
554 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
555 * @see #KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT
556 */
557 public long LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT;
558
559 /**
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700560 * This is amount of time we will wait from the point where we decide we would
561 * like to go idle until we actually do, while waiting for jobs and other current
562 * activity to finish.
563 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
564 * @see #KEY_LIGHT_PRE_IDLE_TIMEOUT
565 */
566 public long LIGHT_PRE_IDLE_TIMEOUT;
567
568 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700569 * This is the initial time that we will run in idle maintenance mode.
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700570 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
571 * @see #KEY_LIGHT_IDLE_TIMEOUT
572 */
573 public long LIGHT_IDLE_TIMEOUT;
574
575 /**
Dianne Hackborn953fc942016-03-29 15:36:24 -0700576 * Scaling factor to apply to the light idle mode time each time we complete a cycle.
577 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
578 * @see #KEY_LIGHT_IDLE_FACTOR
579 */
580 public float LIGHT_IDLE_FACTOR;
581
582 /**
583 * This is the maximum time we will run in idle maintenence mode.
584 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
585 * @see #KEY_LIGHT_MAX_IDLE_TIMEOUT
586 */
587 public long LIGHT_MAX_IDLE_TIMEOUT;
588
589 /**
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800590 * This is the minimum amount of time we want to make available for maintenance mode
591 * when lightly idling. That is, we will always have at least this amount of time
592 * available maintenance before timing out and cutting off maintenance mode.
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700593 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800594 * @see #KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700595 */
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800596 public long LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
597
598 /**
599 * This is the maximum amount of time we want to make available for maintenance mode
600 * when lightly idling. That is, if the system isn't using up its minimum maintenance
601 * budget and this time is being added to the budget reserve, this is the maximum
602 * reserve size we will allow to grow and thus the maximum amount of time we will
603 * allow for the maintenance window.
604 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
605 * @see #KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET
606 */
607 public long LIGHT_IDLE_MAINTENANCE_MAX_BUDGET;
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700608
609 /**
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700610 * This is the minimum amount of time that we will stay in maintenance mode after
611 * a light doze. We have this minimum to allow various things to respond to switching
612 * in to maintenance mode and scheduling their work -- otherwise we may
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700613 * see there is nothing to do (no jobs pending) and go out of maintenance
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700614 * mode immediately.
615 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
616 * @see #KEY_MIN_LIGHT_MAINTENANCE_TIME
617 */
618 public long MIN_LIGHT_MAINTENANCE_TIME;
619
620 /**
621 * This is the minimum amount of time that we will stay in maintenance mode after
622 * a full doze. We have this minimum to allow various things to respond to switching
623 * in to maintenance mode and scheduling their work -- otherwise we may
Dianne Hackborn7ab40252016-06-15 17:30:24 -0700624 * see there is nothing to do (no jobs pending) and go out of maintenance
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700625 * mode immediately.
626 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
627 * @see #KEY_MIN_DEEP_MAINTENANCE_TIME
628 */
629 public long MIN_DEEP_MAINTENANCE_TIME;
630
631 /**
Adam Lesinski31c05d12015-06-09 17:34:04 -0700632 * This is the time, after becoming inactive, at which we start looking at the
633 * motion sensor to determine if the device is being left alone. We don't do this
634 * immediately after going inactive just because we don't want to be continually running
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700635 * the motion sensor whenever the screen is off.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700636 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
637 * @see #KEY_INACTIVE_TIMEOUT
638 */
639 public long INACTIVE_TIMEOUT;
640
641 /**
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700642 * If we don't receive a callback from AnyMotion in this amount of time +
643 * {@link #LOCATING_TIMEOUT}, we will change from
Adam Lesinski31c05d12015-06-09 17:34:04 -0700644 * STATE_SENSING to STATE_INACTIVE, and any AnyMotion callbacks while not in STATE_SENSING
645 * will be ignored.
646 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
647 * @see #KEY_SENSING_TIMEOUT
648 */
649 public long SENSING_TIMEOUT;
650
651 /**
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700652 * This is how long we will wait to try to get a good location fix before going in to
653 * idle mode.
654 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
655 * @see #KEY_LOCATING_TIMEOUT
656 */
657 public long LOCATING_TIMEOUT;
658
659 /**
660 * The desired maximum accuracy (in meters) we consider the location to be good enough to go
661 * on to idle. We will be trying to get an accuracy fix at least this good or until
662 * {@link #LOCATING_TIMEOUT} expires.
663 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
664 * @see #KEY_LOCATION_ACCURACY
665 */
666 public float LOCATION_ACCURACY;
667
668 /**
Adam Lesinski31c05d12015-06-09 17:34:04 -0700669 * This is the time, after seeing motion, that we wait after becoming inactive from
670 * that until we start looking for motion again.
671 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
672 * @see #KEY_MOTION_INACTIVE_TIMEOUT
673 */
674 public long MOTION_INACTIVE_TIMEOUT;
675
676 /**
677 * This is the time, after the inactive timeout elapses, that we will wait looking
Nick Vaccaro20feaea2015-09-17 17:22:44 -0700678 * for motion until we truly consider the device to be idle.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700679 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
680 * @see #KEY_IDLE_AFTER_INACTIVE_TIMEOUT
681 */
682 public long IDLE_AFTER_INACTIVE_TIMEOUT;
683
684 /**
685 * This is the initial time, after being idle, that we will allow ourself to be back
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700686 * in the IDLE_MAINTENANCE state allowing the system to run normally until we return to
687 * idle.
Adam Lesinski31c05d12015-06-09 17:34:04 -0700688 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
689 * @see #KEY_IDLE_PENDING_TIMEOUT
690 */
691 public long IDLE_PENDING_TIMEOUT;
692
693 /**
694 * Maximum pending idle timeout (time spent running) we will be allowed to use.
695 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
696 * @see #KEY_MAX_IDLE_PENDING_TIMEOUT
697 */
698 public long MAX_IDLE_PENDING_TIMEOUT;
699
700 /**
701 * Scaling factor to apply to current pending idle timeout each time we cycle through
702 * that state.
703 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
704 * @see #KEY_IDLE_PENDING_FACTOR
705 */
706 public float IDLE_PENDING_FACTOR;
707
708 /**
709 * This is the initial time that we want to sit in the idle state before waking up
710 * again to return to pending idle and allowing normal work to run.
711 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
712 * @see #KEY_IDLE_TIMEOUT
713 */
714 public long IDLE_TIMEOUT;
715
716 /**
717 * Maximum idle duration we will be allowed to use.
718 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
719 * @see #KEY_MAX_IDLE_TIMEOUT
720 */
721 public long MAX_IDLE_TIMEOUT;
722
723 /**
724 * Scaling factor to apply to current idle timeout each time we cycle through that state.
725 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
726 * @see #KEY_IDLE_FACTOR
727 */
728 public float IDLE_FACTOR;
729
730 /**
731 * This is the minimum time we will allow until the next upcoming alarm for us to
732 * actually go in to idle mode.
733 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
734 * @see #KEY_MIN_TIME_TO_ALARM
735 */
736 public long MIN_TIME_TO_ALARM;
737
738 /**
739 * Max amount of time to temporarily whitelist an app when it receives a high priority
740 * tickle.
741 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
742 * @see #KEY_MAX_TEMP_APP_WHITELIST_DURATION
743 */
744 public long MAX_TEMP_APP_WHITELIST_DURATION;
745
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700746 /**
747 * Amount of time we would like to whitelist an app that is receiving an MMS.
748 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
749 * @see #KEY_MMS_TEMP_APP_WHITELIST_DURATION
750 */
751 public long MMS_TEMP_APP_WHITELIST_DURATION;
752
Dianne Hackborn451c3462015-07-21 17:39:46 -0700753 /**
754 * Amount of time we would like to whitelist an app that is receiving an SMS.
755 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
756 * @see #KEY_SMS_TEMP_APP_WHITELIST_DURATION
757 */
758 public long SMS_TEMP_APP_WHITELIST_DURATION;
759
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700760 /**
761 * Amount of time we would like to whitelist an app that is handling a
762 * {@link android.app.PendingIntent} triggered by a {@link android.app.Notification}.
763 * @see Settings.Global#DEVICE_IDLE_CONSTANTS
764 * @see #KEY_NOTIFICATION_WHITELIST_DURATION
765 */
766 public long NOTIFICATION_WHITELIST_DURATION;
767
Adam Lesinski31c05d12015-06-09 17:34:04 -0700768 private final ContentResolver mResolver;
shreerag597da8a2017-07-21 14:24:14 -0700769 private final boolean mSmallBatteryDevice;
Adam Lesinski31c05d12015-06-09 17:34:04 -0700770 private final KeyValueListParser mParser = new KeyValueListParser(',');
771
772 public Constants(Handler handler, ContentResolver resolver) {
773 super(handler);
774 mResolver = resolver;
shreerag597da8a2017-07-21 14:24:14 -0700775 mSmallBatteryDevice = ActivityManager.isSmallBatteryDevice();
776 mResolver.registerContentObserver(
777 Settings.Global.getUriFor(Settings.Global.DEVICE_IDLE_CONSTANTS),
Joe LaPennaf33b5bf2016-03-23 15:19:47 -0700778 false, this);
Adam Lesinski31c05d12015-06-09 17:34:04 -0700779 updateConstants();
780 }
781
782 @Override
783 public void onChange(boolean selfChange, Uri uri) {
784 updateConstants();
785 }
786
787 private void updateConstants() {
788 synchronized (DeviceIdleController.this) {
789 try {
790 mParser.setString(Settings.Global.getString(mResolver,
shreerag597da8a2017-07-21 14:24:14 -0700791 Settings.Global.DEVICE_IDLE_CONSTANTS));
Adam Lesinski31c05d12015-06-09 17:34:04 -0700792 } catch (IllegalArgumentException e) {
793 // Failed to parse the settings string, log this and move on
794 // with defaults.
795 Slog.e(TAG, "Bad device idle settings", e);
796 }
797
Dianne Hackborn953fc942016-03-29 15:36:24 -0700798 LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT = mParser.getLong(
799 KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT,
800 !COMPRESS_TIME ? 5 * 60 * 1000L : 15 * 1000L);
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700801 LIGHT_PRE_IDLE_TIMEOUT = mParser.getLong(KEY_LIGHT_PRE_IDLE_TIMEOUT,
802 !COMPRESS_TIME ? 10 * 60 * 1000L : 30 * 1000L);
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700803 LIGHT_IDLE_TIMEOUT = mParser.getLong(KEY_LIGHT_IDLE_TIMEOUT,
Dianne Hackborn953fc942016-03-29 15:36:24 -0700804 !COMPRESS_TIME ? 5 * 60 * 1000L : 15 * 1000L);
805 LIGHT_IDLE_FACTOR = mParser.getFloat(KEY_LIGHT_IDLE_FACTOR,
806 2f);
807 LIGHT_MAX_IDLE_TIMEOUT = mParser.getLong(KEY_LIGHT_MAX_IDLE_TIMEOUT,
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700808 !COMPRESS_TIME ? 15 * 60 * 1000L : 60 * 1000L);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800809 LIGHT_IDLE_MAINTENANCE_MIN_BUDGET = mParser.getLong(
810 KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET,
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700811 !COMPRESS_TIME ? 1 * 60 * 1000L : 15 * 1000L);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800812 LIGHT_IDLE_MAINTENANCE_MAX_BUDGET = mParser.getLong(
813 KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET,
814 !COMPRESS_TIME ? 5 * 60 * 1000L : 30 * 1000L);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700815 MIN_LIGHT_MAINTENANCE_TIME = mParser.getLong(
816 KEY_MIN_LIGHT_MAINTENANCE_TIME,
817 !COMPRESS_TIME ? 5 * 1000L : 1 * 1000L);
818 MIN_DEEP_MAINTENANCE_TIME = mParser.getLong(
819 KEY_MIN_DEEP_MAINTENANCE_TIME,
820 !COMPRESS_TIME ? 30 * 1000L : 5 * 1000L);
Michael Kwan88871462017-08-21 13:13:37 -0700821 long inactiveTimeoutDefault = (mSmallBatteryDevice ? 15 : 30) * 60 * 1000L;
Adam Lesinski31c05d12015-06-09 17:34:04 -0700822 INACTIVE_TIMEOUT = mParser.getLong(KEY_INACTIVE_TIMEOUT,
Joe LaPenna0c5d3e92016-03-24 13:29:56 -0700823 !COMPRESS_TIME ? inactiveTimeoutDefault : (inactiveTimeoutDefault / 10));
Adam Lesinski31c05d12015-06-09 17:34:04 -0700824 SENSING_TIMEOUT = mParser.getLong(KEY_SENSING_TIMEOUT,
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700825 !DEBUG ? 4 * 60 * 1000L : 60 * 1000L);
826 LOCATING_TIMEOUT = mParser.getLong(KEY_LOCATING_TIMEOUT,
827 !DEBUG ? 30 * 1000L : 15 * 1000L);
828 LOCATION_ACCURACY = mParser.getFloat(KEY_LOCATION_ACCURACY, 20);
Adam Lesinski31c05d12015-06-09 17:34:04 -0700829 MOTION_INACTIVE_TIMEOUT = mParser.getLong(KEY_MOTION_INACTIVE_TIMEOUT,
830 !COMPRESS_TIME ? 10 * 60 * 1000L : 60 * 1000L);
Michael Kwan88871462017-08-21 13:13:37 -0700831 long idleAfterInactiveTimeout = (mSmallBatteryDevice ? 15 : 30) * 60 * 1000L;
Adam Lesinski31c05d12015-06-09 17:34:04 -0700832 IDLE_AFTER_INACTIVE_TIMEOUT = mParser.getLong(KEY_IDLE_AFTER_INACTIVE_TIMEOUT,
Joe LaPenna0c5d3e92016-03-24 13:29:56 -0700833 !COMPRESS_TIME ? idleAfterInactiveTimeout
834 : (idleAfterInactiveTimeout / 10));
Adam Lesinski31c05d12015-06-09 17:34:04 -0700835 IDLE_PENDING_TIMEOUT = mParser.getLong(KEY_IDLE_PENDING_TIMEOUT,
836 !COMPRESS_TIME ? 5 * 60 * 1000L : 30 * 1000L);
837 MAX_IDLE_PENDING_TIMEOUT = mParser.getLong(KEY_MAX_IDLE_PENDING_TIMEOUT,
838 !COMPRESS_TIME ? 10 * 60 * 1000L : 60 * 1000L);
839 IDLE_PENDING_FACTOR = mParser.getFloat(KEY_IDLE_PENDING_FACTOR,
840 2f);
841 IDLE_TIMEOUT = mParser.getLong(KEY_IDLE_TIMEOUT,
842 !COMPRESS_TIME ? 60 * 60 * 1000L : 6 * 60 * 1000L);
843 MAX_IDLE_TIMEOUT = mParser.getLong(KEY_MAX_IDLE_TIMEOUT,
844 !COMPRESS_TIME ? 6 * 60 * 60 * 1000L : 30 * 60 * 1000L);
845 IDLE_FACTOR = mParser.getFloat(KEY_IDLE_FACTOR,
846 2f);
847 MIN_TIME_TO_ALARM = mParser.getLong(KEY_MIN_TIME_TO_ALARM,
848 !COMPRESS_TIME ? 60 * 60 * 1000L : 6 * 60 * 1000L);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700849 MAX_TEMP_APP_WHITELIST_DURATION = mParser.getLong(
850 KEY_MAX_TEMP_APP_WHITELIST_DURATION, 5 * 60 * 1000L);
851 MMS_TEMP_APP_WHITELIST_DURATION = mParser.getLong(
Dianne Hackborn0b6134b2015-07-14 18:48:07 -0700852 KEY_MMS_TEMP_APP_WHITELIST_DURATION, 60 * 1000L);
Dianne Hackborn451c3462015-07-21 17:39:46 -0700853 SMS_TEMP_APP_WHITELIST_DURATION = mParser.getLong(
854 KEY_SMS_TEMP_APP_WHITELIST_DURATION, 20 * 1000L);
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700855 NOTIFICATION_WHITELIST_DURATION = mParser.getLong(
856 KEY_NOTIFICATION_WHITELIST_DURATION, 30 * 1000L);
Adam Lesinski31c05d12015-06-09 17:34:04 -0700857 }
858 }
859
860 void dump(PrintWriter pw) {
861 pw.println(" Settings:");
862
Dianne Hackborn953fc942016-03-29 15:36:24 -0700863 pw.print(" "); pw.print(KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT); pw.print("=");
864 TimeUtils.formatDuration(LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT, pw);
865 pw.println();
866
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700867 pw.print(" "); pw.print(KEY_LIGHT_PRE_IDLE_TIMEOUT); pw.print("=");
868 TimeUtils.formatDuration(LIGHT_PRE_IDLE_TIMEOUT, pw);
869 pw.println();
870
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700871 pw.print(" "); pw.print(KEY_LIGHT_IDLE_TIMEOUT); pw.print("=");
872 TimeUtils.formatDuration(LIGHT_IDLE_TIMEOUT, pw);
873 pw.println();
874
Dianne Hackborn953fc942016-03-29 15:36:24 -0700875 pw.print(" "); pw.print(KEY_LIGHT_IDLE_FACTOR); pw.print("=");
876 pw.print(LIGHT_IDLE_FACTOR);
877 pw.println();
878
879 pw.print(" "); pw.print(KEY_LIGHT_MAX_IDLE_TIMEOUT); pw.print("=");
880 TimeUtils.formatDuration(LIGHT_MAX_IDLE_TIMEOUT, pw);
881 pw.println();
882
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800883 pw.print(" "); pw.print(KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET); pw.print("=");
884 TimeUtils.formatDuration(LIGHT_IDLE_MAINTENANCE_MIN_BUDGET, pw);
885 pw.println();
886
887 pw.print(" "); pw.print(KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET); pw.print("=");
888 TimeUtils.formatDuration(LIGHT_IDLE_MAINTENANCE_MAX_BUDGET, pw);
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700889 pw.println();
890
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700891 pw.print(" "); pw.print(KEY_MIN_LIGHT_MAINTENANCE_TIME); pw.print("=");
892 TimeUtils.formatDuration(MIN_LIGHT_MAINTENANCE_TIME, pw);
893 pw.println();
894
895 pw.print(" "); pw.print(KEY_MIN_DEEP_MAINTENANCE_TIME); pw.print("=");
896 TimeUtils.formatDuration(MIN_DEEP_MAINTENANCE_TIME, pw);
897 pw.println();
898
Dianne Hackborna750a632015-06-16 17:18:23 -0700899 pw.print(" "); pw.print(KEY_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700900 TimeUtils.formatDuration(INACTIVE_TIMEOUT, pw);
901 pw.println();
902
Dianne Hackborna750a632015-06-16 17:18:23 -0700903 pw.print(" "); pw.print(KEY_SENSING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700904 TimeUtils.formatDuration(SENSING_TIMEOUT, pw);
905 pw.println();
906
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700907 pw.print(" "); pw.print(KEY_LOCATING_TIMEOUT); pw.print("=");
908 TimeUtils.formatDuration(LOCATING_TIMEOUT, pw);
909 pw.println();
910
911 pw.print(" "); pw.print(KEY_LOCATION_ACCURACY); pw.print("=");
912 pw.print(LOCATION_ACCURACY); pw.print("m");
913 pw.println();
914
Dianne Hackborna750a632015-06-16 17:18:23 -0700915 pw.print(" "); pw.print(KEY_MOTION_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700916 TimeUtils.formatDuration(MOTION_INACTIVE_TIMEOUT, pw);
917 pw.println();
918
Dianne Hackborna750a632015-06-16 17:18:23 -0700919 pw.print(" "); pw.print(KEY_IDLE_AFTER_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700920 TimeUtils.formatDuration(IDLE_AFTER_INACTIVE_TIMEOUT, pw);
921 pw.println();
922
Dianne Hackborna750a632015-06-16 17:18:23 -0700923 pw.print(" "); pw.print(KEY_IDLE_PENDING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700924 TimeUtils.formatDuration(IDLE_PENDING_TIMEOUT, pw);
925 pw.println();
926
Dianne Hackborna750a632015-06-16 17:18:23 -0700927 pw.print(" "); pw.print(KEY_MAX_IDLE_PENDING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700928 TimeUtils.formatDuration(MAX_IDLE_PENDING_TIMEOUT, pw);
929 pw.println();
930
Dianne Hackborna750a632015-06-16 17:18:23 -0700931 pw.print(" "); pw.print(KEY_IDLE_PENDING_FACTOR); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700932 pw.println(IDLE_PENDING_FACTOR);
933
Dianne Hackborna750a632015-06-16 17:18:23 -0700934 pw.print(" "); pw.print(KEY_IDLE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700935 TimeUtils.formatDuration(IDLE_TIMEOUT, pw);
936 pw.println();
937
Dianne Hackborna750a632015-06-16 17:18:23 -0700938 pw.print(" "); pw.print(KEY_MAX_IDLE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700939 TimeUtils.formatDuration(MAX_IDLE_TIMEOUT, pw);
940 pw.println();
941
Dianne Hackborna750a632015-06-16 17:18:23 -0700942 pw.print(" "); pw.print(KEY_IDLE_FACTOR); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700943 pw.println(IDLE_FACTOR);
944
Dianne Hackborna750a632015-06-16 17:18:23 -0700945 pw.print(" "); pw.print(KEY_MIN_TIME_TO_ALARM); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700946 TimeUtils.formatDuration(MIN_TIME_TO_ALARM, pw);
947 pw.println();
948
Dianne Hackborna750a632015-06-16 17:18:23 -0700949 pw.print(" "); pw.print(KEY_MAX_TEMP_APP_WHITELIST_DURATION); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700950 TimeUtils.formatDuration(MAX_TEMP_APP_WHITELIST_DURATION, pw);
951 pw.println();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700952
953 pw.print(" "); pw.print(KEY_MMS_TEMP_APP_WHITELIST_DURATION); pw.print("=");
954 TimeUtils.formatDuration(MMS_TEMP_APP_WHITELIST_DURATION, pw);
955 pw.println();
Dianne Hackborn451c3462015-07-21 17:39:46 -0700956
957 pw.print(" "); pw.print(KEY_SMS_TEMP_APP_WHITELIST_DURATION); pw.print("=");
958 TimeUtils.formatDuration(SMS_TEMP_APP_WHITELIST_DURATION, pw);
959 pw.println();
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700960
961 pw.print(" "); pw.print(KEY_NOTIFICATION_WHITELIST_DURATION); pw.print("=");
962 TimeUtils.formatDuration(NOTIFICATION_WHITELIST_DURATION, pw);
963 pw.println();
Adam Lesinski31c05d12015-06-09 17:34:04 -0700964 }
965 }
966
967 private Constants mConstants;
968
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700969 @Override
970 public void onAnyMotionResult(int result) {
971 if (DEBUG) Slog.d(TAG, "onAnyMotionResult(" + result + ")");
Kevin Gabayan92f15e62016-04-04 17:52:22 -0700972 if (result != AnyMotionDetector.RESULT_UNKNOWN) {
973 synchronized (this) {
974 cancelSensingTimeoutAlarmLocked();
975 }
976 }
Kevin Gabayandcf47012016-07-08 10:41:24 -0700977 if ((result == AnyMotionDetector.RESULT_MOVED) ||
978 (result == AnyMotionDetector.RESULT_UNKNOWN)) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700979 synchronized (this) {
Kevin Gabayandcf47012016-07-08 10:41:24 -0700980 handleMotionDetectedLocked(mConstants.INACTIVE_TIMEOUT, "non_stationary");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700981 }
982 } else if (result == AnyMotionDetector.RESULT_STATIONARY) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700983 if (mState == STATE_SENSING) {
984 // If we are currently sensing, it is time to move to locating.
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700985 synchronized (this) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700986 mNotMoving = true;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800987 stepIdleStateLocked("s:stationary");
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700988 }
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700989 } else if (mState == STATE_LOCATING) {
990 // If we are currently locating, note that we are not moving and step
991 // if we have located the position.
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700992 synchronized (this) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700993 mNotMoving = true;
994 if (mLocated) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800995 stepIdleStateLocked("s:stationary");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700996 }
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700997 }
998 }
999 }
1000 }
1001
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001002 private static final int MSG_WRITE_CONFIG = 1;
1003 private static final int MSG_REPORT_IDLE_ON = 2;
1004 private static final int MSG_REPORT_IDLE_ON_LIGHT = 3;
1005 private static final int MSG_REPORT_IDLE_OFF = 4;
1006 private static final int MSG_REPORT_ACTIVE = 5;
1007 private static final int MSG_TEMP_APP_WHITELIST_TIMEOUT = 6;
1008 private static final int MSG_REPORT_MAINTENANCE_ACTIVITY = 7;
1009 private static final int MSG_FINISH_IDLE_OP = 8;
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001010 private static final int MSG_REPORT_TEMP_APP_WHITELIST_CHANGED = 9;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001011
1012 final class MyHandler extends Handler {
1013 MyHandler(Looper looper) {
1014 super(looper);
1015 }
1016
1017 @Override public void handleMessage(Message msg) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001018 if (DEBUG) Slog.d(TAG, "handleMessage(" + msg.what + ")");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001019 switch (msg.what) {
1020 case MSG_WRITE_CONFIG: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001021 // Does not hold a wakelock. Just let this happen whenever.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001022 handleWriteConfigFile();
1023 } break;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001024 case MSG_REPORT_IDLE_ON:
1025 case MSG_REPORT_IDLE_ON_LIGHT: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001026 // mGoingIdleWakeLock is held at this point
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001027 EventLogTags.writeDeviceIdleOnStart();
Dianne Hackbornb6843652016-02-22 12:20:13 -08001028 final boolean deepChanged;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001029 final boolean lightChanged;
1030 if (msg.what == MSG_REPORT_IDLE_ON) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001031 deepChanged = mLocalPowerManager.setDeviceIdleMode(true);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001032 lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
1033 } else {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001034 deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001035 lightChanged = mLocalPowerManager.setLightDeviceIdleMode(true);
1036 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001037 try {
1038 mNetworkPolicyManager.setDeviceIdleMode(true);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001039 mBatteryStats.noteDeviceIdleMode(msg.what == MSG_REPORT_IDLE_ON
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07001040 ? BatteryStats.DEVICE_IDLE_MODE_DEEP
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001041 : BatteryStats.DEVICE_IDLE_MODE_LIGHT, null, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001042 } catch (RemoteException e) {
1043 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001044 if (deepChanged) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001045 getContext().sendBroadcastAsUser(mIdleIntent, UserHandle.ALL);
1046 }
1047 if (lightChanged) {
1048 getContext().sendBroadcastAsUser(mLightIdleIntent, UserHandle.ALL);
1049 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001050 EventLogTags.writeDeviceIdleOnComplete();
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001051 mGoingIdleWakeLock.release();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001052 } break;
1053 case MSG_REPORT_IDLE_OFF: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001054 // mActiveIdleWakeLock is held at this point
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001055 EventLogTags.writeDeviceIdleOffStart("unknown");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001056 final boolean deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001057 final boolean lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001058 try {
1059 mNetworkPolicyManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001060 mBatteryStats.noteDeviceIdleMode(BatteryStats.DEVICE_IDLE_MODE_OFF,
1061 null, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001062 } catch (RemoteException e) {
1063 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001064 if (deepChanged) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001065 incActiveIdleOps();
1066 getContext().sendOrderedBroadcastAsUser(mIdleIntent, UserHandle.ALL,
1067 null, mIdleStartedDoneReceiver, null, 0, null, null);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001068 }
1069 if (lightChanged) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001070 incActiveIdleOps();
1071 getContext().sendOrderedBroadcastAsUser(mLightIdleIntent, UserHandle.ALL,
1072 null, mIdleStartedDoneReceiver, null, 0, null, null);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001073 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001074 // Always start with one active op for the message being sent here.
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001075 // Now we are done!
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001076 decActiveIdleOps();
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001077 EventLogTags.writeDeviceIdleOffComplete();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001078 } break;
1079 case MSG_REPORT_ACTIVE: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001080 // The device is awake at this point, so no wakelock necessary.
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001081 String activeReason = (String)msg.obj;
1082 int activeUid = msg.arg1;
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001083 EventLogTags.writeDeviceIdleOffStart(
1084 activeReason != null ? activeReason : "unknown");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001085 final boolean deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001086 final boolean lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001087 try {
1088 mNetworkPolicyManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001089 mBatteryStats.noteDeviceIdleMode(BatteryStats.DEVICE_IDLE_MODE_OFF,
1090 activeReason, activeUid);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001091 } catch (RemoteException e) {
1092 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001093 if (deepChanged) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001094 getContext().sendBroadcastAsUser(mIdleIntent, UserHandle.ALL);
1095 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001096 if (lightChanged) {
1097 getContext().sendBroadcastAsUser(mLightIdleIntent, UserHandle.ALL);
1098 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001099 EventLogTags.writeDeviceIdleOffComplete();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001100 } break;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001101 case MSG_TEMP_APP_WHITELIST_TIMEOUT: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001102 // TODO: What is keeping the device awake at this point? Does it need to be?
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001103 int uid = msg.arg1;
1104 checkTempAppWhitelistTimeout(uid);
1105 } break;
Yao Chenca5edbb2016-01-13 14:44:36 -08001106 case MSG_REPORT_MAINTENANCE_ACTIVITY: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001107 // TODO: What is keeping the device awake at this point? Does it need to be?
Yao Chenca5edbb2016-01-13 14:44:36 -08001108 boolean active = (msg.arg1 == 1);
1109 final int size = mMaintenanceActivityListeners.beginBroadcast();
1110 try {
1111 for (int i = 0; i < size; i++) {
1112 try {
1113 mMaintenanceActivityListeners.getBroadcastItem(i)
1114 .onMaintenanceActivityChanged(active);
1115 } catch (RemoteException ignored) {
1116 }
1117 }
1118 } finally {
1119 mMaintenanceActivityListeners.finishBroadcast();
1120 }
1121 } break;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001122 case MSG_FINISH_IDLE_OP: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001123 // mActiveIdleWakeLock is held at this point
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001124 decActiveIdleOps();
1125 } break;
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001126 case MSG_REPORT_TEMP_APP_WHITELIST_CHANGED: {
1127 final int appId = msg.arg1;
1128 final boolean added = (msg.arg2 == 1);
1129 mNetworkPolicyManagerInternal.onTempPowerSaveWhitelistChange(appId, added);
1130 } break;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001131 }
1132 }
1133 }
1134
1135 final MyHandler mHandler;
1136
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001137 BinderService mBinderService;
1138
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001139 private final class BinderService extends IDeviceIdleController.Stub {
1140 @Override public void addPowerSaveWhitelistApp(String name) {
Eugene Susla6a7006a2017-03-13 12:57:58 -07001141 if (DEBUG) {
1142 Slog.i(TAG, "addPowerSaveWhitelistApp(name = " + name + ")");
1143 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001144 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1145 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001146 long ident = Binder.clearCallingIdentity();
1147 try {
1148 addPowerSaveWhitelistAppInternal(name);
1149 } finally {
1150 Binder.restoreCallingIdentity(ident);
1151 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001152 }
1153
1154 @Override public void removePowerSaveWhitelistApp(String name) {
Eugene Susla6a7006a2017-03-13 12:57:58 -07001155 if (DEBUG) {
1156 Slog.i(TAG, "removePowerSaveWhitelistApp(name = " + name + ")");
1157 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001158 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1159 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001160 long ident = Binder.clearCallingIdentity();
1161 try {
1162 removePowerSaveWhitelistAppInternal(name);
1163 } finally {
1164 Binder.restoreCallingIdentity(ident);
1165 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001166 }
1167
Suprabh Shukla08105642017-09-26 14:45:30 -07001168 @Override public void removeSystemPowerWhitelistApp(String name) {
1169 if (DEBUG) {
1170 Slog.d(TAG, "removeAppFromSystemWhitelist(name = " + name + ")");
1171 }
1172 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1173 null);
1174 long ident = Binder.clearCallingIdentity();
1175 try {
1176 removeSystemPowerWhitelistAppInternal(name);
1177 } finally {
1178 Binder.restoreCallingIdentity(ident);
1179 }
1180 }
1181
1182 @Override public void restoreSystemPowerWhitelistApp(String name) {
1183 if (DEBUG) {
1184 Slog.d(TAG, "restoreAppToSystemWhitelist(name = " + name + ")");
1185 }
1186 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1187 null);
1188 long ident = Binder.clearCallingIdentity();
1189 try {
1190 restoreSystemPowerWhitelistAppInternal(name);
1191 } finally {
1192 Binder.restoreCallingIdentity(ident);
1193 }
1194 }
1195
1196 public String[] getRemovedSystemPowerWhitelistApps() {
1197 return getRemovedSystemPowerWhitelistAppsInternal();
1198 }
1199
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001200 @Override public String[] getSystemPowerWhitelistExceptIdle() {
1201 return getSystemPowerWhitelistExceptIdleInternal();
1202 }
1203
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001204 @Override public String[] getSystemPowerWhitelist() {
1205 return getSystemPowerWhitelistInternal();
1206 }
1207
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001208 @Override public String[] getUserPowerWhitelist() {
1209 return getUserPowerWhitelistInternal();
1210 }
1211
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001212 @Override public String[] getFullPowerWhitelistExceptIdle() {
1213 return getFullPowerWhitelistExceptIdleInternal();
1214 }
1215
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001216 @Override public String[] getFullPowerWhitelist() {
1217 return getFullPowerWhitelistInternal();
1218 }
1219
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001220 @Override public int[] getAppIdWhitelistExceptIdle() {
1221 return getAppIdWhitelistExceptIdleInternal();
1222 }
1223
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001224 @Override public int[] getAppIdWhitelist() {
1225 return getAppIdWhitelistInternal();
1226 }
1227
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001228 @Override public int[] getAppIdUserWhitelist() {
1229 return getAppIdUserWhitelistInternal();
1230 }
1231
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001232 @Override public int[] getAppIdTempWhitelist() {
1233 return getAppIdTempWhitelistInternal();
1234 }
1235
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001236 @Override public boolean isPowerSaveWhitelistExceptIdleApp(String name) {
1237 return isPowerSaveWhitelistExceptIdleAppInternal(name);
1238 }
1239
Amith Yamasani06bf8242015-05-08 16:36:21 -07001240 @Override public boolean isPowerSaveWhitelistApp(String name) {
1241 return isPowerSaveWhitelistAppInternal(name);
1242 }
1243
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001244 @Override public void addPowerSaveTempWhitelistApp(String packageName, long duration,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001245 int userId, String reason) throws RemoteException {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001246 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001247 }
1248
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001249 @Override public long addPowerSaveTempWhitelistAppForMms(String packageName,
1250 int userId, String reason) throws RemoteException {
1251 long duration = mConstants.MMS_TEMP_APP_WHITELIST_DURATION;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001252 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001253 return duration;
1254 }
1255
Dianne Hackborn451c3462015-07-21 17:39:46 -07001256 @Override public long addPowerSaveTempWhitelistAppForSms(String packageName,
1257 int userId, String reason) throws RemoteException {
1258 long duration = mConstants.SMS_TEMP_APP_WHITELIST_DURATION;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001259 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Dianne Hackborn451c3462015-07-21 17:39:46 -07001260 return duration;
1261 }
1262
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001263 @Override public void exitIdle(String reason) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001264 getContext().enforceCallingOrSelfPermission(Manifest.permission.DEVICE_POWER,
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001265 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001266 long ident = Binder.clearCallingIdentity();
1267 try {
1268 exitIdleInternal(reason);
1269 } finally {
1270 Binder.restoreCallingIdentity(ident);
1271 }
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001272 }
1273
Yao Chenca5edbb2016-01-13 14:44:36 -08001274 @Override public boolean registerMaintenanceActivityListener(
1275 IMaintenanceActivityListener listener) {
1276 return DeviceIdleController.this.registerMaintenanceActivityListener(listener);
1277 }
1278
1279 @Override public void unregisterMaintenanceActivityListener(
1280 IMaintenanceActivityListener listener) {
1281 DeviceIdleController.this.unregisterMaintenanceActivityListener(listener);
1282 }
1283
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001284 @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1285 DeviceIdleController.this.dump(fd, pw, args);
1286 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001287
1288 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07001289 FileDescriptor err, String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
1290 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001291 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001292 }
1293
Felipe Lemeef134662016-08-10 14:46:39 -07001294 public class LocalService {
Christopher Tatee0be7e82017-02-08 17:38:20 -08001295 // duration in milliseconds
1296 public void addPowerSaveTempWhitelistApp(int callingUid, String packageName,
1297 long duration, int userId, boolean sync, String reason) {
1298 addPowerSaveTempWhitelistAppInternal(callingUid, packageName, duration,
1299 userId, sync, reason);
1300 }
1301
1302 // duration in milliseconds
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001303 public void addPowerSaveTempWhitelistAppDirect(int appId, long duration, boolean sync,
1304 String reason) {
1305 addPowerSaveTempWhitelistAppDirectInternal(0, appId, duration, sync, reason);
1306 }
1307
Christopher Tatee0be7e82017-02-08 17:38:20 -08001308 // duration in milliseconds
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001309 public long getNotificationWhitelistDuration() {
1310 return mConstants.NOTIFICATION_WHITELIST_DURATION;
1311 }
1312
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001313 public void setJobsActive(boolean active) {
1314 DeviceIdleController.this.setJobsActive(active);
1315 }
1316
1317 // Up-call from alarm manager.
1318 public void setAlarmsActive(boolean active) {
1319 DeviceIdleController.this.setAlarmsActive(active);
1320 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001321
Christopher Tate42a386b2016-11-07 12:21:21 -08001322 /** Is the app on any of the power save whitelists, whether system or user? */
1323 public boolean isAppOnWhitelist(int appid) {
1324 return DeviceIdleController.this.isAppOnWhitelistInternal(appid);
1325 }
1326
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001327 /**
1328 * Returns the array of app ids whitelisted by user. Take care not to
1329 * modify this, as it is a reference to the original copy. But the reference
1330 * can change when the list changes, so it needs to be re-acquired when
1331 * {@link PowerManager#ACTION_POWER_SAVE_WHITELIST_CHANGED} is sent.
1332 */
1333 public int[] getPowerSaveWhitelistUserAppIds() {
1334 return DeviceIdleController.this.getPowerSaveWhitelistUserAppIds();
1335 }
Suprabh Shuklaa78acfd2017-10-13 19:29:36 -07001336
1337 public int[] getPowerSaveTempWhitelistAppIds() {
1338 return DeviceIdleController.this.getAppIdTempWhitelistInternal();
1339 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001340 }
1341
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001342 public DeviceIdleController(Context context) {
1343 super(context);
1344 mConfigFile = new AtomicFile(new File(getSystemDir(), "deviceidle.xml"));
1345 mHandler = new MyHandler(BackgroundThread.getHandler().getLooper());
1346 }
1347
Christopher Tate42a386b2016-11-07 12:21:21 -08001348 boolean isAppOnWhitelistInternal(int appid) {
1349 synchronized (this) {
1350 return Arrays.binarySearch(mPowerSaveWhitelistAllAppIdArray, appid) >= 0;
1351 }
1352 }
1353
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001354 int[] getPowerSaveWhitelistUserAppIds() {
1355 synchronized (this) {
1356 return mPowerSaveWhitelistUserAppIdArray;
1357 }
1358 }
1359
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001360 private static File getSystemDir() {
1361 return new File(Environment.getDataDirectory(), "system");
1362 }
1363
1364 @Override
1365 public void onStart() {
1366 final PackageManager pm = getContext().getPackageManager();
1367
1368 synchronized (this) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001369 mLightEnabled = mDeepEnabled = getContext().getResources().getBoolean(
Dianne Hackborn92617032015-06-19 15:32:19 -07001370 com.android.internal.R.bool.config_enableAutoPowerModes);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001371 SystemConfig sysConfig = SystemConfig.getInstance();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001372 ArraySet<String> allowPowerExceptIdle = sysConfig.getAllowInPowerSaveExceptIdle();
1373 for (int i=0; i<allowPowerExceptIdle.size(); i++) {
1374 String pkg = allowPowerExceptIdle.valueAt(i);
1375 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001376 ApplicationInfo ai = pm.getApplicationInfo(pkg,
1377 PackageManager.MATCH_SYSTEM_ONLY);
1378 int appid = UserHandle.getAppId(ai.uid);
1379 mPowerSaveWhitelistAppsExceptIdle.put(ai.packageName, appid);
1380 mPowerSaveWhitelistSystemAppIdsExceptIdle.put(appid, true);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001381 } catch (PackageManager.NameNotFoundException e) {
1382 }
1383 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001384 ArraySet<String> allowPower = sysConfig.getAllowInPowerSave();
1385 for (int i=0; i<allowPower.size(); i++) {
1386 String pkg = allowPower.valueAt(i);
1387 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001388 ApplicationInfo ai = pm.getApplicationInfo(pkg,
1389 PackageManager.MATCH_SYSTEM_ONLY);
1390 int appid = UserHandle.getAppId(ai.uid);
1391 // These apps are on both the whitelist-except-idle as well
1392 // as the full whitelist, so they apply in all cases.
1393 mPowerSaveWhitelistAppsExceptIdle.put(ai.packageName, appid);
1394 mPowerSaveWhitelistSystemAppIdsExceptIdle.put(appid, true);
1395 mPowerSaveWhitelistApps.put(ai.packageName, appid);
1396 mPowerSaveWhitelistSystemAppIds.put(appid, true);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001397 } catch (PackageManager.NameNotFoundException e) {
1398 }
1399 }
1400
Adam Lesinski31c05d12015-06-09 17:34:04 -07001401 mConstants = new Constants(mHandler, getContext().getContentResolver());
1402
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001403 readConfigFileLocked();
1404 updateWhitelistAppIdsLocked();
1405
Dianne Hackborn88c41352016-04-07 15:18:58 -07001406 mNetworkConnected = true;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001407 mScreenOn = true;
1408 // Start out assuming we are charging. If we aren't, we will at least get
1409 // a battery update the next time the level drops.
1410 mCharging = true;
1411 mState = STATE_ACTIVE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001412 mLightState = LIGHT_STATE_ACTIVE;
Adam Lesinski31c05d12015-06-09 17:34:04 -07001413 mInactiveTimeout = mConstants.INACTIVE_TIMEOUT;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001414 }
1415
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001416 mBinderService = new BinderService();
1417 publishBinderService(Context.DEVICE_IDLE_CONTROLLER, mBinderService);
Dianne Hackborna750a632015-06-16 17:18:23 -07001418 publishLocalService(LocalService.class, new LocalService());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001419 }
1420
1421 @Override
1422 public void onBootPhase(int phase) {
1423 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1424 synchronized (this) {
1425 mAlarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
1426 mBatteryStats = BatteryStatsService.getService();
Dianne Hackborn85e35642017-01-12 15:10:57 -08001427 mLocalActivityManager = getLocalService(ActivityManagerInternal.class);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001428 mLocalPowerManager = getLocalService(PowerManagerInternal.class);
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001429 mPowerManager = getContext().getSystemService(PowerManager.class);
1430 mActiveIdleWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
1431 "deviceidle_maint");
1432 mActiveIdleWakeLock.setReferenceCounted(false);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001433 mGoingIdleWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
1434 "deviceidle_going_idle");
1435 mGoingIdleWakeLock.setReferenceCounted(true);
Dianne Hackborn88c41352016-04-07 15:18:58 -07001436 mConnectivityService = (ConnectivityService)ServiceManager.getService(
1437 Context.CONNECTIVITY_SERVICE);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001438 mLocalAlarmManager = getLocalService(AlarmManagerService.LocalService.class);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001439 mNetworkPolicyManager = INetworkPolicyManager.Stub.asInterface(
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001440 ServiceManager.getService(Context.NETWORK_POLICY_SERVICE));
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001441 mNetworkPolicyManagerInternal = getLocalService(NetworkPolicyManagerInternal.class);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001442 mSensorManager = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001443 int sigMotionSensorId = getContext().getResources().getInteger(
1444 com.android.internal.R.integer.config_autoPowerModeAnyMotionSensor);
1445 if (sigMotionSensorId > 0) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001446 mMotionSensor = mSensorManager.getDefaultSensor(sigMotionSensorId, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001447 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001448 if (mMotionSensor == null && getContext().getResources().getBoolean(
Joe LaPenna23d681b2015-08-27 15:12:11 -07001449 com.android.internal.R.bool.config_autoPowerModePreferWristTilt)) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001450 mMotionSensor = mSensorManager.getDefaultSensor(
1451 Sensor.TYPE_WRIST_TILT_GESTURE, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001452 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001453 if (mMotionSensor == null) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07001454 // As a last ditch, fall back to SMD.
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001455 mMotionSensor = mSensorManager.getDefaultSensor(
1456 Sensor.TYPE_SIGNIFICANT_MOTION, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001457 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001458
Joe LaPenna23d681b2015-08-27 15:12:11 -07001459 if (getContext().getResources().getBoolean(
1460 com.android.internal.R.bool.config_autoPowerModePrefetchLocation)) {
1461 mLocationManager = (LocationManager) getContext().getSystemService(
1462 Context.LOCATION_SERVICE);
1463 mLocationRequest = new LocationRequest()
1464 .setQuality(LocationRequest.ACCURACY_FINE)
1465 .setInterval(0)
1466 .setFastestInterval(0)
1467 .setNumUpdates(1);
1468 }
1469
1470 float angleThreshold = getContext().getResources().getInteger(
1471 com.android.internal.R.integer.config_autoPowerModeThresholdAngle) / 100f;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001472 mAnyMotionDetector = new AnyMotionDetector(
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001473 (PowerManager) getContext().getSystemService(Context.POWER_SERVICE),
Joe LaPenna23d681b2015-08-27 15:12:11 -07001474 mHandler, mSensorManager, this, angleThreshold);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001475
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001476 mIdleIntent = new Intent(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001477 mIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1478 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001479 mLightIdleIntent = new Intent(PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED);
1480 mLightIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1481 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001482
1483 IntentFilter filter = new IntentFilter();
1484 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001485 getContext().registerReceiver(mReceiver, filter);
Amith Yamasaniac59f75e2016-05-05 12:38:17 -07001486
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001487 filter = new IntentFilter();
1488 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1489 filter.addDataScheme("package");
Amith Yamasaniac59f75e2016-05-05 12:38:17 -07001490 getContext().registerReceiver(mReceiver, filter);
1491
Dianne Hackborn88c41352016-04-07 15:18:58 -07001492 filter = new IntentFilter();
1493 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001494 getContext().registerReceiver(mReceiver, filter);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001495
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -07001496 filter = new IntentFilter();
1497 filter.addAction(Intent.ACTION_SCREEN_OFF);
1498 filter.addAction(Intent.ACTION_SCREEN_ON);
1499 getContext().registerReceiver(mInteractivityReceiver, filter);
1500
Dianne Hackborn85e35642017-01-12 15:10:57 -08001501 mLocalActivityManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001502 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001503 mLocalAlarmManager.setDeviceIdleUserWhitelist(mPowerSaveWhitelistUserAppIdArray);
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -07001504
1505 updateInteractivityLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001506 }
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -07001507 updateConnectivityState(null);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001508 }
1509 }
1510
1511 public boolean addPowerSaveWhitelistAppInternal(String name) {
1512 synchronized (this) {
1513 try {
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001514 ApplicationInfo ai = getContext().getPackageManager().getApplicationInfo(name,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07001515 PackageManager.MATCH_ANY_USER);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001516 if (mPowerSaveWhitelistUserApps.put(name, UserHandle.getAppId(ai.uid)) == null) {
1517 reportPowerSaveWhitelistChangedLocked();
1518 updateWhitelistAppIdsLocked();
1519 writeConfigFileLocked();
1520 }
1521 return true;
1522 } catch (PackageManager.NameNotFoundException e) {
1523 return false;
1524 }
1525 }
1526 }
1527
1528 public boolean removePowerSaveWhitelistAppInternal(String name) {
1529 synchronized (this) {
1530 if (mPowerSaveWhitelistUserApps.remove(name) != null) {
1531 reportPowerSaveWhitelistChangedLocked();
1532 updateWhitelistAppIdsLocked();
1533 writeConfigFileLocked();
1534 return true;
1535 }
1536 }
1537 return false;
1538 }
1539
Felipe Lemef8a46232016-02-10 13:51:54 -08001540 public boolean getPowerSaveWhitelistAppInternal(String name) {
1541 synchronized (this) {
1542 return mPowerSaveWhitelistUserApps.containsKey(name);
1543 }
1544 }
1545
Suprabh Shukla08105642017-09-26 14:45:30 -07001546 void resetSystemPowerWhitelistInternal() {
1547 synchronized (this) {
1548 mPowerSaveWhitelistApps.putAll(mRemovedFromSystemWhitelistApps);
1549 mRemovedFromSystemWhitelistApps.clear();
1550 reportPowerSaveWhitelistChangedLocked();
1551 updateWhitelistAppIdsLocked();
1552 writeConfigFileLocked();
1553 }
1554 }
1555
1556 public boolean restoreSystemPowerWhitelistAppInternal(String name) {
1557 synchronized (this) {
1558 if (!mRemovedFromSystemWhitelistApps.containsKey(name)) {
1559 return false;
1560 }
1561 mPowerSaveWhitelistApps.put(name, mRemovedFromSystemWhitelistApps.remove(name));
1562 reportPowerSaveWhitelistChangedLocked();
1563 updateWhitelistAppIdsLocked();
1564 writeConfigFileLocked();
1565 return true;
1566 }
1567 }
1568
1569 public boolean removeSystemPowerWhitelistAppInternal(String name) {
1570 synchronized (this) {
1571 if (!mPowerSaveWhitelistApps.containsKey(name)) {
1572 return false;
1573 }
1574 mRemovedFromSystemWhitelistApps.put(name, mPowerSaveWhitelistApps.remove(name));
1575 reportPowerSaveWhitelistChangedLocked();
1576 updateWhitelistAppIdsLocked();
1577 writeConfigFileLocked();
1578 return true;
1579 }
1580 }
1581
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07001582 public boolean addPowerSaveWhitelistExceptIdleInternal(String name) {
1583 synchronized (this) {
1584 try {
1585 final ApplicationInfo ai = getContext().getPackageManager().getApplicationInfo(name,
1586 PackageManager.MATCH_ANY_USER);
1587 if (mPowerSaveWhitelistAppsExceptIdle.put(name, UserHandle.getAppId(ai.uid))
1588 == null) {
1589 mPowerSaveWhitelistUserAppsExceptIdle.add(name);
1590 reportPowerSaveWhitelistChangedLocked();
1591 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(
1592 mPowerSaveWhitelistAppsExceptIdle, mPowerSaveWhitelistUserApps,
1593 mPowerSaveWhitelistExceptIdleAppIds);
1594 }
1595 return true;
1596 } catch (PackageManager.NameNotFoundException e) {
1597 return false;
1598 }
1599 }
1600 }
1601
1602 public void resetPowerSaveWhitelistExceptIdleInternal() {
1603 synchronized (this) {
1604 if (mPowerSaveWhitelistAppsExceptIdle.removeAll(
1605 mPowerSaveWhitelistUserAppsExceptIdle)) {
1606 reportPowerSaveWhitelistChangedLocked();
1607 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(
1608 mPowerSaveWhitelistAppsExceptIdle, mPowerSaveWhitelistUserApps,
1609 mPowerSaveWhitelistExceptIdleAppIds);
1610 mPowerSaveWhitelistUserAppsExceptIdle.clear();
1611 }
1612 }
1613 }
1614
1615 public boolean getPowerSaveWhitelistExceptIdleInternal(String name) {
1616 synchronized (this) {
1617 return mPowerSaveWhitelistAppsExceptIdle.containsKey(name);
1618 }
1619 }
1620
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001621 public String[] getSystemPowerWhitelistExceptIdleInternal() {
1622 synchronized (this) {
1623 int size = mPowerSaveWhitelistAppsExceptIdle.size();
1624 String[] apps = new String[size];
1625 for (int i = 0; i < size; i++) {
1626 apps[i] = mPowerSaveWhitelistAppsExceptIdle.keyAt(i);
1627 }
1628 return apps;
1629 }
1630 }
1631
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001632 public String[] getSystemPowerWhitelistInternal() {
1633 synchronized (this) {
1634 int size = mPowerSaveWhitelistApps.size();
1635 String[] apps = new String[size];
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001636 for (int i = 0; i < size; i++) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001637 apps[i] = mPowerSaveWhitelistApps.keyAt(i);
1638 }
1639 return apps;
1640 }
1641 }
1642
Suprabh Shukla08105642017-09-26 14:45:30 -07001643 public String[] getRemovedSystemPowerWhitelistAppsInternal() {
1644 synchronized (this) {
1645 int size = mRemovedFromSystemWhitelistApps.size();
1646 final String[] apps = new String[size];
1647 for (int i = 0; i < size; i++) {
1648 apps[i] = mRemovedFromSystemWhitelistApps.keyAt(i);
1649 }
1650 return apps;
1651 }
1652 }
1653
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001654 public String[] getUserPowerWhitelistInternal() {
1655 synchronized (this) {
1656 int size = mPowerSaveWhitelistUserApps.size();
1657 String[] apps = new String[size];
1658 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1659 apps[i] = mPowerSaveWhitelistUserApps.keyAt(i);
1660 }
1661 return apps;
1662 }
1663 }
1664
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001665 public String[] getFullPowerWhitelistExceptIdleInternal() {
1666 synchronized (this) {
1667 int size = mPowerSaveWhitelistAppsExceptIdle.size() + mPowerSaveWhitelistUserApps.size();
1668 String[] apps = new String[size];
1669 int cur = 0;
1670 for (int i = 0; i < mPowerSaveWhitelistAppsExceptIdle.size(); i++) {
1671 apps[cur] = mPowerSaveWhitelistAppsExceptIdle.keyAt(i);
1672 cur++;
1673 }
1674 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1675 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
1676 cur++;
1677 }
1678 return apps;
1679 }
1680 }
1681
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001682 public String[] getFullPowerWhitelistInternal() {
1683 synchronized (this) {
1684 int size = mPowerSaveWhitelistApps.size() + mPowerSaveWhitelistUserApps.size();
1685 String[] apps = new String[size];
1686 int cur = 0;
1687 for (int i = 0; i < mPowerSaveWhitelistApps.size(); i++) {
1688 apps[cur] = mPowerSaveWhitelistApps.keyAt(i);
1689 cur++;
1690 }
1691 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1692 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
1693 cur++;
1694 }
1695 return apps;
1696 }
1697 }
1698
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001699 public boolean isPowerSaveWhitelistExceptIdleAppInternal(String packageName) {
1700 synchronized (this) {
1701 return mPowerSaveWhitelistAppsExceptIdle.containsKey(packageName)
1702 || mPowerSaveWhitelistUserApps.containsKey(packageName);
1703 }
1704 }
1705
Amith Yamasani06bf8242015-05-08 16:36:21 -07001706 public boolean isPowerSaveWhitelistAppInternal(String packageName) {
1707 synchronized (this) {
1708 return mPowerSaveWhitelistApps.containsKey(packageName)
1709 || mPowerSaveWhitelistUserApps.containsKey(packageName);
1710 }
1711 }
1712
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001713 public int[] getAppIdWhitelistExceptIdleInternal() {
1714 synchronized (this) {
1715 return mPowerSaveWhitelistExceptIdleAppIdArray;
1716 }
1717 }
1718
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001719 public int[] getAppIdWhitelistInternal() {
1720 synchronized (this) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001721 return mPowerSaveWhitelistAllAppIdArray;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001722 }
1723 }
1724
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001725 public int[] getAppIdUserWhitelistInternal() {
1726 synchronized (this) {
1727 return mPowerSaveWhitelistUserAppIdArray;
1728 }
1729 }
1730
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001731 public int[] getAppIdTempWhitelistInternal() {
1732 synchronized (this) {
1733 return mTempWhitelistAppIdArray;
1734 }
1735 }
1736
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001737 void addPowerSaveTempWhitelistAppChecked(String packageName, long duration,
1738 int userId, String reason) throws RemoteException {
1739 getContext().enforceCallingPermission(
1740 Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
1741 "No permission to change device idle whitelist");
1742 final int callingUid = Binder.getCallingUid();
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001743 userId = ActivityManager.getService().handleIncomingUser(
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001744 Binder.getCallingPid(),
1745 callingUid,
1746 userId,
1747 /*allowAll=*/ false,
1748 /*requireFull=*/ false,
1749 "addPowerSaveTempWhitelistApp", null);
1750 final long token = Binder.clearCallingIdentity();
1751 try {
1752 addPowerSaveTempWhitelistAppInternal(callingUid,
1753 packageName, duration, userId, true, reason);
1754 } finally {
1755 Binder.restoreCallingIdentity(token);
1756 }
1757 }
1758
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001759 /**
1760 * Adds an app to the temporary whitelist and resets the endTime for granting the
1761 * app an exemption to access network and acquire wakelocks.
1762 */
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001763 void addPowerSaveTempWhitelistAppInternal(int callingUid, String packageName,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001764 long duration, int userId, boolean sync, String reason) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001765 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001766 int uid = getContext().getPackageManager().getPackageUidAsUser(packageName, userId);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001767 int appId = UserHandle.getAppId(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001768 addPowerSaveTempWhitelistAppDirectInternal(callingUid, appId, duration, sync, reason);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001769 } catch (NameNotFoundException e) {
1770 }
1771 }
1772
Dianne Hackborna750a632015-06-16 17:18:23 -07001773 /**
1774 * Adds an app to the temporary whitelist and resets the endTime for granting the
1775 * app an exemption to access network and acquire wakelocks.
1776 */
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001777 void addPowerSaveTempWhitelistAppDirectInternal(int callingUid, int appId,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001778 long duration, boolean sync, String reason) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001779 final long timeNow = SystemClock.elapsedRealtime();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001780 boolean informWhitelistChanged = false;
Dianne Hackborna750a632015-06-16 17:18:23 -07001781 synchronized (this) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001782 int callingAppId = UserHandle.getAppId(callingUid);
1783 if (callingAppId >= Process.FIRST_APPLICATION_UID) {
1784 if (!mPowerSaveWhitelistSystemAppIds.get(callingAppId)) {
1785 throw new SecurityException("Calling app " + UserHandle.formatUid(callingUid)
1786 + " is not on whitelist");
1787 }
1788 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001789 duration = Math.min(duration, mConstants.MAX_TEMP_APP_WHITELIST_DURATION);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001790 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.get(appId);
1791 final boolean newEntry = entry == null;
Dianne Hackborna750a632015-06-16 17:18:23 -07001792 // Set the new end time
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001793 if (newEntry) {
1794 entry = new Pair<>(new MutableLong(0), reason);
1795 mTempWhitelistAppIdEndTimes.put(appId, entry);
1796 }
1797 entry.first.value = timeNow + duration;
Dianne Hackborna750a632015-06-16 17:18:23 -07001798 if (DEBUG) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001799 Slog.d(TAG, "Adding AppId " + appId + " to temp whitelist. New entry: " + newEntry);
Dianne Hackborna750a632015-06-16 17:18:23 -07001800 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001801 if (newEntry) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001802 // No pending timeout for the app id, post a delayed message
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001803 try {
1804 mBatteryStats.noteEvent(BatteryStats.HistoryItem.EVENT_TEMP_WHITELIST_START,
1805 reason, appId);
1806 } catch (RemoteException e) {
1807 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001808 postTempActiveTimeoutMessage(appId, duration);
Dianne Hackborn85e35642017-01-12 15:10:57 -08001809 updateTempWhitelistAppIdsLocked(appId, true);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001810 if (sync) {
1811 informWhitelistChanged = true;
1812 } else {
1813 mHandler.obtainMessage(MSG_REPORT_TEMP_APP_WHITELIST_CHANGED, appId, 1)
1814 .sendToTarget();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001815 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001816 reportTempWhitelistChangedLocked();
1817 }
1818 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001819 if (informWhitelistChanged) {
1820 mNetworkPolicyManagerInternal.onTempPowerSaveWhitelistChange(appId, true);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001821 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001822 }
1823
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001824 private void postTempActiveTimeoutMessage(int uid, long delay) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001825 if (DEBUG) {
1826 Slog.d(TAG, "postTempActiveTimeoutMessage: uid=" + uid + ", delay=" + delay);
1827 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001828 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_TEMP_APP_WHITELIST_TIMEOUT, uid, 0),
1829 delay);
1830 }
1831
1832 void checkTempAppWhitelistTimeout(int uid) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001833 final long timeNow = SystemClock.elapsedRealtime();
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001834 if (DEBUG) {
1835 Slog.d(TAG, "checkTempAppWhitelistTimeout: uid=" + uid + ", timeNow=" + timeNow);
1836 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001837 synchronized (this) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001838 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.get(uid);
1839 if (entry == null) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001840 // Nothing to do
1841 return;
1842 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001843 if (timeNow >= entry.first.value) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001844 mTempWhitelistAppIdEndTimes.delete(uid);
1845 if (DEBUG) {
1846 Slog.d(TAG, "Removing UID " + uid + " from temp whitelist");
1847 }
Dianne Hackborn85e35642017-01-12 15:10:57 -08001848 updateTempWhitelistAppIdsLocked(uid, false);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001849 mHandler.obtainMessage(MSG_REPORT_TEMP_APP_WHITELIST_CHANGED, uid, 0)
1850 .sendToTarget();
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001851 reportTempWhitelistChangedLocked();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001852 try {
1853 mBatteryStats.noteEvent(BatteryStats.HistoryItem.EVENT_TEMP_WHITELIST_FINISH,
1854 entry.second, uid);
1855 } catch (RemoteException e) {
1856 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001857 } else {
1858 // Need more time
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001859 if (DEBUG) {
1860 Slog.d(TAG, "Time to remove UID " + uid + ": " + entry.first.value);
1861 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001862 postTempActiveTimeoutMessage(uid, entry.first.value - timeNow);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001863 }
1864 }
1865 }
1866
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001867 public void exitIdleInternal(String reason) {
1868 synchronized (this) {
1869 becomeActiveLocked(reason, Binder.getCallingUid());
1870 }
1871 }
1872
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -07001873 void updateConnectivityState(Intent connIntent) {
1874 ConnectivityService cm;
1875 synchronized (this) {
1876 cm = mConnectivityService;
1877 }
1878 if (cm == null) {
1879 return;
1880 }
1881 // Note: can't call out to ConnectivityService with our lock held.
1882 NetworkInfo ni = cm.getActiveNetworkInfo();
1883 synchronized (this) {
Dianne Hackborn88c41352016-04-07 15:18:58 -07001884 boolean conn;
1885 if (ni == null) {
1886 conn = false;
1887 } else {
1888 if (connIntent == null) {
1889 conn = ni.isConnected();
1890 } else {
1891 final int networkType =
1892 connIntent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1893 ConnectivityManager.TYPE_NONE);
1894 if (ni.getType() != networkType) {
1895 return;
1896 }
1897 conn = !connIntent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,
1898 false);
1899 }
1900 }
1901 if (conn != mNetworkConnected) {
1902 mNetworkConnected = conn;
1903 if (conn && mLightState == LIGHT_STATE_WAITING_FOR_NETWORK) {
1904 stepLightIdleStateLocked("network");
1905 }
1906 }
1907 }
1908 }
1909
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -07001910 void updateInteractivityLocked() {
1911 // The interactivity state from the power manager tells us whether the display is
1912 // in a state that we need to keep things running so they will update at a normal
1913 // frequency.
1914 boolean screenOn = mPowerManager.isInteractive();
1915 if (DEBUG) Slog.d(TAG, "updateInteractivityLocked: screenOn=" + screenOn);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001916 if (!screenOn && mScreenOn) {
1917 mScreenOn = false;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001918 if (!mForceIdle) {
1919 becomeInactiveIfAppropriateLocked();
1920 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001921 } else if (screenOn) {
1922 mScreenOn = true;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001923 if (!mForceIdle) {
1924 becomeActiveLocked("screen", Process.myUid());
1925 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001926 }
1927 }
1928
1929 void updateChargingLocked(boolean charging) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001930 if (DEBUG) Slog.i(TAG, "updateChargingLocked: charging=" + charging);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001931 if (!charging && mCharging) {
1932 mCharging = false;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001933 if (!mForceIdle) {
1934 becomeInactiveIfAppropriateLocked();
1935 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001936 } else if (charging) {
1937 mCharging = charging;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001938 if (!mForceIdle) {
1939 becomeActiveLocked("charging", Process.myUid());
1940 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001941 }
1942 }
1943
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001944 void scheduleReportActiveLocked(String activeReason, int activeUid) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001945 Message msg = mHandler.obtainMessage(MSG_REPORT_ACTIVE, activeUid, 0, activeReason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001946 mHandler.sendMessage(msg);
1947 }
1948
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001949 void becomeActiveLocked(String activeReason, int activeUid) {
1950 if (DEBUG) Slog.i(TAG, "becomeActiveLocked, reason = " + activeReason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001951 if (mState != STATE_ACTIVE || mLightState != STATE_ACTIVE) {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001952 EventLogTags.writeDeviceIdle(STATE_ACTIVE, activeReason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001953 EventLogTags.writeDeviceIdleLight(LIGHT_STATE_ACTIVE, activeReason);
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001954 scheduleReportActiveLocked(activeReason, activeUid);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001955 mState = STATE_ACTIVE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001956 mLightState = LIGHT_STATE_ACTIVE;
Adam Lesinski31c05d12015-06-09 17:34:04 -07001957 mInactiveTimeout = mConstants.INACTIVE_TIMEOUT;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001958 mCurIdleBudget = 0;
1959 mMaintenanceStartTime = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001960 resetIdleManagementLocked();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001961 resetLightIdleManagementLocked();
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08001962 addEvent(EVENT_NORMAL);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001963 }
1964 }
1965
1966 void becomeInactiveIfAppropriateLocked() {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001967 if (DEBUG) Slog.d(TAG, "becomeInactiveIfAppropriateLocked()");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001968 if ((!mScreenOn && !mCharging) || mForceIdle) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001969 // Screen has turned off; we are now going to become inactive and start
1970 // waiting to see if we will ultimately go idle.
Dianne Hackbornb6843652016-02-22 12:20:13 -08001971 if (mState == STATE_ACTIVE && mDeepEnabled) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001972 mState = STATE_INACTIVE;
1973 if (DEBUG) Slog.d(TAG, "Moved from STATE_ACTIVE to STATE_INACTIVE");
1974 resetIdleManagementLocked();
1975 scheduleAlarmLocked(mInactiveTimeout, false);
1976 EventLogTags.writeDeviceIdle(mState, "no activity");
1977 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001978 if (mLightState == LIGHT_STATE_ACTIVE && mLightEnabled) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001979 mLightState = LIGHT_STATE_INACTIVE;
1980 if (DEBUG) Slog.d(TAG, "Moved from LIGHT_STATE_ACTIVE to LIGHT_STATE_INACTIVE");
1981 resetLightIdleManagementLocked();
Dianne Hackborn953fc942016-03-29 15:36:24 -07001982 scheduleLightAlarmLocked(mConstants.LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001983 EventLogTags.writeDeviceIdleLight(mLightState, "no activity");
1984 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001985 }
1986 }
1987
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001988 void resetIdleManagementLocked() {
1989 mNextIdlePendingDelay = 0;
1990 mNextIdleDelay = 0;
Dianne Hackborn953fc942016-03-29 15:36:24 -07001991 mNextLightIdleDelay = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001992 cancelAlarmLocked();
Kevin Gabayan92f15e62016-04-04 17:52:22 -07001993 cancelSensingTimeoutAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001994 cancelLocatingLocked();
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001995 stopMonitoringMotionLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001996 mAnyMotionDetector.stop();
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001997 }
1998
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001999 void resetLightIdleManagementLocked() {
2000 cancelLightAlarmLocked();
2001 }
2002
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002003 void exitForceIdleLocked() {
2004 if (mForceIdle) {
2005 mForceIdle = false;
2006 if (mScreenOn || mCharging) {
Dianne Hackborn88c41352016-04-07 15:18:58 -07002007 becomeActiveLocked("exit-force", Process.myUid());
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002008 }
2009 }
2010 }
2011
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002012 void stepLightIdleStateLocked(String reason) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002013 if (mLightState == LIGHT_STATE_OVERRIDE) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002014 // If we are already in deep device idle mode, then
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002015 // there is nothing left to do for light mode.
2016 return;
2017 }
2018
2019 if (DEBUG) Slog.d(TAG, "stepLightIdleStateLocked: mLightState=" + mLightState);
2020 EventLogTags.writeDeviceIdleLightStep();
2021
2022 switch (mLightState) {
2023 case LIGHT_STATE_INACTIVE:
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002024 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
Dianne Hackborn953fc942016-03-29 15:36:24 -07002025 // Reset the upcoming idle delays.
2026 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002027 mMaintenanceStartTime = 0;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002028 if (!isOpsInactiveLocked()) {
2029 // We have some active ops going on... give them a chance to finish
2030 // before going in to our first idle.
2031 mLightState = LIGHT_STATE_PRE_IDLE;
2032 EventLogTags.writeDeviceIdleLight(mLightState, reason);
2033 scheduleLightAlarmLocked(mConstants.LIGHT_PRE_IDLE_TIMEOUT);
2034 break;
2035 }
2036 // Nothing active, fall through to immediately idle.
2037 case LIGHT_STATE_PRE_IDLE:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002038 case LIGHT_STATE_IDLE_MAINTENANCE:
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002039 if (mMaintenanceStartTime != 0) {
2040 long duration = SystemClock.elapsedRealtime() - mMaintenanceStartTime;
2041 if (duration < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
2042 // We didn't use up all of our minimum budget; add this to the reserve.
2043 mCurIdleBudget += (mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET-duration);
2044 } else {
2045 // We used more than our minimum budget; this comes out of the reserve.
2046 mCurIdleBudget -= (duration-mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET);
2047 }
2048 }
2049 mMaintenanceStartTime = 0;
Dianne Hackborn953fc942016-03-29 15:36:24 -07002050 scheduleLightAlarmLocked(mNextLightIdleDelay);
2051 mNextLightIdleDelay = Math.min(mConstants.LIGHT_MAX_IDLE_TIMEOUT,
2052 (long)(mNextLightIdleDelay * mConstants.LIGHT_IDLE_FACTOR));
2053 if (mNextLightIdleDelay < mConstants.LIGHT_IDLE_TIMEOUT) {
2054 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
2055 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002056 if (DEBUG) Slog.d(TAG, "Moved to LIGHT_STATE_IDLE.");
2057 mLightState = LIGHT_STATE_IDLE;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002058 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002059 addEvent(EVENT_LIGHT_IDLE);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08002060 mGoingIdleWakeLock.acquire();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002061 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON_LIGHT);
2062 break;
2063 case LIGHT_STATE_IDLE:
Dianne Hackborn88c41352016-04-07 15:18:58 -07002064 case LIGHT_STATE_WAITING_FOR_NETWORK:
2065 if (mNetworkConnected || mLightState == LIGHT_STATE_WAITING_FOR_NETWORK) {
2066 // We have been idling long enough, now it is time to do some work.
2067 mActiveIdleOpCount = 1;
2068 mActiveIdleWakeLock.acquire();
2069 mMaintenanceStartTime = SystemClock.elapsedRealtime();
2070 if (mCurIdleBudget < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
2071 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
2072 } else if (mCurIdleBudget > mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET) {
2073 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET;
2074 }
2075 scheduleLightAlarmLocked(mCurIdleBudget);
2076 if (DEBUG) Slog.d(TAG,
2077 "Moved from LIGHT_STATE_IDLE to LIGHT_STATE_IDLE_MAINTENANCE.");
2078 mLightState = LIGHT_STATE_IDLE_MAINTENANCE;
2079 EventLogTags.writeDeviceIdleLight(mLightState, reason);
2080 addEvent(EVENT_LIGHT_MAINTENANCE);
2081 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
2082 } else {
2083 // We'd like to do maintenance, but currently don't have network
2084 // connectivity... let's try to wait until the network comes back.
2085 // We'll only wait for another full idle period, however, and then give up.
2086 scheduleLightAlarmLocked(mNextLightIdleDelay);
2087 if (DEBUG) Slog.d(TAG, "Moved to LIGHT_WAITING_FOR_NETWORK.");
2088 mLightState = LIGHT_STATE_WAITING_FOR_NETWORK;
2089 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002090 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002091 break;
2092 }
2093 }
2094
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002095 void stepIdleStateLocked(String reason) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002096 if (DEBUG) Slog.d(TAG, "stepIdleStateLocked: mState=" + mState);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002097 EventLogTags.writeDeviceIdleStep();
2098
2099 final long now = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07002100 if ((now+mConstants.MIN_TIME_TO_ALARM) > mAlarmManager.getNextWakeFromIdleTime()) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002101 // Whoops, there is an upcoming alarm. We don't actually want to go idle.
2102 if (mState != STATE_ACTIVE) {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002103 becomeActiveLocked("alarm", Process.myUid());
Koji Fukui27b33302015-12-16 19:43:01 +09002104 becomeInactiveIfAppropriateLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002105 }
2106 return;
2107 }
2108
2109 switch (mState) {
2110 case STATE_INACTIVE:
2111 // We have now been inactive long enough, it is time to start looking
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002112 // for motion and sleep some more while doing so.
2113 startMonitoringMotionLocked();
Adam Lesinski31c05d12015-06-09 17:34:04 -07002114 scheduleAlarmLocked(mConstants.IDLE_AFTER_INACTIVE_TIMEOUT, false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002115 // Reset the upcoming idle delays.
Adam Lesinski31c05d12015-06-09 17:34:04 -07002116 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
2117 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002118 mState = STATE_IDLE_PENDING;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002119 if (DEBUG) Slog.d(TAG, "Moved from STATE_INACTIVE to STATE_IDLE_PENDING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002120 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002121 break;
2122 case STATE_IDLE_PENDING:
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002123 mState = STATE_SENSING;
2124 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE_PENDING to STATE_SENSING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002125 EventLogTags.writeDeviceIdle(mState, reason);
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002126 scheduleSensingTimeoutAlarmLocked(mConstants.SENSING_TIMEOUT);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002127 cancelLocatingLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002128 mNotMoving = false;
2129 mLocated = false;
2130 mLastGenericLocation = null;
2131 mLastGpsLocation = null;
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002132 mAnyMotionDetector.checkForAnyMotion();
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002133 break;
2134 case STATE_SENSING:
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002135 cancelSensingTimeoutAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002136 mState = STATE_LOCATING;
2137 if (DEBUG) Slog.d(TAG, "Moved from STATE_SENSING to STATE_LOCATING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002138 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002139 scheduleAlarmLocked(mConstants.LOCATING_TIMEOUT, false);
Joe LaPenna23d681b2015-08-27 15:12:11 -07002140 if (mLocationManager != null
2141 && mLocationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
2142 mLocationManager.requestLocationUpdates(mLocationRequest,
2143 mGenericLocationListener, mHandler.getLooper());
2144 mLocating = true;
2145 } else {
2146 mHasNetworkLocation = false;
2147 }
2148 if (mLocationManager != null
2149 && mLocationManager.getProvider(LocationManager.GPS_PROVIDER) != null) {
2150 mHasGps = true;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002151 mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 5,
2152 mGpsLocationListener, mHandler.getLooper());
Joe LaPenna23d681b2015-08-27 15:12:11 -07002153 mLocating = true;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002154 } else {
Joe LaPenna23d681b2015-08-27 15:12:11 -07002155 mHasGps = false;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002156 }
Joe LaPenna23d681b2015-08-27 15:12:11 -07002157 // If we have a location provider, we're all set, the listeners will move state
2158 // forward.
2159 if (mLocating) {
2160 break;
2161 }
2162
2163 // Otherwise, we have to move from locating into idle maintenance.
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002164 case STATE_LOCATING:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002165 cancelAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002166 cancelLocatingLocked();
2167 mAnyMotionDetector.stop();
Dianne Hackborn953fc942016-03-29 15:36:24 -07002168
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002169 case STATE_IDLE_MAINTENANCE:
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002170 scheduleAlarmLocked(mNextIdleDelay, true);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002171 if (DEBUG) Slog.d(TAG, "Moved to STATE_IDLE. Next alarm in " + mNextIdleDelay +
2172 " ms.");
Adam Lesinski31c05d12015-06-09 17:34:04 -07002173 mNextIdleDelay = (long)(mNextIdleDelay * mConstants.IDLE_FACTOR);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002174 if (DEBUG) Slog.d(TAG, "Setting mNextIdleDelay = " + mNextIdleDelay);
Adam Lesinski31c05d12015-06-09 17:34:04 -07002175 mNextIdleDelay = Math.min(mNextIdleDelay, mConstants.MAX_IDLE_TIMEOUT);
Dianne Hackborn953fc942016-03-29 15:36:24 -07002176 if (mNextIdleDelay < mConstants.IDLE_TIMEOUT) {
2177 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
2178 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002179 mState = STATE_IDLE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002180 if (mLightState != LIGHT_STATE_OVERRIDE) {
2181 mLightState = LIGHT_STATE_OVERRIDE;
2182 cancelLightAlarmLocked();
2183 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002184 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackbornb6843652016-02-22 12:20:13 -08002185 addEvent(EVENT_DEEP_IDLE);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08002186 mGoingIdleWakeLock.acquire();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002187 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON);
2188 break;
2189 case STATE_IDLE:
2190 // We have been idling long enough, now it is time to do some work.
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002191 mActiveIdleOpCount = 1;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002192 mActiveIdleWakeLock.acquire();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002193 scheduleAlarmLocked(mNextIdlePendingDelay, false);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002194 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE to STATE_IDLE_MAINTENANCE. " +
2195 "Next alarm in " + mNextIdlePendingDelay + " ms.");
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002196 mMaintenanceStartTime = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07002197 mNextIdlePendingDelay = Math.min(mConstants.MAX_IDLE_PENDING_TIMEOUT,
2198 (long)(mNextIdlePendingDelay * mConstants.IDLE_PENDING_FACTOR));
Dianne Hackborn953fc942016-03-29 15:36:24 -07002199 if (mNextIdlePendingDelay < mConstants.IDLE_PENDING_TIMEOUT) {
2200 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
2201 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002202 mState = STATE_IDLE_MAINTENANCE;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002203 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackbornb6843652016-02-22 12:20:13 -08002204 addEvent(EVENT_DEEP_MAINTENANCE);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002205 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
2206 break;
2207 }
2208 }
2209
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002210 void incActiveIdleOps() {
2211 synchronized (this) {
2212 mActiveIdleOpCount++;
2213 }
2214 }
2215
2216 void decActiveIdleOps() {
2217 synchronized (this) {
2218 mActiveIdleOpCount--;
2219 if (mActiveIdleOpCount <= 0) {
2220 exitMaintenanceEarlyIfNeededLocked();
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002221 mActiveIdleWakeLock.release();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002222 }
2223 }
2224 }
2225
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002226 void setJobsActive(boolean active) {
2227 synchronized (this) {
2228 mJobsActive = active;
Yao Chenca5edbb2016-01-13 14:44:36 -08002229 reportMaintenanceActivityIfNeededLocked();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002230 if (!active) {
2231 exitMaintenanceEarlyIfNeededLocked();
2232 }
2233 }
2234 }
2235
2236 void setAlarmsActive(boolean active) {
2237 synchronized (this) {
2238 mAlarmsActive = active;
2239 if (!active) {
2240 exitMaintenanceEarlyIfNeededLocked();
2241 }
2242 }
2243 }
2244
Yao Chenca5edbb2016-01-13 14:44:36 -08002245 boolean registerMaintenanceActivityListener(IMaintenanceActivityListener listener) {
2246 synchronized (this) {
2247 mMaintenanceActivityListeners.register(listener);
2248 return mReportedMaintenanceActivity;
2249 }
2250 }
2251
2252 void unregisterMaintenanceActivityListener(IMaintenanceActivityListener listener) {
2253 synchronized (this) {
2254 mMaintenanceActivityListeners.unregister(listener);
2255 }
2256 }
2257
2258 void reportMaintenanceActivityIfNeededLocked() {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07002259 boolean active = mJobsActive;
Yao Chenca5edbb2016-01-13 14:44:36 -08002260 if (active == mReportedMaintenanceActivity) {
2261 return;
2262 }
2263 mReportedMaintenanceActivity = active;
2264 Message msg = mHandler.obtainMessage(MSG_REPORT_MAINTENANCE_ACTIVITY,
2265 mReportedMaintenanceActivity ? 1 : 0, 0);
2266 mHandler.sendMessage(msg);
2267 }
2268
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002269 boolean isOpsInactiveLocked() {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07002270 return mActiveIdleOpCount <= 0 && !mJobsActive && !mAlarmsActive;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002271 }
2272
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002273 void exitMaintenanceEarlyIfNeededLocked() {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002274 if (mState == STATE_IDLE_MAINTENANCE || mLightState == LIGHT_STATE_IDLE_MAINTENANCE
2275 || mLightState == LIGHT_STATE_PRE_IDLE) {
2276 if (isOpsInactiveLocked()) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002277 final long now = SystemClock.elapsedRealtime();
2278 if (DEBUG) {
2279 StringBuilder sb = new StringBuilder();
2280 sb.append("Exit: start=");
2281 TimeUtils.formatDuration(mMaintenanceStartTime, sb);
2282 sb.append(" now=");
2283 TimeUtils.formatDuration(now, sb);
2284 Slog.d(TAG, sb.toString());
2285 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002286 if (mState == STATE_IDLE_MAINTENANCE) {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002287 stepIdleStateLocked("s:early");
2288 } else if (mLightState == LIGHT_STATE_PRE_IDLE) {
2289 stepLightIdleStateLocked("s:predone");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002290 } else {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002291 stepLightIdleStateLocked("s:early");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002292 }
2293 }
2294 }
2295 }
2296
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002297 void motionLocked() {
2298 if (DEBUG) Slog.d(TAG, "motionLocked()");
2299 // The motion sensor will have been disabled at this point
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002300 handleMotionDetectedLocked(mConstants.MOTION_INACTIVE_TIMEOUT, "motion");
2301 }
2302
2303 void handleMotionDetectedLocked(long timeout, String type) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002304 // The device is not yet active, so we want to go back to the pending idle
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002305 // state to wait again for no motion. Note that we only monitor for motion
2306 // after moving out of the inactive state, so no need to worry about that.
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002307 boolean becomeInactive = false;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002308 if (mState != STATE_ACTIVE) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002309 scheduleReportActiveLocked(type, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002310 mState = STATE_ACTIVE;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002311 mInactiveTimeout = timeout;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002312 mCurIdleBudget = 0;
2313 mMaintenanceStartTime = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002314 EventLogTags.writeDeviceIdle(mState, type);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002315 addEvent(EVENT_NORMAL);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002316 becomeInactive = true;
2317 }
2318 if (mLightState == LIGHT_STATE_OVERRIDE) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002319 // We went out of light idle mode because we had started deep idle mode... let's
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002320 // now go back and reset things so we resume light idling if appropriate.
2321 mLightState = STATE_ACTIVE;
2322 EventLogTags.writeDeviceIdleLight(mLightState, type);
2323 becomeInactive = true;
2324 }
2325 if (becomeInactive) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002326 becomeInactiveIfAppropriateLocked();
2327 }
2328 }
2329
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002330 void receivedGenericLocationLocked(Location location) {
2331 if (mState != STATE_LOCATING) {
2332 cancelLocatingLocked();
2333 return;
2334 }
2335 if (DEBUG) Slog.d(TAG, "Generic location: " + location);
2336 mLastGenericLocation = new Location(location);
Joe LaPenna23d681b2015-08-27 15:12:11 -07002337 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY && mHasGps) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002338 return;
2339 }
2340 mLocated = true;
2341 if (mNotMoving) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002342 stepIdleStateLocked("s:location");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002343 }
2344 }
2345
2346 void receivedGpsLocationLocked(Location location) {
2347 if (mState != STATE_LOCATING) {
2348 cancelLocatingLocked();
2349 return;
2350 }
2351 if (DEBUG) Slog.d(TAG, "GPS location: " + location);
2352 mLastGpsLocation = new Location(location);
2353 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY) {
2354 return;
2355 }
2356 mLocated = true;
2357 if (mNotMoving) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002358 stepIdleStateLocked("s:gps");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002359 }
2360 }
2361
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002362 void startMonitoringMotionLocked() {
2363 if (DEBUG) Slog.d(TAG, "startMonitoringMotionLocked()");
2364 if (mMotionSensor != null && !mMotionListener.active) {
2365 mMotionListener.registerLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002366 }
2367 }
2368
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002369 void stopMonitoringMotionLocked() {
2370 if (DEBUG) Slog.d(TAG, "stopMonitoringMotionLocked()");
2371 if (mMotionSensor != null && mMotionListener.active) {
2372 mMotionListener.unregisterLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002373 }
2374 }
2375
2376 void cancelAlarmLocked() {
2377 if (mNextAlarmTime != 0) {
2378 mNextAlarmTime = 0;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002379 mAlarmManager.cancel(mDeepAlarmListener);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002380 }
2381 }
2382
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002383 void cancelLightAlarmLocked() {
2384 if (mNextLightAlarmTime != 0) {
2385 mNextLightAlarmTime = 0;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002386 mAlarmManager.cancel(mLightAlarmListener);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002387 }
2388 }
2389
2390 void cancelLocatingLocked() {
2391 if (mLocating) {
2392 mLocationManager.removeUpdates(mGenericLocationListener);
2393 mLocationManager.removeUpdates(mGpsLocationListener);
2394 mLocating = false;
2395 }
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002396 }
2397
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002398 void cancelSensingTimeoutAlarmLocked() {
2399 if (mNextSensingTimeoutAlarmTime != 0) {
2400 mNextSensingTimeoutAlarmTime = 0;
2401 mAlarmManager.cancel(mSensingTimeoutAlarmListener);
2402 }
2403 }
2404
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002405 void scheduleAlarmLocked(long delay, boolean idleUntil) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002406 if (DEBUG) Slog.d(TAG, "scheduleAlarmLocked(" + delay + ", " + idleUntil + ")");
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002407 if (mMotionSensor == null) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07002408 // If there is no motion sensor on this device, then we won't schedule
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002409 // alarms, because we can't determine if the device is not moving. This effectively
Joe LaPenna23d681b2015-08-27 15:12:11 -07002410 // turns off normal execution of device idling, although it is still possible to
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002411 // manually poke it by pretending like the alarm is going off.
2412 return;
2413 }
2414 mNextAlarmTime = SystemClock.elapsedRealtime() + delay;
2415 if (idleUntil) {
2416 mAlarmManager.setIdleUntil(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002417 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002418 } else {
2419 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002420 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002421 }
2422 }
2423
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002424 void scheduleLightAlarmLocked(long delay) {
2425 if (DEBUG) Slog.d(TAG, "scheduleLightAlarmLocked(" + delay + ")");
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002426 mNextLightAlarmTime = SystemClock.elapsedRealtime() + delay;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002427 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002428 mNextLightAlarmTime, "DeviceIdleController.light", mLightAlarmListener, mHandler);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002429 }
2430
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002431 void scheduleSensingTimeoutAlarmLocked(long delay) {
2432 if (DEBUG) Slog.d(TAG, "scheduleSensingAlarmLocked(" + delay + ")");
2433 mNextSensingTimeoutAlarmTime = SystemClock.elapsedRealtime() + delay;
2434 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, mNextSensingTimeoutAlarmTime,
2435 "DeviceIdleController.sensing", mSensingTimeoutAlarmListener, mHandler);
2436 }
2437
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002438 private static int[] buildAppIdArray(ArrayMap<String, Integer> systemApps,
2439 ArrayMap<String, Integer> userApps, SparseBooleanArray outAppIds) {
2440 outAppIds.clear();
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002441 if (systemApps != null) {
2442 for (int i = 0; i < systemApps.size(); i++) {
2443 outAppIds.put(systemApps.valueAt(i), true);
2444 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002445 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002446 if (userApps != null) {
2447 for (int i = 0; i < userApps.size(); i++) {
2448 outAppIds.put(userApps.valueAt(i), true);
2449 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002450 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002451 int size = outAppIds.size();
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002452 int[] appids = new int[size];
2453 for (int i = 0; i < size; i++) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002454 appids[i] = outAppIds.keyAt(i);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002455 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002456 return appids;
2457 }
2458
2459 private void updateWhitelistAppIdsLocked() {
2460 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(mPowerSaveWhitelistAppsExceptIdle,
2461 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistExceptIdleAppIds);
2462 mPowerSaveWhitelistAllAppIdArray = buildAppIdArray(mPowerSaveWhitelistApps,
2463 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistAllAppIds);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002464 mPowerSaveWhitelistUserAppIdArray = buildAppIdArray(null,
2465 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistUserAppIds);
Dianne Hackborn85e35642017-01-12 15:10:57 -08002466 if (mLocalActivityManager != null) {
2467 if (DEBUG) {
2468 Slog.d(TAG, "Setting activity manager whitelist to "
2469 + Arrays.toString(mPowerSaveWhitelistAllAppIdArray));
2470 }
2471 mLocalActivityManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
2472 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002473 if (mLocalPowerManager != null) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002474 if (DEBUG) {
2475 Slog.d(TAG, "Setting wakelock whitelist to "
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002476 + Arrays.toString(mPowerSaveWhitelistAllAppIdArray));
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002477 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002478 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002479 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002480 if (mLocalAlarmManager != null) {
2481 if (DEBUG) {
2482 Slog.d(TAG, "Setting alarm whitelist to "
2483 + Arrays.toString(mPowerSaveWhitelistUserAppIdArray));
2484 }
2485 mLocalAlarmManager.setDeviceIdleUserWhitelist(mPowerSaveWhitelistUserAppIdArray);
2486 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002487 }
2488
Dianne Hackborn85e35642017-01-12 15:10:57 -08002489 private void updateTempWhitelistAppIdsLocked(int appId, boolean adding) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002490 final int size = mTempWhitelistAppIdEndTimes.size();
2491 if (mTempWhitelistAppIdArray.length != size) {
2492 mTempWhitelistAppIdArray = new int[size];
2493 }
2494 for (int i = 0; i < size; i++) {
2495 mTempWhitelistAppIdArray[i] = mTempWhitelistAppIdEndTimes.keyAt(i);
2496 }
Dianne Hackborn85e35642017-01-12 15:10:57 -08002497 if (mLocalActivityManager != null) {
2498 if (DEBUG) {
2499 Slog.d(TAG, "Setting activity manager temp whitelist to "
2500 + Arrays.toString(mTempWhitelistAppIdArray));
2501 }
2502 mLocalActivityManager.updateDeviceIdleTempWhitelist(mTempWhitelistAppIdArray, appId,
2503 adding);
2504 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002505 if (mLocalPowerManager != null) {
2506 if (DEBUG) {
2507 Slog.d(TAG, "Setting wakelock temp whitelist to "
2508 + Arrays.toString(mTempWhitelistAppIdArray));
2509 }
2510 mLocalPowerManager.setDeviceIdleTempWhitelist(mTempWhitelistAppIdArray);
2511 }
2512 }
2513
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002514 private void reportPowerSaveWhitelistChangedLocked() {
2515 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
2516 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Xiaohui Chene4de5a02015-09-22 15:33:31 -07002517 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002518 }
2519
2520 private void reportTempWhitelistChangedLocked() {
2521 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_TEMP_WHITELIST_CHANGED);
2522 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Xiaohui Chene4de5a02015-09-22 15:33:31 -07002523 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002524 }
2525
2526 void readConfigFileLocked() {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002527 if (DEBUG) Slog.d(TAG, "Reading config from " + mConfigFile.getBaseFile());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002528 mPowerSaveWhitelistUserApps.clear();
2529 FileInputStream stream;
2530 try {
2531 stream = mConfigFile.openRead();
2532 } catch (FileNotFoundException e) {
2533 return;
2534 }
2535 try {
2536 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002537 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002538 readConfigFileLocked(parser);
2539 } catch (XmlPullParserException e) {
2540 } finally {
2541 try {
2542 stream.close();
2543 } catch (IOException e) {
2544 }
2545 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002546 }
2547
2548 private void readConfigFileLocked(XmlPullParser parser) {
2549 final PackageManager pm = getContext().getPackageManager();
2550
2551 try {
2552 int type;
2553 while ((type = parser.next()) != XmlPullParser.START_TAG
2554 && type != XmlPullParser.END_DOCUMENT) {
2555 ;
2556 }
2557
2558 if (type != XmlPullParser.START_TAG) {
2559 throw new IllegalStateException("no start tag found");
2560 }
2561
2562 int outerDepth = parser.getDepth();
2563 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2564 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2565 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2566 continue;
2567 }
2568
2569 String tagName = parser.getName();
Suprabh Shukla08105642017-09-26 14:45:30 -07002570 switch (tagName) {
2571 case "wl":
2572 String name = parser.getAttributeValue(null, "n");
2573 if (name != null) {
2574 try {
2575 ApplicationInfo ai = pm.getApplicationInfo(name,
2576 PackageManager.MATCH_ANY_USER);
2577 mPowerSaveWhitelistUserApps.put(ai.packageName,
2578 UserHandle.getAppId(ai.uid));
2579 } catch (PackageManager.NameNotFoundException e) {
2580 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002581 }
Suprabh Shukla08105642017-09-26 14:45:30 -07002582 break;
2583 case "un-wl":
2584 final String packageName = parser.getAttributeValue(null, "n");
2585 if (mPowerSaveWhitelistApps.containsKey(packageName)) {
2586 mRemovedFromSystemWhitelistApps.put(packageName,
2587 mPowerSaveWhitelistApps.remove(packageName));
2588 }
2589 break;
2590 default:
2591 Slog.w(TAG, "Unknown element under <config>: "
2592 + parser.getName());
2593 XmlUtils.skipCurrentTag(parser);
2594 break;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002595 }
2596 }
2597
2598 } catch (IllegalStateException e) {
2599 Slog.w(TAG, "Failed parsing config " + e);
2600 } catch (NullPointerException e) {
2601 Slog.w(TAG, "Failed parsing config " + e);
2602 } catch (NumberFormatException e) {
2603 Slog.w(TAG, "Failed parsing config " + e);
2604 } catch (XmlPullParserException e) {
2605 Slog.w(TAG, "Failed parsing config " + e);
2606 } catch (IOException e) {
2607 Slog.w(TAG, "Failed parsing config " + e);
2608 } catch (IndexOutOfBoundsException e) {
2609 Slog.w(TAG, "Failed parsing config " + e);
2610 }
2611 }
2612
2613 void writeConfigFileLocked() {
2614 mHandler.removeMessages(MSG_WRITE_CONFIG);
2615 mHandler.sendEmptyMessageDelayed(MSG_WRITE_CONFIG, 5000);
2616 }
2617
2618 void handleWriteConfigFile() {
2619 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
2620
2621 try {
2622 synchronized (this) {
2623 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002624 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002625 writeConfigFileLocked(out);
2626 }
2627 } catch (IOException e) {
2628 }
2629
2630 synchronized (mConfigFile) {
2631 FileOutputStream stream = null;
2632 try {
2633 stream = mConfigFile.startWrite();
2634 memStream.writeTo(stream);
2635 stream.flush();
2636 FileUtils.sync(stream);
2637 stream.close();
2638 mConfigFile.finishWrite(stream);
2639 } catch (IOException e) {
2640 Slog.w(TAG, "Error writing config file", e);
2641 mConfigFile.failWrite(stream);
2642 }
2643 }
2644 }
2645
2646 void writeConfigFileLocked(XmlSerializer out) throws IOException {
2647 out.startDocument(null, true);
2648 out.startTag(null, "config");
2649 for (int i=0; i<mPowerSaveWhitelistUserApps.size(); i++) {
2650 String name = mPowerSaveWhitelistUserApps.keyAt(i);
2651 out.startTag(null, "wl");
2652 out.attribute(null, "n", name);
2653 out.endTag(null, "wl");
2654 }
Suprabh Shukla08105642017-09-26 14:45:30 -07002655 for (int i = 0; i < mRemovedFromSystemWhitelistApps.size(); i++) {
2656 out.startTag(null, "un-wl");
2657 out.attribute(null, "n", mRemovedFromSystemWhitelistApps.keyAt(i));
2658 out.endTag(null, "un-wl");
2659 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002660 out.endTag(null, "config");
2661 out.endDocument();
2662 }
2663
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002664 static void dumpHelp(PrintWriter pw) {
2665 pw.println("Device idle controller (deviceidle) commands:");
2666 pw.println(" help");
2667 pw.println(" Print this help text.");
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002668 pw.println(" step [light|deep]");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002669 pw.println(" Immediately step to next state, without waiting for alarm.");
Dianne Hackborn88c41352016-04-07 15:18:58 -07002670 pw.println(" force-idle [light|deep]");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002671 pw.println(" Force directly into idle mode, regardless of other device state.");
Dianne Hackborn88c41352016-04-07 15:18:58 -07002672 pw.println(" force-inactive");
2673 pw.println(" Force to be inactive, ready to freely step idle states.");
2674 pw.println(" unforce");
2675 pw.println(" Resume normal functioning after force-idle or force-inactive.");
2676 pw.println(" get [light|deep|force|screen|charging|network]");
2677 pw.println(" Retrieve the current given state.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002678 pw.println(" disable [light|deep|all]");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002679 pw.println(" Completely disable device idle mode.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002680 pw.println(" enable [light|deep|all]");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002681 pw.println(" Re-enable device idle mode after it had previously been disabled.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002682 pw.println(" enabled [light|deep|all]");
Dianne Hackborn92617032015-06-19 15:32:19 -07002683 pw.println(" Print 1 if device idle mode is currently enabled, else 0.");
Dianne Hackborn1b139682015-07-06 15:13:37 -07002684 pw.println(" whitelist");
2685 pw.println(" Print currently whitelisted apps.");
Dianne Hackborn92617032015-06-19 15:32:19 -07002686 pw.println(" whitelist [package ...]");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002687 pw.println(" Add (prefix with +) or remove (prefix with -) packages.");
Suprabh Shukla08105642017-09-26 14:45:30 -07002688 pw.println(" sys-whitelist [package ...|reset]");
2689 pw.println(" Prefix the package with '-' to remove it from the system whitelist or '+'"
2690 + " to put it back in the system whitelist.");
2691 pw.println(" Note that only packages that were"
2692 + " earlier removed from the system whitelist can be added back.");
2693 pw.println(" reset will reset the whitelist to the original state");
2694 pw.println(" Prints the system whitelist if no arguments are specified");
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07002695 pw.println(" except-idle-whitelist [package ...|reset]");
2696 pw.println(" Prefix the package with '+' to add it to whitelist or "
2697 + "'=' to check if it is already whitelisted");
2698 pw.println(" [reset] will reset the whitelist to it's original state");
2699 pw.println(" Note that unlike <whitelist> cmd, "
2700 + "changes made using this won't be persisted across boots");
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002701 pw.println(" tempwhitelist");
2702 pw.println(" Print packages that are temporarily whitelisted.");
Dianne Hackborn85e35642017-01-12 15:10:57 -08002703 pw.println(" tempwhitelist [-u USER] [-d DURATION] [package ..]");
2704 pw.println(" Temporarily place packages in whitelist for DURATION milliseconds.");
2705 pw.println(" If no DURATION is specified, 10 seconds is used");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002706 }
2707
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002708 class Shell extends ShellCommand {
2709 int userId = UserHandle.USER_SYSTEM;
2710
2711 @Override
2712 public int onCommand(String cmd) {
2713 return onShellCommand(this, cmd);
2714 }
2715
2716 @Override
2717 public void onHelp() {
2718 PrintWriter pw = getOutPrintWriter();
2719 dumpHelp(pw);
2720 }
2721 }
2722
2723 int onShellCommand(Shell shell, String cmd) {
2724 PrintWriter pw = shell.getOutPrintWriter();
2725 if ("step".equals(cmd)) {
2726 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2727 null);
2728 synchronized (this) {
2729 long token = Binder.clearCallingIdentity();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002730 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002731 try {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002732 if (arg == null || "deep".equals(arg)) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002733 stepIdleStateLocked("s:shell");
2734 pw.print("Stepped to deep: ");
2735 pw.println(stateToString(mState));
2736 } else if ("light".equals(arg)) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002737 stepLightIdleStateLocked("s:shell");
2738 pw.print("Stepped to light: "); pw.println(lightStateToString(mLightState));
2739 } else {
2740 pw.println("Unknown idle mode: " + arg);
2741 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002742 } finally {
2743 Binder.restoreCallingIdentity(token);
2744 }
2745 }
2746 } else if ("force-idle".equals(cmd)) {
2747 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2748 null);
2749 synchronized (this) {
2750 long token = Binder.clearCallingIdentity();
Dianne Hackborn88c41352016-04-07 15:18:58 -07002751 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002752 try {
Dianne Hackborn88c41352016-04-07 15:18:58 -07002753 if (arg == null || "deep".equals(arg)) {
2754 if (!mDeepEnabled) {
2755 pw.println("Unable to go deep idle; not enabled");
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002756 return -1;
2757 }
Dianne Hackborn88c41352016-04-07 15:18:58 -07002758 mForceIdle = true;
2759 becomeInactiveIfAppropriateLocked();
2760 int curState = mState;
2761 while (curState != STATE_IDLE) {
2762 stepIdleStateLocked("s:shell");
2763 if (curState == mState) {
2764 pw.print("Unable to go deep idle; stopped at ");
2765 pw.println(stateToString(mState));
2766 exitForceIdleLocked();
2767 return -1;
2768 }
2769 curState = mState;
2770 }
2771 pw.println("Now forced in to deep idle mode");
2772 } else if ("light".equals(arg)) {
2773 mForceIdle = true;
2774 becomeInactiveIfAppropriateLocked();
2775 int curLightState = mLightState;
2776 while (curLightState != LIGHT_STATE_IDLE) {
2777 stepIdleStateLocked("s:shell");
2778 if (curLightState == mLightState) {
2779 pw.print("Unable to go light idle; stopped at ");
2780 pw.println(lightStateToString(mLightState));
2781 exitForceIdleLocked();
2782 return -1;
2783 }
2784 curLightState = mLightState;
2785 }
2786 pw.println("Now forced in to light idle mode");
2787 } else {
2788 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002789 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002790 } finally {
2791 Binder.restoreCallingIdentity(token);
2792 }
2793 }
Dianne Hackborn88c41352016-04-07 15:18:58 -07002794 } else if ("force-inactive".equals(cmd)) {
2795 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2796 null);
2797 synchronized (this) {
2798 long token = Binder.clearCallingIdentity();
2799 try {
2800 mForceIdle = true;
2801 becomeInactiveIfAppropriateLocked();
2802 pw.print("Light state: ");
2803 pw.print(lightStateToString(mLightState));
2804 pw.print(", deep state: ");
2805 pw.println(stateToString(mState));
2806 } finally {
2807 Binder.restoreCallingIdentity(token);
2808 }
2809 }
2810 } else if ("unforce".equals(cmd)) {
2811 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2812 null);
2813 synchronized (this) {
2814 long token = Binder.clearCallingIdentity();
2815 try {
2816 exitForceIdleLocked();
2817 pw.print("Light state: ");
2818 pw.print(lightStateToString(mLightState));
2819 pw.print(", deep state: ");
2820 pw.println(stateToString(mState));
2821 } finally {
2822 Binder.restoreCallingIdentity(token);
2823 }
2824 }
2825 } else if ("get".equals(cmd)) {
2826 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2827 null);
2828 synchronized (this) {
2829 String arg = shell.getNextArg();
2830 if (arg != null) {
2831 long token = Binder.clearCallingIdentity();
2832 try {
2833 switch (arg) {
2834 case "light": pw.println(lightStateToString(mLightState)); break;
2835 case "deep": pw.println(stateToString(mState)); break;
2836 case "force": pw.println(mForceIdle); break;
2837 case "screen": pw.println(mScreenOn); break;
2838 case "charging": pw.println(mCharging); break;
2839 case "network": pw.println(mNetworkConnected); break;
2840 default: pw.println("Unknown get option: " + arg); break;
2841 }
2842 } finally {
2843 Binder.restoreCallingIdentity(token);
2844 }
2845 } else {
2846 pw.println("Argument required");
2847 }
2848 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002849 } else if ("disable".equals(cmd)) {
2850 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2851 null);
2852 synchronized (this) {
2853 long token = Binder.clearCallingIdentity();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002854 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002855 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002856 boolean becomeActive = false;
2857 boolean valid = false;
2858 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
2859 valid = true;
2860 if (mDeepEnabled) {
2861 mDeepEnabled = false;
2862 becomeActive = true;
2863 pw.println("Deep idle mode disabled");
2864 }
2865 }
2866 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
2867 valid = true;
2868 if (mLightEnabled) {
2869 mLightEnabled = false;
2870 becomeActive = true;
2871 pw.println("Light idle mode disabled");
2872 }
2873 }
2874 if (becomeActive) {
2875 becomeActiveLocked((arg == null ? "all" : arg) + "-disabled",
2876 Process.myUid());
2877 }
2878 if (!valid) {
2879 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002880 }
2881 } finally {
2882 Binder.restoreCallingIdentity(token);
2883 }
2884 }
2885 } else if ("enable".equals(cmd)) {
2886 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2887 null);
2888 synchronized (this) {
2889 long token = Binder.clearCallingIdentity();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002890 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002891 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002892 boolean becomeInactive = false;
2893 boolean valid = false;
2894 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
2895 valid = true;
2896 if (!mDeepEnabled) {
2897 mDeepEnabled = true;
2898 becomeInactive = true;
2899 pw.println("Deep idle mode enabled");
2900 }
2901 }
2902 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
2903 valid = true;
2904 if (!mLightEnabled) {
2905 mLightEnabled = true;
2906 becomeInactive = true;
2907 pw.println("Light idle mode enable");
2908 }
2909 }
2910 if (becomeInactive) {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002911 becomeInactiveIfAppropriateLocked();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002912 }
2913 if (!valid) {
2914 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002915 }
2916 } finally {
2917 Binder.restoreCallingIdentity(token);
2918 }
2919 }
2920 } else if ("enabled".equals(cmd)) {
2921 synchronized (this) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002922 String arg = shell.getNextArg();
2923 if (arg == null || "all".equals(arg)) {
2924 pw.println(mDeepEnabled && mLightEnabled ? "1" : 0);
2925 } else if ("deep".equals(arg)) {
2926 pw.println(mDeepEnabled ? "1" : 0);
2927 } else if ("light".equals(arg)) {
2928 pw.println(mLightEnabled ? "1" : 0);
2929 } else {
2930 pw.println("Unknown idle mode: " + arg);
2931 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002932 }
2933 } else if ("whitelist".equals(cmd)) {
Dianne Hackborneb909e32016-09-29 14:35:15 -07002934 String arg = shell.getNextArg();
2935 if (arg != null) {
2936 getContext().enforceCallingOrSelfPermission(
2937 android.Manifest.permission.DEVICE_POWER, null);
2938 long token = Binder.clearCallingIdentity();
2939 try {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002940 do {
2941 if (arg.length() < 1 || (arg.charAt(0) != '-'
Felipe Lemef8a46232016-02-10 13:51:54 -08002942 && arg.charAt(0) != '+' && arg.charAt(0) != '=')) {
2943 pw.println("Package must be prefixed with +, -, or =: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002944 return -1;
2945 }
2946 char op = arg.charAt(0);
2947 String pkg = arg.substring(1);
2948 if (op == '+') {
2949 if (addPowerSaveWhitelistAppInternal(pkg)) {
2950 pw.println("Added: " + pkg);
2951 } else {
2952 pw.println("Unknown package: " + pkg);
2953 }
Felipe Lemef8a46232016-02-10 13:51:54 -08002954 } else if (op == '-') {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002955 if (removePowerSaveWhitelistAppInternal(pkg)) {
2956 pw.println("Removed: " + pkg);
2957 }
Felipe Lemef8a46232016-02-10 13:51:54 -08002958 } else {
2959 pw.println(getPowerSaveWhitelistAppInternal(pkg));
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002960 }
2961 } while ((arg=shell.getNextArg()) != null);
Dianne Hackborneb909e32016-09-29 14:35:15 -07002962 } finally {
2963 Binder.restoreCallingIdentity(token);
2964 }
2965 } else {
2966 synchronized (this) {
2967 for (int j=0; j<mPowerSaveWhitelistAppsExceptIdle.size(); j++) {
2968 pw.print("system-excidle,");
2969 pw.print(mPowerSaveWhitelistAppsExceptIdle.keyAt(j));
2970 pw.print(",");
2971 pw.println(mPowerSaveWhitelistAppsExceptIdle.valueAt(j));
2972 }
2973 for (int j=0; j<mPowerSaveWhitelistApps.size(); j++) {
2974 pw.print("system,");
2975 pw.print(mPowerSaveWhitelistApps.keyAt(j));
2976 pw.print(",");
2977 pw.println(mPowerSaveWhitelistApps.valueAt(j));
2978 }
2979 for (int j=0; j<mPowerSaveWhitelistUserApps.size(); j++) {
2980 pw.print("user,");
2981 pw.print(mPowerSaveWhitelistUserApps.keyAt(j));
2982 pw.print(",");
2983 pw.println(mPowerSaveWhitelistUserApps.valueAt(j));
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002984 }
2985 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002986 }
2987 } else if ("tempwhitelist".equals(cmd)) {
Dianne Hackborn85e35642017-01-12 15:10:57 -08002988 long duration = 10000;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002989 String opt;
2990 while ((opt=shell.getNextOption()) != null) {
2991 if ("-u".equals(opt)) {
2992 opt = shell.getNextArg();
2993 if (opt == null) {
2994 pw.println("-u requires a user number");
2995 return -1;
2996 }
2997 shell.userId = Integer.parseInt(opt);
Dianne Hackborn85e35642017-01-12 15:10:57 -08002998 } else if ("-d".equals(opt)) {
2999 opt = shell.getNextArg();
3000 if (opt == null) {
3001 pw.println("-d requires a duration");
3002 return -1;
3003 }
3004 duration = Long.parseLong(opt);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003005 }
3006 }
3007 String arg = shell.getNextArg();
3008 if (arg != null) {
3009 try {
Dianne Hackborn85e35642017-01-12 15:10:57 -08003010 addPowerSaveTempWhitelistAppChecked(arg, duration, shell.userId, "shell");
Christopher Tateec3a9f32017-03-21 17:43:47 -07003011 } catch (Exception e) {
3012 pw.println("Failed: " + e);
3013 return -1;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003014 }
3015 } else {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003016 dumpTempWhitelistSchedule(pw, false);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003017 }
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07003018 } else if ("except-idle-whitelist".equals(cmd)) {
3019 getContext().enforceCallingOrSelfPermission(
3020 android.Manifest.permission.DEVICE_POWER, null);
3021 final long token = Binder.clearCallingIdentity();
3022 try {
3023 String arg = shell.getNextArg();
3024 if (arg == null) {
3025 pw.println("No arguments given");
3026 return -1;
3027 } else if ("reset".equals(arg)) {
3028 resetPowerSaveWhitelistExceptIdleInternal();
3029 } else {
3030 do {
3031 if (arg.length() < 1 || (arg.charAt(0) != '-'
3032 && arg.charAt(0) != '+' && arg.charAt(0) != '=')) {
3033 pw.println("Package must be prefixed with +, -, or =: " + arg);
3034 return -1;
3035 }
3036 char op = arg.charAt(0);
3037 String pkg = arg.substring(1);
3038 if (op == '+') {
3039 if (addPowerSaveWhitelistExceptIdleInternal(pkg)) {
3040 pw.println("Added: " + pkg);
3041 } else {
3042 pw.println("Unknown package: " + pkg);
3043 }
3044 } else if (op == '=') {
3045 pw.println(getPowerSaveWhitelistExceptIdleInternal(pkg));
3046 } else {
3047 pw.println("Unknown argument: " + arg);
3048 return -1;
3049 }
3050 } while ((arg = shell.getNextArg()) != null);
3051 }
3052 } finally {
3053 Binder.restoreCallingIdentity(token);
3054 }
Suprabh Shukla08105642017-09-26 14:45:30 -07003055 } else if ("sys-whitelist".equals(cmd)) {
3056 String arg = shell.getNextArg();
3057 if (arg != null) {
3058 getContext().enforceCallingOrSelfPermission(
3059 android.Manifest.permission.DEVICE_POWER, null);
3060 final long token = Binder.clearCallingIdentity();
3061 try {
3062 if ("reset".equals(arg)) {
3063 resetSystemPowerWhitelistInternal();
3064 } else {
3065 do {
3066 if (arg.length() < 1
3067 || (arg.charAt(0) != '-' && arg.charAt(0) != '+')) {
3068 pw.println("Package must be prefixed with + or - " + arg);
3069 return -1;
3070 }
3071 final char op = arg.charAt(0);
3072 final String pkg = arg.substring(1);
3073 switch (op) {
3074 case '+':
3075 if (restoreSystemPowerWhitelistAppInternal(pkg)) {
3076 pw.println("Restored " + pkg);
3077 }
3078 break;
3079 case '-':
3080 if (removeSystemPowerWhitelistAppInternal(pkg)) {
3081 pw.println("Removed " + pkg);
3082 }
3083 break;
3084 }
3085 } while ((arg = shell.getNextArg()) != null);
3086 }
3087 } finally {
3088 Binder.restoreCallingIdentity(token);
3089 }
3090 } else {
3091 synchronized (this) {
3092 for (int j=0; j<mPowerSaveWhitelistApps.size(); j++) {
3093 pw.print(mPowerSaveWhitelistApps.keyAt(j));
3094 pw.print(",");
3095 pw.println(mPowerSaveWhitelistApps.valueAt(j));
3096 }
3097 }
3098 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003099 } else {
3100 return shell.handleDefaultCommands(cmd);
3101 }
3102 return 0;
3103 }
3104
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003105 void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003106 if (!DumpUtils.checkDumpPermission(getContext(), TAG, pw)) return;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003107
3108 if (args != null) {
Xiaohui Chen7c696362015-09-16 09:56:14 -07003109 int userId = UserHandle.USER_SYSTEM;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003110 for (int i=0; i<args.length; i++) {
3111 String arg = args[i];
3112 if ("-h".equals(arg)) {
3113 dumpHelp(pw);
3114 return;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003115 } else if ("-u".equals(arg)) {
3116 i++;
3117 if (i < args.length) {
3118 arg = args[i];
3119 userId = Integer.parseInt(arg);
3120 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003121 } else if ("-a".equals(arg)) {
3122 // Ignore, we always dump all.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003123 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
3124 pw.println("Unknown option: " + arg);
3125 return;
3126 } else {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003127 Shell shell = new Shell();
3128 shell.userId = userId;
3129 String[] newArgs = new String[args.length-i];
3130 System.arraycopy(args, i, newArgs, 0, args.length-i);
Dianne Hackborn354736e2016-08-22 17:00:05 -07003131 shell.exec(mBinderService, null, fd, null, newArgs, null,
3132 new ResultReceiver(null));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003133 return;
3134 }
3135 }
3136 }
3137
3138 synchronized (this) {
Dianne Hackborna750a632015-06-16 17:18:23 -07003139 mConstants.dump(pw);
3140
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08003141 if (mEventCmds[0] != EVENT_NULL) {
3142 pw.println(" Idling history:");
3143 long now = SystemClock.elapsedRealtime();
3144 for (int i=EVENT_BUFFER_SIZE-1; i>=0; i--) {
3145 int cmd = mEventCmds[i];
3146 if (cmd == EVENT_NULL) {
3147 continue;
3148 }
3149 String label;
3150 switch (mEventCmds[i]) {
3151 case EVENT_NORMAL: label = " normal"; break;
3152 case EVENT_LIGHT_IDLE: label = " light-idle"; break;
3153 case EVENT_LIGHT_MAINTENANCE: label = "light-maint"; break;
Dianne Hackbornb6843652016-02-22 12:20:13 -08003154 case EVENT_DEEP_IDLE: label = " deep-idle"; break;
3155 case EVENT_DEEP_MAINTENANCE: label = " deep-maint"; break;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08003156 default: label = " ??"; break;
3157 }
3158 pw.print(" ");
3159 pw.print(label);
3160 pw.print(": ");
3161 TimeUtils.formatDuration(mEventTimes[i], now, pw);;
3162 pw.println();
3163 }
3164 }
3165
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003166 int size = mPowerSaveWhitelistAppsExceptIdle.size();
3167 if (size > 0) {
3168 pw.println(" Whitelist (except idle) system apps:");
3169 for (int i = 0; i < size; i++) {
3170 pw.print(" ");
3171 pw.println(mPowerSaveWhitelistAppsExceptIdle.keyAt(i));
3172 }
3173 }
3174 size = mPowerSaveWhitelistApps.size();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003175 if (size > 0) {
3176 pw.println(" Whitelist system apps:");
3177 for (int i = 0; i < size; i++) {
3178 pw.print(" ");
3179 pw.println(mPowerSaveWhitelistApps.keyAt(i));
3180 }
3181 }
Suprabh Shukla08105642017-09-26 14:45:30 -07003182 size = mRemovedFromSystemWhitelistApps.size();
3183 if (size > 0) {
3184 pw.println(" Removed from whitelist system apps:");
3185 for (int i = 0; i < size; i++) {
3186 pw.print(" ");
3187 pw.println(mRemovedFromSystemWhitelistApps.keyAt(i));
3188 }
3189 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003190 size = mPowerSaveWhitelistUserApps.size();
3191 if (size > 0) {
3192 pw.println(" Whitelist user apps:");
3193 for (int i = 0; i < size; i++) {
3194 pw.print(" ");
3195 pw.println(mPowerSaveWhitelistUserApps.keyAt(i));
3196 }
3197 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003198 size = mPowerSaveWhitelistExceptIdleAppIds.size();
3199 if (size > 0) {
3200 pw.println(" Whitelist (except idle) all app ids:");
3201 for (int i = 0; i < size; i++) {
3202 pw.print(" ");
3203 pw.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
3204 pw.println();
3205 }
3206 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08003207 size = mPowerSaveWhitelistUserAppIds.size();
3208 if (size > 0) {
3209 pw.println(" Whitelist user app ids:");
3210 for (int i = 0; i < size; i++) {
3211 pw.print(" ");
3212 pw.print(mPowerSaveWhitelistUserAppIds.keyAt(i));
3213 pw.println();
3214 }
3215 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07003216 size = mPowerSaveWhitelistAllAppIds.size();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003217 if (size > 0) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07003218 pw.println(" Whitelist all app ids:");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003219 for (int i = 0; i < size; i++) {
Dianne Hackborna750a632015-06-16 17:18:23 -07003220 pw.print(" ");
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07003221 pw.print(mPowerSaveWhitelistAllAppIds.keyAt(i));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003222 pw.println();
3223 }
3224 }
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003225 dumpTempWhitelistSchedule(pw, true);
3226
Dianne Hackborna750a632015-06-16 17:18:23 -07003227 size = mTempWhitelistAppIdArray != null ? mTempWhitelistAppIdArray.length : 0;
3228 if (size > 0) {
3229 pw.println(" Temp whitelist app ids:");
3230 for (int i = 0; i < size; i++) {
3231 pw.print(" ");
3232 pw.print(mTempWhitelistAppIdArray[i]);
3233 pw.println();
3234 }
3235 }
Adam Lesinski31c05d12015-06-09 17:34:04 -07003236
Dianne Hackbornb6843652016-02-22 12:20:13 -08003237 pw.print(" mLightEnabled="); pw.print(mLightEnabled);
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003238 pw.print(" mDeepEnabled="); pw.println(mDeepEnabled);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003239 pw.print(" mForceIdle="); pw.println(mForceIdle);
Nick Vaccaro20feaea2015-09-17 17:22:44 -07003240 pw.print(" mMotionSensor="); pw.println(mMotionSensor);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003241 pw.print(" mScreenOn="); pw.println(mScreenOn);
Dianne Hackborn88c41352016-04-07 15:18:58 -07003242 pw.print(" mNetworkConnected="); pw.println(mNetworkConnected);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003243 pw.print(" mCharging="); pw.println(mCharging);
Nick Vaccaro20feaea2015-09-17 17:22:44 -07003244 pw.print(" mMotionActive="); pw.println(mMotionListener.active);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003245 pw.print(" mNotMoving="); pw.println(mNotMoving);
Joe LaPenna23d681b2015-08-27 15:12:11 -07003246 pw.print(" mLocating="); pw.print(mLocating); pw.print(" mHasGps=");
3247 pw.print(mHasGps); pw.print(" mHasNetwork=");
3248 pw.print(mHasNetworkLocation); pw.print(" mLocated="); pw.println(mLocated);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07003249 if (mLastGenericLocation != null) {
3250 pw.print(" mLastGenericLocation="); pw.println(mLastGenericLocation);
3251 }
3252 if (mLastGpsLocation != null) {
3253 pw.print(" mLastGpsLocation="); pw.println(mLastGpsLocation);
3254 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003255 pw.print(" mState="); pw.print(stateToString(mState));
3256 pw.print(" mLightState=");
3257 pw.println(lightStateToString(mLightState));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003258 pw.print(" mInactiveTimeout="); TimeUtils.formatDuration(mInactiveTimeout, pw);
3259 pw.println();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003260 if (mActiveIdleOpCount != 0) {
3261 pw.print(" mActiveIdleOpCount="); pw.println(mActiveIdleOpCount);
3262 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003263 if (mNextAlarmTime != 0) {
3264 pw.print(" mNextAlarmTime=");
3265 TimeUtils.formatDuration(mNextAlarmTime, SystemClock.elapsedRealtime(), pw);
3266 pw.println();
3267 }
3268 if (mNextIdlePendingDelay != 0) {
3269 pw.print(" mNextIdlePendingDelay=");
3270 TimeUtils.formatDuration(mNextIdlePendingDelay, pw);
3271 pw.println();
3272 }
3273 if (mNextIdleDelay != 0) {
3274 pw.print(" mNextIdleDelay=");
3275 TimeUtils.formatDuration(mNextIdleDelay, pw);
3276 pw.println();
3277 }
Dianne Hackborn953fc942016-03-29 15:36:24 -07003278 if (mNextLightIdleDelay != 0) {
3279 pw.print(" mNextIdleDelay=");
3280 TimeUtils.formatDuration(mNextLightIdleDelay, pw);
3281 pw.println();
3282 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003283 if (mNextLightAlarmTime != 0) {
3284 pw.print(" mNextLightAlarmTime=");
3285 TimeUtils.formatDuration(mNextLightAlarmTime, SystemClock.elapsedRealtime(), pw);
3286 pw.println();
3287 }
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08003288 if (mCurIdleBudget != 0) {
3289 pw.print(" mCurIdleBudget=");
3290 TimeUtils.formatDuration(mCurIdleBudget, pw);
3291 pw.println();
3292 }
3293 if (mMaintenanceStartTime != 0) {
3294 pw.print(" mMaintenanceStartTime=");
3295 TimeUtils.formatDuration(mMaintenanceStartTime, SystemClock.elapsedRealtime(), pw);
3296 pw.println();
3297 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003298 if (mJobsActive) {
3299 pw.print(" mJobsActive="); pw.println(mJobsActive);
3300 }
3301 if (mAlarmsActive) {
3302 pw.print(" mAlarmsActive="); pw.println(mAlarmsActive);
3303 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003304 }
3305 }
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003306
3307 void dumpTempWhitelistSchedule(PrintWriter pw, boolean printTitle) {
3308 final int size = mTempWhitelistAppIdEndTimes.size();
3309 if (size > 0) {
3310 String prefix = "";
3311 if (printTitle) {
3312 pw.println(" Temp whitelist schedule:");
3313 prefix = " ";
3314 }
3315 final long timeNow = SystemClock.elapsedRealtime();
3316 for (int i = 0; i < size; i++) {
3317 pw.print(prefix);
3318 pw.print("UID=");
3319 pw.print(mTempWhitelistAppIdEndTimes.keyAt(i));
3320 pw.print(": ");
3321 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.valueAt(i);
3322 TimeUtils.formatDuration(entry.first.value, timeNow, pw);
3323 pw.print(" - ");
3324 pw.println(entry.second);
3325 }
3326 }
3327 }
3328 }