blob: 4f1e335a2d508c5d03b667ed3470a26e17eb95e6 [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
Sudheer Shanka326b3112017-11-27 14:40:57 -080079import com.android.internal.annotations.GuardedBy;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070080import com.android.internal.app.IBatteryStats;
81import com.android.internal.os.AtomicFile;
82import com.android.internal.os.BackgroundThread;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060083import com.android.internal.util.DumpUtils;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070084import com.android.internal.util.FastXmlSerializer;
85import com.android.internal.util.XmlUtils;
86import com.android.server.am.BatteryStatsService;
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -070087import com.android.server.net.NetworkPolicyManagerInternal;
Amith Yamasani520d8f22015-05-08 16:36:21 -070088
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070089import org.xmlpull.v1.XmlPullParser;
90import org.xmlpull.v1.XmlPullParserException;
91import org.xmlpull.v1.XmlSerializer;
92
93import java.io.ByteArrayOutputStream;
94import java.io.File;
95import java.io.FileDescriptor;
96import java.io.FileInputStream;
97import java.io.FileNotFoundException;
98import java.io.FileOutputStream;
99import java.io.IOException;
100import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100101import java.nio.charset.StandardCharsets;
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700102import java.util.Arrays;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700103
104/**
105 * Keeps track of device idleness and drives low power mode based on that.
106 */
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700107public class DeviceIdleController extends SystemService
108 implements AnyMotionDetector.DeviceIdleCallback {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700109 private static final String TAG = "DeviceIdleController";
110
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700111 private static final boolean DEBUG = false;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700112
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700113 private static final boolean COMPRESS_TIME = false;
Amith Yamasani520d8f22015-05-08 16:36:21 -0700114
Dianne Hackborn953fc942016-03-29 15:36:24 -0700115 private static final int EVENT_BUFFER_SIZE = 100;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800116
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700117 private AlarmManager mAlarmManager;
118 private IBatteryStats mBatteryStats;
Dianne Hackborn85e35642017-01-12 15:10:57 -0800119 private ActivityManagerInternal mLocalActivityManager;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700120 private PowerManagerInternal mLocalPowerManager;
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700121 private PowerManager mPowerManager;
Dianne Hackborn88c41352016-04-07 15:18:58 -0700122 private ConnectivityService mConnectivityService;
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 Hackborn0b4daca2015-04-27 09:47:32 -07001438 mNetworkPolicyManager = INetworkPolicyManager.Stub.asInterface(
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001439 ServiceManager.getService(Context.NETWORK_POLICY_SERVICE));
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001440 mNetworkPolicyManagerInternal = getLocalService(NetworkPolicyManagerInternal.class);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001441 mSensorManager = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001442 int sigMotionSensorId = getContext().getResources().getInteger(
1443 com.android.internal.R.integer.config_autoPowerModeAnyMotionSensor);
1444 if (sigMotionSensorId > 0) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001445 mMotionSensor = mSensorManager.getDefaultSensor(sigMotionSensorId, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001446 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001447 if (mMotionSensor == null && getContext().getResources().getBoolean(
Joe LaPenna23d681b2015-08-27 15:12:11 -07001448 com.android.internal.R.bool.config_autoPowerModePreferWristTilt)) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001449 mMotionSensor = mSensorManager.getDefaultSensor(
1450 Sensor.TYPE_WRIST_TILT_GESTURE, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001451 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001452 if (mMotionSensor == null) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07001453 // As a last ditch, fall back to SMD.
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001454 mMotionSensor = mSensorManager.getDefaultSensor(
1455 Sensor.TYPE_SIGNIFICANT_MOTION, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001456 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001457
Joe LaPenna23d681b2015-08-27 15:12:11 -07001458 if (getContext().getResources().getBoolean(
1459 com.android.internal.R.bool.config_autoPowerModePrefetchLocation)) {
1460 mLocationManager = (LocationManager) getContext().getSystemService(
1461 Context.LOCATION_SERVICE);
1462 mLocationRequest = new LocationRequest()
1463 .setQuality(LocationRequest.ACCURACY_FINE)
1464 .setInterval(0)
1465 .setFastestInterval(0)
1466 .setNumUpdates(1);
1467 }
1468
1469 float angleThreshold = getContext().getResources().getInteger(
1470 com.android.internal.R.integer.config_autoPowerModeThresholdAngle) / 100f;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001471 mAnyMotionDetector = new AnyMotionDetector(
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001472 (PowerManager) getContext().getSystemService(Context.POWER_SERVICE),
Joe LaPenna23d681b2015-08-27 15:12:11 -07001473 mHandler, mSensorManager, this, angleThreshold);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001474
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001475 mIdleIntent = new Intent(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001476 mIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1477 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001478 mLightIdleIntent = new Intent(PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED);
1479 mLightIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1480 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001481
1482 IntentFilter filter = new IntentFilter();
1483 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001484 getContext().registerReceiver(mReceiver, filter);
Amith Yamasaniac59f75e2016-05-05 12:38:17 -07001485
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001486 filter = new IntentFilter();
1487 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1488 filter.addDataScheme("package");
Amith Yamasaniac59f75e2016-05-05 12:38:17 -07001489 getContext().registerReceiver(mReceiver, filter);
1490
Dianne Hackborn88c41352016-04-07 15:18:58 -07001491 filter = new IntentFilter();
1492 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001493 getContext().registerReceiver(mReceiver, filter);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001494
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -07001495 filter = new IntentFilter();
1496 filter.addAction(Intent.ACTION_SCREEN_OFF);
1497 filter.addAction(Intent.ACTION_SCREEN_ON);
1498 getContext().registerReceiver(mInteractivityReceiver, filter);
1499
Dianne Hackborn85e35642017-01-12 15:10:57 -08001500 mLocalActivityManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001501 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -07001502
Makoto Onuki2206af32017-11-21 16:25:35 -08001503 passWhiteListToForceAppStandbyTrackerLocked();
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -07001504 updateInteractivityLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001505 }
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -07001506 updateConnectivityState(null);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001507 }
1508 }
1509
1510 public boolean addPowerSaveWhitelistAppInternal(String name) {
1511 synchronized (this) {
1512 try {
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001513 ApplicationInfo ai = getContext().getPackageManager().getApplicationInfo(name,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07001514 PackageManager.MATCH_ANY_USER);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001515 if (mPowerSaveWhitelistUserApps.put(name, UserHandle.getAppId(ai.uid)) == null) {
1516 reportPowerSaveWhitelistChangedLocked();
1517 updateWhitelistAppIdsLocked();
1518 writeConfigFileLocked();
1519 }
1520 return true;
1521 } catch (PackageManager.NameNotFoundException e) {
1522 return false;
1523 }
1524 }
1525 }
1526
1527 public boolean removePowerSaveWhitelistAppInternal(String name) {
1528 synchronized (this) {
1529 if (mPowerSaveWhitelistUserApps.remove(name) != null) {
1530 reportPowerSaveWhitelistChangedLocked();
1531 updateWhitelistAppIdsLocked();
1532 writeConfigFileLocked();
1533 return true;
1534 }
1535 }
1536 return false;
1537 }
1538
Felipe Lemef8a46232016-02-10 13:51:54 -08001539 public boolean getPowerSaveWhitelistAppInternal(String name) {
1540 synchronized (this) {
1541 return mPowerSaveWhitelistUserApps.containsKey(name);
1542 }
1543 }
1544
Suprabh Shukla08105642017-09-26 14:45:30 -07001545 void resetSystemPowerWhitelistInternal() {
1546 synchronized (this) {
1547 mPowerSaveWhitelistApps.putAll(mRemovedFromSystemWhitelistApps);
1548 mRemovedFromSystemWhitelistApps.clear();
1549 reportPowerSaveWhitelistChangedLocked();
1550 updateWhitelistAppIdsLocked();
1551 writeConfigFileLocked();
1552 }
1553 }
1554
1555 public boolean restoreSystemPowerWhitelistAppInternal(String name) {
1556 synchronized (this) {
1557 if (!mRemovedFromSystemWhitelistApps.containsKey(name)) {
1558 return false;
1559 }
1560 mPowerSaveWhitelistApps.put(name, mRemovedFromSystemWhitelistApps.remove(name));
1561 reportPowerSaveWhitelistChangedLocked();
1562 updateWhitelistAppIdsLocked();
1563 writeConfigFileLocked();
1564 return true;
1565 }
1566 }
1567
1568 public boolean removeSystemPowerWhitelistAppInternal(String name) {
1569 synchronized (this) {
1570 if (!mPowerSaveWhitelistApps.containsKey(name)) {
1571 return false;
1572 }
1573 mRemovedFromSystemWhitelistApps.put(name, mPowerSaveWhitelistApps.remove(name));
1574 reportPowerSaveWhitelistChangedLocked();
1575 updateWhitelistAppIdsLocked();
1576 writeConfigFileLocked();
1577 return true;
1578 }
1579 }
1580
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07001581 public boolean addPowerSaveWhitelistExceptIdleInternal(String name) {
1582 synchronized (this) {
1583 try {
1584 final ApplicationInfo ai = getContext().getPackageManager().getApplicationInfo(name,
1585 PackageManager.MATCH_ANY_USER);
1586 if (mPowerSaveWhitelistAppsExceptIdle.put(name, UserHandle.getAppId(ai.uid))
1587 == null) {
1588 mPowerSaveWhitelistUserAppsExceptIdle.add(name);
1589 reportPowerSaveWhitelistChangedLocked();
1590 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(
1591 mPowerSaveWhitelistAppsExceptIdle, mPowerSaveWhitelistUserApps,
1592 mPowerSaveWhitelistExceptIdleAppIds);
1593 }
1594 return true;
1595 } catch (PackageManager.NameNotFoundException e) {
1596 return false;
1597 }
1598 }
1599 }
1600
1601 public void resetPowerSaveWhitelistExceptIdleInternal() {
1602 synchronized (this) {
1603 if (mPowerSaveWhitelistAppsExceptIdle.removeAll(
1604 mPowerSaveWhitelistUserAppsExceptIdle)) {
1605 reportPowerSaveWhitelistChangedLocked();
1606 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(
1607 mPowerSaveWhitelistAppsExceptIdle, mPowerSaveWhitelistUserApps,
1608 mPowerSaveWhitelistExceptIdleAppIds);
1609 mPowerSaveWhitelistUserAppsExceptIdle.clear();
1610 }
1611 }
1612 }
1613
1614 public boolean getPowerSaveWhitelistExceptIdleInternal(String name) {
1615 synchronized (this) {
1616 return mPowerSaveWhitelistAppsExceptIdle.containsKey(name);
1617 }
1618 }
1619
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001620 public String[] getSystemPowerWhitelistExceptIdleInternal() {
1621 synchronized (this) {
1622 int size = mPowerSaveWhitelistAppsExceptIdle.size();
1623 String[] apps = new String[size];
1624 for (int i = 0; i < size; i++) {
1625 apps[i] = mPowerSaveWhitelistAppsExceptIdle.keyAt(i);
1626 }
1627 return apps;
1628 }
1629 }
1630
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001631 public String[] getSystemPowerWhitelistInternal() {
1632 synchronized (this) {
1633 int size = mPowerSaveWhitelistApps.size();
1634 String[] apps = new String[size];
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001635 for (int i = 0; i < size; i++) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001636 apps[i] = mPowerSaveWhitelistApps.keyAt(i);
1637 }
1638 return apps;
1639 }
1640 }
1641
Suprabh Shukla08105642017-09-26 14:45:30 -07001642 public String[] getRemovedSystemPowerWhitelistAppsInternal() {
1643 synchronized (this) {
1644 int size = mRemovedFromSystemWhitelistApps.size();
1645 final String[] apps = new String[size];
1646 for (int i = 0; i < size; i++) {
1647 apps[i] = mRemovedFromSystemWhitelistApps.keyAt(i);
1648 }
1649 return apps;
1650 }
1651 }
1652
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001653 public String[] getUserPowerWhitelistInternal() {
1654 synchronized (this) {
1655 int size = mPowerSaveWhitelistUserApps.size();
1656 String[] apps = new String[size];
1657 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1658 apps[i] = mPowerSaveWhitelistUserApps.keyAt(i);
1659 }
1660 return apps;
1661 }
1662 }
1663
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001664 public String[] getFullPowerWhitelistExceptIdleInternal() {
1665 synchronized (this) {
1666 int size = mPowerSaveWhitelistAppsExceptIdle.size() + mPowerSaveWhitelistUserApps.size();
1667 String[] apps = new String[size];
1668 int cur = 0;
1669 for (int i = 0; i < mPowerSaveWhitelistAppsExceptIdle.size(); i++) {
1670 apps[cur] = mPowerSaveWhitelistAppsExceptIdle.keyAt(i);
1671 cur++;
1672 }
1673 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1674 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
1675 cur++;
1676 }
1677 return apps;
1678 }
1679 }
1680
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001681 public String[] getFullPowerWhitelistInternal() {
1682 synchronized (this) {
1683 int size = mPowerSaveWhitelistApps.size() + mPowerSaveWhitelistUserApps.size();
1684 String[] apps = new String[size];
1685 int cur = 0;
1686 for (int i = 0; i < mPowerSaveWhitelistApps.size(); i++) {
1687 apps[cur] = mPowerSaveWhitelistApps.keyAt(i);
1688 cur++;
1689 }
1690 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1691 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
1692 cur++;
1693 }
1694 return apps;
1695 }
1696 }
1697
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001698 public boolean isPowerSaveWhitelistExceptIdleAppInternal(String packageName) {
1699 synchronized (this) {
1700 return mPowerSaveWhitelistAppsExceptIdle.containsKey(packageName)
1701 || mPowerSaveWhitelistUserApps.containsKey(packageName);
1702 }
1703 }
1704
Amith Yamasani06bf8242015-05-08 16:36:21 -07001705 public boolean isPowerSaveWhitelistAppInternal(String packageName) {
1706 synchronized (this) {
1707 return mPowerSaveWhitelistApps.containsKey(packageName)
1708 || mPowerSaveWhitelistUserApps.containsKey(packageName);
1709 }
1710 }
1711
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001712 public int[] getAppIdWhitelistExceptIdleInternal() {
1713 synchronized (this) {
1714 return mPowerSaveWhitelistExceptIdleAppIdArray;
1715 }
1716 }
1717
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001718 public int[] getAppIdWhitelistInternal() {
1719 synchronized (this) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001720 return mPowerSaveWhitelistAllAppIdArray;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001721 }
1722 }
1723
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001724 public int[] getAppIdUserWhitelistInternal() {
1725 synchronized (this) {
1726 return mPowerSaveWhitelistUserAppIdArray;
1727 }
1728 }
1729
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001730 public int[] getAppIdTempWhitelistInternal() {
1731 synchronized (this) {
1732 return mTempWhitelistAppIdArray;
1733 }
1734 }
1735
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001736 void addPowerSaveTempWhitelistAppChecked(String packageName, long duration,
1737 int userId, String reason) throws RemoteException {
1738 getContext().enforceCallingPermission(
1739 Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
1740 "No permission to change device idle whitelist");
1741 final int callingUid = Binder.getCallingUid();
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001742 userId = ActivityManager.getService().handleIncomingUser(
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001743 Binder.getCallingPid(),
1744 callingUid,
1745 userId,
1746 /*allowAll=*/ false,
1747 /*requireFull=*/ false,
1748 "addPowerSaveTempWhitelistApp", null);
1749 final long token = Binder.clearCallingIdentity();
1750 try {
1751 addPowerSaveTempWhitelistAppInternal(callingUid,
1752 packageName, duration, userId, true, reason);
1753 } finally {
1754 Binder.restoreCallingIdentity(token);
1755 }
1756 }
1757
Sudheer Shanka326b3112017-11-27 14:40:57 -08001758 void removePowerSaveTempWhitelistAppChecked(String packageName, int userId)
1759 throws RemoteException {
1760 getContext().enforceCallingPermission(
1761 Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
1762 "No permission to change device idle whitelist");
1763 final int callingUid = Binder.getCallingUid();
1764 userId = ActivityManager.getService().handleIncomingUser(
1765 Binder.getCallingPid(),
1766 callingUid,
1767 userId,
1768 /*allowAll=*/ false,
1769 /*requireFull=*/ false,
1770 "removePowerSaveTempWhitelistApp", null);
1771 final long token = Binder.clearCallingIdentity();
1772 try {
1773 removePowerSaveTempWhitelistAppInternal(packageName, userId);
1774 } finally {
1775 Binder.restoreCallingIdentity(token);
1776 }
1777 }
1778
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001779 /**
1780 * Adds an app to the temporary whitelist and resets the endTime for granting the
1781 * app an exemption to access network and acquire wakelocks.
1782 */
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001783 void addPowerSaveTempWhitelistAppInternal(int callingUid, String packageName,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001784 long duration, int userId, boolean sync, String reason) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001785 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001786 int uid = getContext().getPackageManager().getPackageUidAsUser(packageName, userId);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001787 int appId = UserHandle.getAppId(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001788 addPowerSaveTempWhitelistAppDirectInternal(callingUid, appId, duration, sync, reason);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001789 } catch (NameNotFoundException e) {
1790 }
1791 }
1792
Dianne Hackborna750a632015-06-16 17:18:23 -07001793 /**
1794 * Adds an app to the temporary whitelist and resets the endTime for granting the
1795 * app an exemption to access network and acquire wakelocks.
1796 */
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001797 void addPowerSaveTempWhitelistAppDirectInternal(int callingUid, int appId,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001798 long duration, boolean sync, String reason) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001799 final long timeNow = SystemClock.elapsedRealtime();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001800 boolean informWhitelistChanged = false;
Dianne Hackborna750a632015-06-16 17:18:23 -07001801 synchronized (this) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001802 int callingAppId = UserHandle.getAppId(callingUid);
1803 if (callingAppId >= Process.FIRST_APPLICATION_UID) {
1804 if (!mPowerSaveWhitelistSystemAppIds.get(callingAppId)) {
1805 throw new SecurityException("Calling app " + UserHandle.formatUid(callingUid)
1806 + " is not on whitelist");
1807 }
1808 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001809 duration = Math.min(duration, mConstants.MAX_TEMP_APP_WHITELIST_DURATION);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001810 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.get(appId);
1811 final boolean newEntry = entry == null;
Dianne Hackborna750a632015-06-16 17:18:23 -07001812 // Set the new end time
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001813 if (newEntry) {
1814 entry = new Pair<>(new MutableLong(0), reason);
1815 mTempWhitelistAppIdEndTimes.put(appId, entry);
1816 }
1817 entry.first.value = timeNow + duration;
Dianne Hackborna750a632015-06-16 17:18:23 -07001818 if (DEBUG) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001819 Slog.d(TAG, "Adding AppId " + appId + " to temp whitelist. New entry: " + newEntry);
Dianne Hackborna750a632015-06-16 17:18:23 -07001820 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001821 if (newEntry) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001822 // No pending timeout for the app id, post a delayed message
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001823 try {
1824 mBatteryStats.noteEvent(BatteryStats.HistoryItem.EVENT_TEMP_WHITELIST_START,
1825 reason, appId);
1826 } catch (RemoteException e) {
1827 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001828 postTempActiveTimeoutMessage(appId, duration);
Dianne Hackborn85e35642017-01-12 15:10:57 -08001829 updateTempWhitelistAppIdsLocked(appId, true);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001830 if (sync) {
1831 informWhitelistChanged = true;
1832 } else {
1833 mHandler.obtainMessage(MSG_REPORT_TEMP_APP_WHITELIST_CHANGED, appId, 1)
1834 .sendToTarget();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001835 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001836 reportTempWhitelistChangedLocked();
1837 }
1838 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001839 if (informWhitelistChanged) {
1840 mNetworkPolicyManagerInternal.onTempPowerSaveWhitelistChange(appId, true);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001841 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001842 }
1843
Sudheer Shanka326b3112017-11-27 14:40:57 -08001844 /**
1845 * Removes an app from the temporary whitelist and notifies the observers.
1846 */
1847 private void removePowerSaveTempWhitelistAppInternal(String packageName, int userId) {
1848 try {
1849 final int uid = getContext().getPackageManager().getPackageUidAsUser(
1850 packageName, userId);
1851 final int appId = UserHandle.getAppId(uid);
1852 removePowerSaveTempWhitelistAppDirectInternal(appId);
1853 } catch (NameNotFoundException e) {
1854 }
1855 }
1856
1857 private void removePowerSaveTempWhitelistAppDirectInternal(int appId) {
1858 synchronized (this) {
1859 final int idx = mTempWhitelistAppIdEndTimes.indexOfKey(appId);
1860 if (idx < 0) {
1861 // Nothing else to do
1862 return;
1863 }
1864 final String reason = mTempWhitelistAppIdEndTimes.valueAt(idx).second;
1865 mTempWhitelistAppIdEndTimes.removeAt(idx);
1866 onAppRemovedFromTempWhitelistLocked(appId, reason);
1867 }
1868 }
1869
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001870 private void postTempActiveTimeoutMessage(int uid, long delay) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001871 if (DEBUG) {
1872 Slog.d(TAG, "postTempActiveTimeoutMessage: uid=" + uid + ", delay=" + delay);
1873 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001874 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_TEMP_APP_WHITELIST_TIMEOUT, uid, 0),
1875 delay);
1876 }
1877
1878 void checkTempAppWhitelistTimeout(int uid) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001879 final long timeNow = SystemClock.elapsedRealtime();
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001880 if (DEBUG) {
1881 Slog.d(TAG, "checkTempAppWhitelistTimeout: uid=" + uid + ", timeNow=" + timeNow);
1882 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001883 synchronized (this) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001884 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.get(uid);
1885 if (entry == null) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001886 // Nothing to do
1887 return;
1888 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001889 if (timeNow >= entry.first.value) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001890 mTempWhitelistAppIdEndTimes.delete(uid);
Sudheer Shanka326b3112017-11-27 14:40:57 -08001891 onAppRemovedFromTempWhitelistLocked(uid, entry.second);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001892 } else {
1893 // Need more time
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001894 if (DEBUG) {
1895 Slog.d(TAG, "Time to remove UID " + uid + ": " + entry.first.value);
1896 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001897 postTempActiveTimeoutMessage(uid, entry.first.value - timeNow);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001898 }
1899 }
1900 }
1901
Sudheer Shanka326b3112017-11-27 14:40:57 -08001902 @GuardedBy("this")
1903 private void onAppRemovedFromTempWhitelistLocked(int appId, String reason) {
1904 if (DEBUG) {
1905 Slog.d(TAG, "Removing appId " + appId + " from temp whitelist");
1906 }
1907 updateTempWhitelistAppIdsLocked(appId, false);
1908 mHandler.obtainMessage(MSG_REPORT_TEMP_APP_WHITELIST_CHANGED, appId, 0)
1909 .sendToTarget();
1910 reportTempWhitelistChangedLocked();
1911 try {
1912 mBatteryStats.noteEvent(BatteryStats.HistoryItem.EVENT_TEMP_WHITELIST_FINISH,
1913 reason, appId);
1914 } catch (RemoteException e) {
1915 }
1916 }
1917
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001918 public void exitIdleInternal(String reason) {
1919 synchronized (this) {
1920 becomeActiveLocked(reason, Binder.getCallingUid());
1921 }
1922 }
1923
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -07001924 void updateConnectivityState(Intent connIntent) {
1925 ConnectivityService cm;
1926 synchronized (this) {
1927 cm = mConnectivityService;
1928 }
1929 if (cm == null) {
1930 return;
1931 }
1932 // Note: can't call out to ConnectivityService with our lock held.
1933 NetworkInfo ni = cm.getActiveNetworkInfo();
1934 synchronized (this) {
Dianne Hackborn88c41352016-04-07 15:18:58 -07001935 boolean conn;
1936 if (ni == null) {
1937 conn = false;
1938 } else {
1939 if (connIntent == null) {
1940 conn = ni.isConnected();
1941 } else {
1942 final int networkType =
1943 connIntent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1944 ConnectivityManager.TYPE_NONE);
1945 if (ni.getType() != networkType) {
1946 return;
1947 }
1948 conn = !connIntent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,
1949 false);
1950 }
1951 }
1952 if (conn != mNetworkConnected) {
1953 mNetworkConnected = conn;
1954 if (conn && mLightState == LIGHT_STATE_WAITING_FOR_NETWORK) {
1955 stepLightIdleStateLocked("network");
1956 }
1957 }
1958 }
1959 }
1960
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -07001961 void updateInteractivityLocked() {
1962 // The interactivity state from the power manager tells us whether the display is
1963 // in a state that we need to keep things running so they will update at a normal
1964 // frequency.
1965 boolean screenOn = mPowerManager.isInteractive();
1966 if (DEBUG) Slog.d(TAG, "updateInteractivityLocked: screenOn=" + screenOn);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001967 if (!screenOn && mScreenOn) {
1968 mScreenOn = false;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001969 if (!mForceIdle) {
1970 becomeInactiveIfAppropriateLocked();
1971 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001972 } else if (screenOn) {
1973 mScreenOn = true;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001974 if (!mForceIdle) {
1975 becomeActiveLocked("screen", Process.myUid());
1976 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001977 }
1978 }
1979
1980 void updateChargingLocked(boolean charging) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001981 if (DEBUG) Slog.i(TAG, "updateChargingLocked: charging=" + charging);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001982 if (!charging && mCharging) {
1983 mCharging = false;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001984 if (!mForceIdle) {
1985 becomeInactiveIfAppropriateLocked();
1986 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001987 } else if (charging) {
1988 mCharging = charging;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001989 if (!mForceIdle) {
1990 becomeActiveLocked("charging", Process.myUid());
1991 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001992 }
1993 }
1994
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001995 void scheduleReportActiveLocked(String activeReason, int activeUid) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001996 Message msg = mHandler.obtainMessage(MSG_REPORT_ACTIVE, activeUid, 0, activeReason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001997 mHandler.sendMessage(msg);
1998 }
1999
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002000 void becomeActiveLocked(String activeReason, int activeUid) {
2001 if (DEBUG) Slog.i(TAG, "becomeActiveLocked, reason = " + activeReason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002002 if (mState != STATE_ACTIVE || mLightState != STATE_ACTIVE) {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002003 EventLogTags.writeDeviceIdle(STATE_ACTIVE, activeReason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002004 EventLogTags.writeDeviceIdleLight(LIGHT_STATE_ACTIVE, activeReason);
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002005 scheduleReportActiveLocked(activeReason, activeUid);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002006 mState = STATE_ACTIVE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002007 mLightState = LIGHT_STATE_ACTIVE;
Adam Lesinski31c05d12015-06-09 17:34:04 -07002008 mInactiveTimeout = mConstants.INACTIVE_TIMEOUT;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002009 mCurIdleBudget = 0;
2010 mMaintenanceStartTime = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002011 resetIdleManagementLocked();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002012 resetLightIdleManagementLocked();
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002013 addEvent(EVENT_NORMAL);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002014 }
2015 }
2016
2017 void becomeInactiveIfAppropriateLocked() {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002018 if (DEBUG) Slog.d(TAG, "becomeInactiveIfAppropriateLocked()");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002019 if ((!mScreenOn && !mCharging) || mForceIdle) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002020 // Screen has turned off; we are now going to become inactive and start
2021 // waiting to see if we will ultimately go idle.
Dianne Hackbornb6843652016-02-22 12:20:13 -08002022 if (mState == STATE_ACTIVE && mDeepEnabled) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002023 mState = STATE_INACTIVE;
2024 if (DEBUG) Slog.d(TAG, "Moved from STATE_ACTIVE to STATE_INACTIVE");
2025 resetIdleManagementLocked();
2026 scheduleAlarmLocked(mInactiveTimeout, false);
2027 EventLogTags.writeDeviceIdle(mState, "no activity");
2028 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08002029 if (mLightState == LIGHT_STATE_ACTIVE && mLightEnabled) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002030 mLightState = LIGHT_STATE_INACTIVE;
2031 if (DEBUG) Slog.d(TAG, "Moved from LIGHT_STATE_ACTIVE to LIGHT_STATE_INACTIVE");
2032 resetLightIdleManagementLocked();
Dianne Hackborn953fc942016-03-29 15:36:24 -07002033 scheduleLightAlarmLocked(mConstants.LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002034 EventLogTags.writeDeviceIdleLight(mLightState, "no activity");
2035 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002036 }
2037 }
2038
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002039 void resetIdleManagementLocked() {
2040 mNextIdlePendingDelay = 0;
2041 mNextIdleDelay = 0;
Dianne Hackborn953fc942016-03-29 15:36:24 -07002042 mNextLightIdleDelay = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002043 cancelAlarmLocked();
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002044 cancelSensingTimeoutAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002045 cancelLocatingLocked();
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002046 stopMonitoringMotionLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002047 mAnyMotionDetector.stop();
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002048 }
2049
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002050 void resetLightIdleManagementLocked() {
2051 cancelLightAlarmLocked();
2052 }
2053
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002054 void exitForceIdleLocked() {
2055 if (mForceIdle) {
2056 mForceIdle = false;
2057 if (mScreenOn || mCharging) {
Dianne Hackborn88c41352016-04-07 15:18:58 -07002058 becomeActiveLocked("exit-force", Process.myUid());
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002059 }
2060 }
2061 }
2062
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002063 void stepLightIdleStateLocked(String reason) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002064 if (mLightState == LIGHT_STATE_OVERRIDE) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002065 // If we are already in deep device idle mode, then
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002066 // there is nothing left to do for light mode.
2067 return;
2068 }
2069
2070 if (DEBUG) Slog.d(TAG, "stepLightIdleStateLocked: mLightState=" + mLightState);
2071 EventLogTags.writeDeviceIdleLightStep();
2072
2073 switch (mLightState) {
2074 case LIGHT_STATE_INACTIVE:
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002075 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
Dianne Hackborn953fc942016-03-29 15:36:24 -07002076 // Reset the upcoming idle delays.
2077 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002078 mMaintenanceStartTime = 0;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002079 if (!isOpsInactiveLocked()) {
2080 // We have some active ops going on... give them a chance to finish
2081 // before going in to our first idle.
2082 mLightState = LIGHT_STATE_PRE_IDLE;
2083 EventLogTags.writeDeviceIdleLight(mLightState, reason);
2084 scheduleLightAlarmLocked(mConstants.LIGHT_PRE_IDLE_TIMEOUT);
2085 break;
2086 }
2087 // Nothing active, fall through to immediately idle.
2088 case LIGHT_STATE_PRE_IDLE:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002089 case LIGHT_STATE_IDLE_MAINTENANCE:
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002090 if (mMaintenanceStartTime != 0) {
2091 long duration = SystemClock.elapsedRealtime() - mMaintenanceStartTime;
2092 if (duration < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
2093 // We didn't use up all of our minimum budget; add this to the reserve.
2094 mCurIdleBudget += (mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET-duration);
2095 } else {
2096 // We used more than our minimum budget; this comes out of the reserve.
2097 mCurIdleBudget -= (duration-mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET);
2098 }
2099 }
2100 mMaintenanceStartTime = 0;
Dianne Hackborn953fc942016-03-29 15:36:24 -07002101 scheduleLightAlarmLocked(mNextLightIdleDelay);
2102 mNextLightIdleDelay = Math.min(mConstants.LIGHT_MAX_IDLE_TIMEOUT,
2103 (long)(mNextLightIdleDelay * mConstants.LIGHT_IDLE_FACTOR));
2104 if (mNextLightIdleDelay < mConstants.LIGHT_IDLE_TIMEOUT) {
2105 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
2106 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002107 if (DEBUG) Slog.d(TAG, "Moved to LIGHT_STATE_IDLE.");
2108 mLightState = LIGHT_STATE_IDLE;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002109 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002110 addEvent(EVENT_LIGHT_IDLE);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08002111 mGoingIdleWakeLock.acquire();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002112 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON_LIGHT);
2113 break;
2114 case LIGHT_STATE_IDLE:
Dianne Hackborn88c41352016-04-07 15:18:58 -07002115 case LIGHT_STATE_WAITING_FOR_NETWORK:
2116 if (mNetworkConnected || mLightState == LIGHT_STATE_WAITING_FOR_NETWORK) {
2117 // We have been idling long enough, now it is time to do some work.
2118 mActiveIdleOpCount = 1;
2119 mActiveIdleWakeLock.acquire();
2120 mMaintenanceStartTime = SystemClock.elapsedRealtime();
2121 if (mCurIdleBudget < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
2122 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
2123 } else if (mCurIdleBudget > mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET) {
2124 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET;
2125 }
2126 scheduleLightAlarmLocked(mCurIdleBudget);
2127 if (DEBUG) Slog.d(TAG,
2128 "Moved from LIGHT_STATE_IDLE to LIGHT_STATE_IDLE_MAINTENANCE.");
2129 mLightState = LIGHT_STATE_IDLE_MAINTENANCE;
2130 EventLogTags.writeDeviceIdleLight(mLightState, reason);
2131 addEvent(EVENT_LIGHT_MAINTENANCE);
2132 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
2133 } else {
2134 // We'd like to do maintenance, but currently don't have network
2135 // connectivity... let's try to wait until the network comes back.
2136 // We'll only wait for another full idle period, however, and then give up.
2137 scheduleLightAlarmLocked(mNextLightIdleDelay);
2138 if (DEBUG) Slog.d(TAG, "Moved to LIGHT_WAITING_FOR_NETWORK.");
2139 mLightState = LIGHT_STATE_WAITING_FOR_NETWORK;
2140 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002141 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002142 break;
2143 }
2144 }
2145
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002146 void stepIdleStateLocked(String reason) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002147 if (DEBUG) Slog.d(TAG, "stepIdleStateLocked: mState=" + mState);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002148 EventLogTags.writeDeviceIdleStep();
2149
2150 final long now = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07002151 if ((now+mConstants.MIN_TIME_TO_ALARM) > mAlarmManager.getNextWakeFromIdleTime()) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002152 // Whoops, there is an upcoming alarm. We don't actually want to go idle.
2153 if (mState != STATE_ACTIVE) {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002154 becomeActiveLocked("alarm", Process.myUid());
Koji Fukui27b33302015-12-16 19:43:01 +09002155 becomeInactiveIfAppropriateLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002156 }
2157 return;
2158 }
2159
2160 switch (mState) {
2161 case STATE_INACTIVE:
2162 // We have now been inactive long enough, it is time to start looking
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002163 // for motion and sleep some more while doing so.
2164 startMonitoringMotionLocked();
Adam Lesinski31c05d12015-06-09 17:34:04 -07002165 scheduleAlarmLocked(mConstants.IDLE_AFTER_INACTIVE_TIMEOUT, false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002166 // Reset the upcoming idle delays.
Adam Lesinski31c05d12015-06-09 17:34:04 -07002167 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
2168 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002169 mState = STATE_IDLE_PENDING;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002170 if (DEBUG) Slog.d(TAG, "Moved from STATE_INACTIVE to STATE_IDLE_PENDING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002171 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002172 break;
2173 case STATE_IDLE_PENDING:
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002174 mState = STATE_SENSING;
2175 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE_PENDING to STATE_SENSING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002176 EventLogTags.writeDeviceIdle(mState, reason);
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002177 scheduleSensingTimeoutAlarmLocked(mConstants.SENSING_TIMEOUT);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002178 cancelLocatingLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002179 mNotMoving = false;
2180 mLocated = false;
2181 mLastGenericLocation = null;
2182 mLastGpsLocation = null;
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002183 mAnyMotionDetector.checkForAnyMotion();
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002184 break;
2185 case STATE_SENSING:
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002186 cancelSensingTimeoutAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002187 mState = STATE_LOCATING;
2188 if (DEBUG) Slog.d(TAG, "Moved from STATE_SENSING to STATE_LOCATING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002189 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002190 scheduleAlarmLocked(mConstants.LOCATING_TIMEOUT, false);
Joe LaPenna23d681b2015-08-27 15:12:11 -07002191 if (mLocationManager != null
2192 && mLocationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
2193 mLocationManager.requestLocationUpdates(mLocationRequest,
2194 mGenericLocationListener, mHandler.getLooper());
2195 mLocating = true;
2196 } else {
2197 mHasNetworkLocation = false;
2198 }
2199 if (mLocationManager != null
2200 && mLocationManager.getProvider(LocationManager.GPS_PROVIDER) != null) {
2201 mHasGps = true;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002202 mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 5,
2203 mGpsLocationListener, mHandler.getLooper());
Joe LaPenna23d681b2015-08-27 15:12:11 -07002204 mLocating = true;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002205 } else {
Joe LaPenna23d681b2015-08-27 15:12:11 -07002206 mHasGps = false;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002207 }
Joe LaPenna23d681b2015-08-27 15:12:11 -07002208 // If we have a location provider, we're all set, the listeners will move state
2209 // forward.
2210 if (mLocating) {
2211 break;
2212 }
2213
2214 // Otherwise, we have to move from locating into idle maintenance.
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002215 case STATE_LOCATING:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002216 cancelAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002217 cancelLocatingLocked();
2218 mAnyMotionDetector.stop();
Dianne Hackborn953fc942016-03-29 15:36:24 -07002219
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002220 case STATE_IDLE_MAINTENANCE:
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002221 scheduleAlarmLocked(mNextIdleDelay, true);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002222 if (DEBUG) Slog.d(TAG, "Moved to STATE_IDLE. Next alarm in " + mNextIdleDelay +
2223 " ms.");
Adam Lesinski31c05d12015-06-09 17:34:04 -07002224 mNextIdleDelay = (long)(mNextIdleDelay * mConstants.IDLE_FACTOR);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002225 if (DEBUG) Slog.d(TAG, "Setting mNextIdleDelay = " + mNextIdleDelay);
Adam Lesinski31c05d12015-06-09 17:34:04 -07002226 mNextIdleDelay = Math.min(mNextIdleDelay, mConstants.MAX_IDLE_TIMEOUT);
Dianne Hackborn953fc942016-03-29 15:36:24 -07002227 if (mNextIdleDelay < mConstants.IDLE_TIMEOUT) {
2228 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
2229 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002230 mState = STATE_IDLE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002231 if (mLightState != LIGHT_STATE_OVERRIDE) {
2232 mLightState = LIGHT_STATE_OVERRIDE;
2233 cancelLightAlarmLocked();
2234 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002235 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackbornb6843652016-02-22 12:20:13 -08002236 addEvent(EVENT_DEEP_IDLE);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08002237 mGoingIdleWakeLock.acquire();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002238 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON);
2239 break;
2240 case STATE_IDLE:
2241 // We have been idling long enough, now it is time to do some work.
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002242 mActiveIdleOpCount = 1;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002243 mActiveIdleWakeLock.acquire();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002244 scheduleAlarmLocked(mNextIdlePendingDelay, false);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002245 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE to STATE_IDLE_MAINTENANCE. " +
2246 "Next alarm in " + mNextIdlePendingDelay + " ms.");
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002247 mMaintenanceStartTime = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07002248 mNextIdlePendingDelay = Math.min(mConstants.MAX_IDLE_PENDING_TIMEOUT,
2249 (long)(mNextIdlePendingDelay * mConstants.IDLE_PENDING_FACTOR));
Dianne Hackborn953fc942016-03-29 15:36:24 -07002250 if (mNextIdlePendingDelay < mConstants.IDLE_PENDING_TIMEOUT) {
2251 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
2252 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002253 mState = STATE_IDLE_MAINTENANCE;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002254 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackbornb6843652016-02-22 12:20:13 -08002255 addEvent(EVENT_DEEP_MAINTENANCE);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002256 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
2257 break;
2258 }
2259 }
2260
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002261 void incActiveIdleOps() {
2262 synchronized (this) {
2263 mActiveIdleOpCount++;
2264 }
2265 }
2266
2267 void decActiveIdleOps() {
2268 synchronized (this) {
2269 mActiveIdleOpCount--;
2270 if (mActiveIdleOpCount <= 0) {
2271 exitMaintenanceEarlyIfNeededLocked();
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002272 mActiveIdleWakeLock.release();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002273 }
2274 }
2275 }
2276
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002277 void setJobsActive(boolean active) {
2278 synchronized (this) {
2279 mJobsActive = active;
Yao Chenca5edbb2016-01-13 14:44:36 -08002280 reportMaintenanceActivityIfNeededLocked();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002281 if (!active) {
2282 exitMaintenanceEarlyIfNeededLocked();
2283 }
2284 }
2285 }
2286
2287 void setAlarmsActive(boolean active) {
2288 synchronized (this) {
2289 mAlarmsActive = active;
2290 if (!active) {
2291 exitMaintenanceEarlyIfNeededLocked();
2292 }
2293 }
2294 }
2295
Yao Chenca5edbb2016-01-13 14:44:36 -08002296 boolean registerMaintenanceActivityListener(IMaintenanceActivityListener listener) {
2297 synchronized (this) {
2298 mMaintenanceActivityListeners.register(listener);
2299 return mReportedMaintenanceActivity;
2300 }
2301 }
2302
2303 void unregisterMaintenanceActivityListener(IMaintenanceActivityListener listener) {
2304 synchronized (this) {
2305 mMaintenanceActivityListeners.unregister(listener);
2306 }
2307 }
2308
2309 void reportMaintenanceActivityIfNeededLocked() {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07002310 boolean active = mJobsActive;
Yao Chenca5edbb2016-01-13 14:44:36 -08002311 if (active == mReportedMaintenanceActivity) {
2312 return;
2313 }
2314 mReportedMaintenanceActivity = active;
2315 Message msg = mHandler.obtainMessage(MSG_REPORT_MAINTENANCE_ACTIVITY,
2316 mReportedMaintenanceActivity ? 1 : 0, 0);
2317 mHandler.sendMessage(msg);
2318 }
2319
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002320 boolean isOpsInactiveLocked() {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07002321 return mActiveIdleOpCount <= 0 && !mJobsActive && !mAlarmsActive;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002322 }
2323
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002324 void exitMaintenanceEarlyIfNeededLocked() {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002325 if (mState == STATE_IDLE_MAINTENANCE || mLightState == LIGHT_STATE_IDLE_MAINTENANCE
2326 || mLightState == LIGHT_STATE_PRE_IDLE) {
2327 if (isOpsInactiveLocked()) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002328 final long now = SystemClock.elapsedRealtime();
2329 if (DEBUG) {
2330 StringBuilder sb = new StringBuilder();
2331 sb.append("Exit: start=");
2332 TimeUtils.formatDuration(mMaintenanceStartTime, sb);
2333 sb.append(" now=");
2334 TimeUtils.formatDuration(now, sb);
2335 Slog.d(TAG, sb.toString());
2336 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002337 if (mState == STATE_IDLE_MAINTENANCE) {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002338 stepIdleStateLocked("s:early");
2339 } else if (mLightState == LIGHT_STATE_PRE_IDLE) {
2340 stepLightIdleStateLocked("s:predone");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002341 } else {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002342 stepLightIdleStateLocked("s:early");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002343 }
2344 }
2345 }
2346 }
2347
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002348 void motionLocked() {
2349 if (DEBUG) Slog.d(TAG, "motionLocked()");
2350 // The motion sensor will have been disabled at this point
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002351 handleMotionDetectedLocked(mConstants.MOTION_INACTIVE_TIMEOUT, "motion");
2352 }
2353
2354 void handleMotionDetectedLocked(long timeout, String type) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002355 // The device is not yet active, so we want to go back to the pending idle
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002356 // state to wait again for no motion. Note that we only monitor for motion
2357 // after moving out of the inactive state, so no need to worry about that.
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002358 boolean becomeInactive = false;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002359 if (mState != STATE_ACTIVE) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002360 scheduleReportActiveLocked(type, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002361 mState = STATE_ACTIVE;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002362 mInactiveTimeout = timeout;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002363 mCurIdleBudget = 0;
2364 mMaintenanceStartTime = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002365 EventLogTags.writeDeviceIdle(mState, type);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002366 addEvent(EVENT_NORMAL);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002367 becomeInactive = true;
2368 }
2369 if (mLightState == LIGHT_STATE_OVERRIDE) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002370 // We went out of light idle mode because we had started deep idle mode... let's
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002371 // now go back and reset things so we resume light idling if appropriate.
2372 mLightState = STATE_ACTIVE;
2373 EventLogTags.writeDeviceIdleLight(mLightState, type);
2374 becomeInactive = true;
2375 }
2376 if (becomeInactive) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002377 becomeInactiveIfAppropriateLocked();
2378 }
2379 }
2380
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002381 void receivedGenericLocationLocked(Location location) {
2382 if (mState != STATE_LOCATING) {
2383 cancelLocatingLocked();
2384 return;
2385 }
2386 if (DEBUG) Slog.d(TAG, "Generic location: " + location);
2387 mLastGenericLocation = new Location(location);
Joe LaPenna23d681b2015-08-27 15:12:11 -07002388 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY && mHasGps) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002389 return;
2390 }
2391 mLocated = true;
2392 if (mNotMoving) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002393 stepIdleStateLocked("s:location");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002394 }
2395 }
2396
2397 void receivedGpsLocationLocked(Location location) {
2398 if (mState != STATE_LOCATING) {
2399 cancelLocatingLocked();
2400 return;
2401 }
2402 if (DEBUG) Slog.d(TAG, "GPS location: " + location);
2403 mLastGpsLocation = new Location(location);
2404 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY) {
2405 return;
2406 }
2407 mLocated = true;
2408 if (mNotMoving) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002409 stepIdleStateLocked("s:gps");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002410 }
2411 }
2412
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002413 void startMonitoringMotionLocked() {
2414 if (DEBUG) Slog.d(TAG, "startMonitoringMotionLocked()");
2415 if (mMotionSensor != null && !mMotionListener.active) {
2416 mMotionListener.registerLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002417 }
2418 }
2419
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002420 void stopMonitoringMotionLocked() {
2421 if (DEBUG) Slog.d(TAG, "stopMonitoringMotionLocked()");
2422 if (mMotionSensor != null && mMotionListener.active) {
2423 mMotionListener.unregisterLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002424 }
2425 }
2426
2427 void cancelAlarmLocked() {
2428 if (mNextAlarmTime != 0) {
2429 mNextAlarmTime = 0;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002430 mAlarmManager.cancel(mDeepAlarmListener);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002431 }
2432 }
2433
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002434 void cancelLightAlarmLocked() {
2435 if (mNextLightAlarmTime != 0) {
2436 mNextLightAlarmTime = 0;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002437 mAlarmManager.cancel(mLightAlarmListener);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002438 }
2439 }
2440
2441 void cancelLocatingLocked() {
2442 if (mLocating) {
2443 mLocationManager.removeUpdates(mGenericLocationListener);
2444 mLocationManager.removeUpdates(mGpsLocationListener);
2445 mLocating = false;
2446 }
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002447 }
2448
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002449 void cancelSensingTimeoutAlarmLocked() {
2450 if (mNextSensingTimeoutAlarmTime != 0) {
2451 mNextSensingTimeoutAlarmTime = 0;
2452 mAlarmManager.cancel(mSensingTimeoutAlarmListener);
2453 }
2454 }
2455
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002456 void scheduleAlarmLocked(long delay, boolean idleUntil) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002457 if (DEBUG) Slog.d(TAG, "scheduleAlarmLocked(" + delay + ", " + idleUntil + ")");
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002458 if (mMotionSensor == null) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07002459 // If there is no motion sensor on this device, then we won't schedule
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002460 // alarms, because we can't determine if the device is not moving. This effectively
Joe LaPenna23d681b2015-08-27 15:12:11 -07002461 // turns off normal execution of device idling, although it is still possible to
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002462 // manually poke it by pretending like the alarm is going off.
2463 return;
2464 }
2465 mNextAlarmTime = SystemClock.elapsedRealtime() + delay;
2466 if (idleUntil) {
2467 mAlarmManager.setIdleUntil(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002468 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002469 } else {
2470 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002471 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002472 }
2473 }
2474
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002475 void scheduleLightAlarmLocked(long delay) {
2476 if (DEBUG) Slog.d(TAG, "scheduleLightAlarmLocked(" + delay + ")");
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002477 mNextLightAlarmTime = SystemClock.elapsedRealtime() + delay;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002478 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002479 mNextLightAlarmTime, "DeviceIdleController.light", mLightAlarmListener, mHandler);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002480 }
2481
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002482 void scheduleSensingTimeoutAlarmLocked(long delay) {
2483 if (DEBUG) Slog.d(TAG, "scheduleSensingAlarmLocked(" + delay + ")");
2484 mNextSensingTimeoutAlarmTime = SystemClock.elapsedRealtime() + delay;
2485 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, mNextSensingTimeoutAlarmTime,
2486 "DeviceIdleController.sensing", mSensingTimeoutAlarmListener, mHandler);
2487 }
2488
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002489 private static int[] buildAppIdArray(ArrayMap<String, Integer> systemApps,
2490 ArrayMap<String, Integer> userApps, SparseBooleanArray outAppIds) {
2491 outAppIds.clear();
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002492 if (systemApps != null) {
2493 for (int i = 0; i < systemApps.size(); i++) {
2494 outAppIds.put(systemApps.valueAt(i), true);
2495 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002496 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002497 if (userApps != null) {
2498 for (int i = 0; i < userApps.size(); i++) {
2499 outAppIds.put(userApps.valueAt(i), true);
2500 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002501 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002502 int size = outAppIds.size();
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002503 int[] appids = new int[size];
2504 for (int i = 0; i < size; i++) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002505 appids[i] = outAppIds.keyAt(i);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002506 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002507 return appids;
2508 }
2509
2510 private void updateWhitelistAppIdsLocked() {
2511 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(mPowerSaveWhitelistAppsExceptIdle,
2512 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistExceptIdleAppIds);
2513 mPowerSaveWhitelistAllAppIdArray = buildAppIdArray(mPowerSaveWhitelistApps,
2514 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistAllAppIds);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002515 mPowerSaveWhitelistUserAppIdArray = buildAppIdArray(null,
2516 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistUserAppIds);
Dianne Hackborn85e35642017-01-12 15:10:57 -08002517 if (mLocalActivityManager != null) {
2518 if (DEBUG) {
2519 Slog.d(TAG, "Setting activity manager whitelist to "
2520 + Arrays.toString(mPowerSaveWhitelistAllAppIdArray));
2521 }
2522 mLocalActivityManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
2523 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002524 if (mLocalPowerManager != null) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002525 if (DEBUG) {
2526 Slog.d(TAG, "Setting wakelock whitelist to "
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002527 + Arrays.toString(mPowerSaveWhitelistAllAppIdArray));
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002528 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002529 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002530 }
Makoto Onuki2206af32017-11-21 16:25:35 -08002531 passWhiteListToForceAppStandbyTrackerLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002532 }
2533
Dianne Hackborn85e35642017-01-12 15:10:57 -08002534 private void updateTempWhitelistAppIdsLocked(int appId, boolean adding) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002535 final int size = mTempWhitelistAppIdEndTimes.size();
2536 if (mTempWhitelistAppIdArray.length != size) {
2537 mTempWhitelistAppIdArray = new int[size];
2538 }
2539 for (int i = 0; i < size; i++) {
2540 mTempWhitelistAppIdArray[i] = mTempWhitelistAppIdEndTimes.keyAt(i);
2541 }
Dianne Hackborn85e35642017-01-12 15:10:57 -08002542 if (mLocalActivityManager != null) {
2543 if (DEBUG) {
2544 Slog.d(TAG, "Setting activity manager temp whitelist to "
2545 + Arrays.toString(mTempWhitelistAppIdArray));
2546 }
2547 mLocalActivityManager.updateDeviceIdleTempWhitelist(mTempWhitelistAppIdArray, appId,
2548 adding);
2549 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002550 if (mLocalPowerManager != null) {
2551 if (DEBUG) {
2552 Slog.d(TAG, "Setting wakelock temp whitelist to "
2553 + Arrays.toString(mTempWhitelistAppIdArray));
2554 }
2555 mLocalPowerManager.setDeviceIdleTempWhitelist(mTempWhitelistAppIdArray);
2556 }
Makoto Onuki2206af32017-11-21 16:25:35 -08002557 passWhiteListToForceAppStandbyTrackerLocked();
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002558 }
2559
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002560 private void reportPowerSaveWhitelistChangedLocked() {
2561 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
2562 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Xiaohui Chene4de5a02015-09-22 15:33:31 -07002563 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002564 }
2565
2566 private void reportTempWhitelistChangedLocked() {
2567 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_TEMP_WHITELIST_CHANGED);
2568 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Xiaohui Chene4de5a02015-09-22 15:33:31 -07002569 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002570 }
2571
Makoto Onuki2206af32017-11-21 16:25:35 -08002572 private void passWhiteListToForceAppStandbyTrackerLocked() {
2573 ForceAppStandbyTracker.getInstance(getContext()).setPowerSaveWhitelistAppIds(
2574 mPowerSaveWhitelistAllAppIdArray,
2575 mTempWhitelistAppIdArray);
2576 }
2577
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002578 void readConfigFileLocked() {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002579 if (DEBUG) Slog.d(TAG, "Reading config from " + mConfigFile.getBaseFile());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002580 mPowerSaveWhitelistUserApps.clear();
2581 FileInputStream stream;
2582 try {
2583 stream = mConfigFile.openRead();
2584 } catch (FileNotFoundException e) {
2585 return;
2586 }
2587 try {
2588 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002589 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002590 readConfigFileLocked(parser);
2591 } catch (XmlPullParserException e) {
2592 } finally {
2593 try {
2594 stream.close();
2595 } catch (IOException e) {
2596 }
2597 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002598 }
2599
2600 private void readConfigFileLocked(XmlPullParser parser) {
2601 final PackageManager pm = getContext().getPackageManager();
2602
2603 try {
2604 int type;
2605 while ((type = parser.next()) != XmlPullParser.START_TAG
2606 && type != XmlPullParser.END_DOCUMENT) {
2607 ;
2608 }
2609
2610 if (type != XmlPullParser.START_TAG) {
2611 throw new IllegalStateException("no start tag found");
2612 }
2613
2614 int outerDepth = parser.getDepth();
2615 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2616 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2617 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2618 continue;
2619 }
2620
2621 String tagName = parser.getName();
Suprabh Shukla08105642017-09-26 14:45:30 -07002622 switch (tagName) {
2623 case "wl":
2624 String name = parser.getAttributeValue(null, "n");
2625 if (name != null) {
2626 try {
2627 ApplicationInfo ai = pm.getApplicationInfo(name,
2628 PackageManager.MATCH_ANY_USER);
2629 mPowerSaveWhitelistUserApps.put(ai.packageName,
2630 UserHandle.getAppId(ai.uid));
2631 } catch (PackageManager.NameNotFoundException e) {
2632 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002633 }
Suprabh Shukla08105642017-09-26 14:45:30 -07002634 break;
2635 case "un-wl":
2636 final String packageName = parser.getAttributeValue(null, "n");
2637 if (mPowerSaveWhitelistApps.containsKey(packageName)) {
2638 mRemovedFromSystemWhitelistApps.put(packageName,
2639 mPowerSaveWhitelistApps.remove(packageName));
2640 }
2641 break;
2642 default:
2643 Slog.w(TAG, "Unknown element under <config>: "
2644 + parser.getName());
2645 XmlUtils.skipCurrentTag(parser);
2646 break;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002647 }
2648 }
2649
2650 } catch (IllegalStateException e) {
2651 Slog.w(TAG, "Failed parsing config " + e);
2652 } catch (NullPointerException e) {
2653 Slog.w(TAG, "Failed parsing config " + e);
2654 } catch (NumberFormatException e) {
2655 Slog.w(TAG, "Failed parsing config " + e);
2656 } catch (XmlPullParserException e) {
2657 Slog.w(TAG, "Failed parsing config " + e);
2658 } catch (IOException e) {
2659 Slog.w(TAG, "Failed parsing config " + e);
2660 } catch (IndexOutOfBoundsException e) {
2661 Slog.w(TAG, "Failed parsing config " + e);
2662 }
2663 }
2664
2665 void writeConfigFileLocked() {
2666 mHandler.removeMessages(MSG_WRITE_CONFIG);
2667 mHandler.sendEmptyMessageDelayed(MSG_WRITE_CONFIG, 5000);
2668 }
2669
2670 void handleWriteConfigFile() {
2671 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
2672
2673 try {
2674 synchronized (this) {
2675 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002676 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002677 writeConfigFileLocked(out);
2678 }
2679 } catch (IOException e) {
2680 }
2681
2682 synchronized (mConfigFile) {
2683 FileOutputStream stream = null;
2684 try {
2685 stream = mConfigFile.startWrite();
2686 memStream.writeTo(stream);
2687 stream.flush();
2688 FileUtils.sync(stream);
2689 stream.close();
2690 mConfigFile.finishWrite(stream);
2691 } catch (IOException e) {
2692 Slog.w(TAG, "Error writing config file", e);
2693 mConfigFile.failWrite(stream);
2694 }
2695 }
2696 }
2697
2698 void writeConfigFileLocked(XmlSerializer out) throws IOException {
2699 out.startDocument(null, true);
2700 out.startTag(null, "config");
2701 for (int i=0; i<mPowerSaveWhitelistUserApps.size(); i++) {
2702 String name = mPowerSaveWhitelistUserApps.keyAt(i);
2703 out.startTag(null, "wl");
2704 out.attribute(null, "n", name);
2705 out.endTag(null, "wl");
2706 }
Suprabh Shukla08105642017-09-26 14:45:30 -07002707 for (int i = 0; i < mRemovedFromSystemWhitelistApps.size(); i++) {
2708 out.startTag(null, "un-wl");
2709 out.attribute(null, "n", mRemovedFromSystemWhitelistApps.keyAt(i));
2710 out.endTag(null, "un-wl");
2711 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002712 out.endTag(null, "config");
2713 out.endDocument();
2714 }
2715
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002716 static void dumpHelp(PrintWriter pw) {
2717 pw.println("Device idle controller (deviceidle) commands:");
2718 pw.println(" help");
2719 pw.println(" Print this help text.");
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002720 pw.println(" step [light|deep]");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002721 pw.println(" Immediately step to next state, without waiting for alarm.");
Dianne Hackborn88c41352016-04-07 15:18:58 -07002722 pw.println(" force-idle [light|deep]");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002723 pw.println(" Force directly into idle mode, regardless of other device state.");
Dianne Hackborn88c41352016-04-07 15:18:58 -07002724 pw.println(" force-inactive");
2725 pw.println(" Force to be inactive, ready to freely step idle states.");
2726 pw.println(" unforce");
2727 pw.println(" Resume normal functioning after force-idle or force-inactive.");
2728 pw.println(" get [light|deep|force|screen|charging|network]");
2729 pw.println(" Retrieve the current given state.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002730 pw.println(" disable [light|deep|all]");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002731 pw.println(" Completely disable device idle mode.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002732 pw.println(" enable [light|deep|all]");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002733 pw.println(" Re-enable device idle mode after it had previously been disabled.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002734 pw.println(" enabled [light|deep|all]");
Dianne Hackborn92617032015-06-19 15:32:19 -07002735 pw.println(" Print 1 if device idle mode is currently enabled, else 0.");
Dianne Hackborn1b139682015-07-06 15:13:37 -07002736 pw.println(" whitelist");
2737 pw.println(" Print currently whitelisted apps.");
Dianne Hackborn92617032015-06-19 15:32:19 -07002738 pw.println(" whitelist [package ...]");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002739 pw.println(" Add (prefix with +) or remove (prefix with -) packages.");
Suprabh Shukla08105642017-09-26 14:45:30 -07002740 pw.println(" sys-whitelist [package ...|reset]");
2741 pw.println(" Prefix the package with '-' to remove it from the system whitelist or '+'"
2742 + " to put it back in the system whitelist.");
2743 pw.println(" Note that only packages that were"
2744 + " earlier removed from the system whitelist can be added back.");
2745 pw.println(" reset will reset the whitelist to the original state");
2746 pw.println(" Prints the system whitelist if no arguments are specified");
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07002747 pw.println(" except-idle-whitelist [package ...|reset]");
2748 pw.println(" Prefix the package with '+' to add it to whitelist or "
2749 + "'=' to check if it is already whitelisted");
2750 pw.println(" [reset] will reset the whitelist to it's original state");
2751 pw.println(" Note that unlike <whitelist> cmd, "
2752 + "changes made using this won't be persisted across boots");
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002753 pw.println(" tempwhitelist");
2754 pw.println(" Print packages that are temporarily whitelisted.");
Sudheer Shanka326b3112017-11-27 14:40:57 -08002755 pw.println(" tempwhitelist [-u USER] [-d DURATION] [-r] [package]");
2756 pw.println(" Temporarily place package in whitelist for DURATION milliseconds.");
Dianne Hackborn85e35642017-01-12 15:10:57 -08002757 pw.println(" If no DURATION is specified, 10 seconds is used");
Sudheer Shanka326b3112017-11-27 14:40:57 -08002758 pw.println(" If [-r] option is used, then the package is removed from temp whitelist "
2759 + "and any [-d] is ignored");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002760 }
2761
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002762 class Shell extends ShellCommand {
2763 int userId = UserHandle.USER_SYSTEM;
2764
2765 @Override
2766 public int onCommand(String cmd) {
2767 return onShellCommand(this, cmd);
2768 }
2769
2770 @Override
2771 public void onHelp() {
2772 PrintWriter pw = getOutPrintWriter();
2773 dumpHelp(pw);
2774 }
2775 }
2776
2777 int onShellCommand(Shell shell, String cmd) {
2778 PrintWriter pw = shell.getOutPrintWriter();
2779 if ("step".equals(cmd)) {
2780 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2781 null);
2782 synchronized (this) {
2783 long token = Binder.clearCallingIdentity();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002784 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002785 try {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002786 if (arg == null || "deep".equals(arg)) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002787 stepIdleStateLocked("s:shell");
2788 pw.print("Stepped to deep: ");
2789 pw.println(stateToString(mState));
2790 } else if ("light".equals(arg)) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002791 stepLightIdleStateLocked("s:shell");
2792 pw.print("Stepped to light: "); pw.println(lightStateToString(mLightState));
2793 } else {
2794 pw.println("Unknown idle mode: " + arg);
2795 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002796 } finally {
2797 Binder.restoreCallingIdentity(token);
2798 }
2799 }
2800 } else if ("force-idle".equals(cmd)) {
2801 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2802 null);
2803 synchronized (this) {
2804 long token = Binder.clearCallingIdentity();
Dianne Hackborn88c41352016-04-07 15:18:58 -07002805 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002806 try {
Dianne Hackborn88c41352016-04-07 15:18:58 -07002807 if (arg == null || "deep".equals(arg)) {
2808 if (!mDeepEnabled) {
2809 pw.println("Unable to go deep idle; not enabled");
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002810 return -1;
2811 }
Dianne Hackborn88c41352016-04-07 15:18:58 -07002812 mForceIdle = true;
2813 becomeInactiveIfAppropriateLocked();
2814 int curState = mState;
2815 while (curState != STATE_IDLE) {
2816 stepIdleStateLocked("s:shell");
2817 if (curState == mState) {
2818 pw.print("Unable to go deep idle; stopped at ");
2819 pw.println(stateToString(mState));
2820 exitForceIdleLocked();
2821 return -1;
2822 }
2823 curState = mState;
2824 }
2825 pw.println("Now forced in to deep idle mode");
2826 } else if ("light".equals(arg)) {
2827 mForceIdle = true;
2828 becomeInactiveIfAppropriateLocked();
2829 int curLightState = mLightState;
2830 while (curLightState != LIGHT_STATE_IDLE) {
2831 stepIdleStateLocked("s:shell");
2832 if (curLightState == mLightState) {
2833 pw.print("Unable to go light idle; stopped at ");
2834 pw.println(lightStateToString(mLightState));
2835 exitForceIdleLocked();
2836 return -1;
2837 }
2838 curLightState = mLightState;
2839 }
2840 pw.println("Now forced in to light idle mode");
2841 } else {
2842 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002843 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002844 } finally {
2845 Binder.restoreCallingIdentity(token);
2846 }
2847 }
Dianne Hackborn88c41352016-04-07 15:18:58 -07002848 } else if ("force-inactive".equals(cmd)) {
2849 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2850 null);
2851 synchronized (this) {
2852 long token = Binder.clearCallingIdentity();
2853 try {
2854 mForceIdle = true;
2855 becomeInactiveIfAppropriateLocked();
2856 pw.print("Light state: ");
2857 pw.print(lightStateToString(mLightState));
2858 pw.print(", deep state: ");
2859 pw.println(stateToString(mState));
2860 } finally {
2861 Binder.restoreCallingIdentity(token);
2862 }
2863 }
2864 } else if ("unforce".equals(cmd)) {
2865 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2866 null);
2867 synchronized (this) {
2868 long token = Binder.clearCallingIdentity();
2869 try {
2870 exitForceIdleLocked();
2871 pw.print("Light state: ");
2872 pw.print(lightStateToString(mLightState));
2873 pw.print(", deep state: ");
2874 pw.println(stateToString(mState));
2875 } finally {
2876 Binder.restoreCallingIdentity(token);
2877 }
2878 }
2879 } else if ("get".equals(cmd)) {
2880 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2881 null);
2882 synchronized (this) {
2883 String arg = shell.getNextArg();
2884 if (arg != null) {
2885 long token = Binder.clearCallingIdentity();
2886 try {
2887 switch (arg) {
2888 case "light": pw.println(lightStateToString(mLightState)); break;
2889 case "deep": pw.println(stateToString(mState)); break;
2890 case "force": pw.println(mForceIdle); break;
2891 case "screen": pw.println(mScreenOn); break;
2892 case "charging": pw.println(mCharging); break;
2893 case "network": pw.println(mNetworkConnected); break;
2894 default: pw.println("Unknown get option: " + arg); break;
2895 }
2896 } finally {
2897 Binder.restoreCallingIdentity(token);
2898 }
2899 } else {
2900 pw.println("Argument required");
2901 }
2902 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002903 } else if ("disable".equals(cmd)) {
2904 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2905 null);
2906 synchronized (this) {
2907 long token = Binder.clearCallingIdentity();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002908 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002909 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002910 boolean becomeActive = false;
2911 boolean valid = false;
2912 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
2913 valid = true;
2914 if (mDeepEnabled) {
2915 mDeepEnabled = false;
2916 becomeActive = true;
2917 pw.println("Deep idle mode disabled");
2918 }
2919 }
2920 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
2921 valid = true;
2922 if (mLightEnabled) {
2923 mLightEnabled = false;
2924 becomeActive = true;
2925 pw.println("Light idle mode disabled");
2926 }
2927 }
2928 if (becomeActive) {
2929 becomeActiveLocked((arg == null ? "all" : arg) + "-disabled",
2930 Process.myUid());
2931 }
2932 if (!valid) {
2933 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002934 }
2935 } finally {
2936 Binder.restoreCallingIdentity(token);
2937 }
2938 }
2939 } else if ("enable".equals(cmd)) {
2940 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2941 null);
2942 synchronized (this) {
2943 long token = Binder.clearCallingIdentity();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002944 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002945 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002946 boolean becomeInactive = false;
2947 boolean valid = false;
2948 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
2949 valid = true;
2950 if (!mDeepEnabled) {
2951 mDeepEnabled = true;
2952 becomeInactive = true;
2953 pw.println("Deep idle mode enabled");
2954 }
2955 }
2956 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
2957 valid = true;
2958 if (!mLightEnabled) {
2959 mLightEnabled = true;
2960 becomeInactive = true;
2961 pw.println("Light idle mode enable");
2962 }
2963 }
2964 if (becomeInactive) {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002965 becomeInactiveIfAppropriateLocked();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002966 }
2967 if (!valid) {
2968 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002969 }
2970 } finally {
2971 Binder.restoreCallingIdentity(token);
2972 }
2973 }
2974 } else if ("enabled".equals(cmd)) {
2975 synchronized (this) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002976 String arg = shell.getNextArg();
2977 if (arg == null || "all".equals(arg)) {
2978 pw.println(mDeepEnabled && mLightEnabled ? "1" : 0);
2979 } else if ("deep".equals(arg)) {
2980 pw.println(mDeepEnabled ? "1" : 0);
2981 } else if ("light".equals(arg)) {
2982 pw.println(mLightEnabled ? "1" : 0);
2983 } else {
2984 pw.println("Unknown idle mode: " + arg);
2985 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002986 }
2987 } else if ("whitelist".equals(cmd)) {
Dianne Hackborneb909e32016-09-29 14:35:15 -07002988 String arg = shell.getNextArg();
2989 if (arg != null) {
2990 getContext().enforceCallingOrSelfPermission(
2991 android.Manifest.permission.DEVICE_POWER, null);
2992 long token = Binder.clearCallingIdentity();
2993 try {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002994 do {
2995 if (arg.length() < 1 || (arg.charAt(0) != '-'
Felipe Lemef8a46232016-02-10 13:51:54 -08002996 && arg.charAt(0) != '+' && arg.charAt(0) != '=')) {
2997 pw.println("Package must be prefixed with +, -, or =: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002998 return -1;
2999 }
3000 char op = arg.charAt(0);
3001 String pkg = arg.substring(1);
3002 if (op == '+') {
3003 if (addPowerSaveWhitelistAppInternal(pkg)) {
3004 pw.println("Added: " + pkg);
3005 } else {
3006 pw.println("Unknown package: " + pkg);
3007 }
Felipe Lemef8a46232016-02-10 13:51:54 -08003008 } else if (op == '-') {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003009 if (removePowerSaveWhitelistAppInternal(pkg)) {
3010 pw.println("Removed: " + pkg);
3011 }
Felipe Lemef8a46232016-02-10 13:51:54 -08003012 } else {
3013 pw.println(getPowerSaveWhitelistAppInternal(pkg));
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003014 }
3015 } while ((arg=shell.getNextArg()) != null);
Dianne Hackborneb909e32016-09-29 14:35:15 -07003016 } finally {
3017 Binder.restoreCallingIdentity(token);
3018 }
3019 } else {
3020 synchronized (this) {
3021 for (int j=0; j<mPowerSaveWhitelistAppsExceptIdle.size(); j++) {
3022 pw.print("system-excidle,");
3023 pw.print(mPowerSaveWhitelistAppsExceptIdle.keyAt(j));
3024 pw.print(",");
3025 pw.println(mPowerSaveWhitelistAppsExceptIdle.valueAt(j));
3026 }
3027 for (int j=0; j<mPowerSaveWhitelistApps.size(); j++) {
3028 pw.print("system,");
3029 pw.print(mPowerSaveWhitelistApps.keyAt(j));
3030 pw.print(",");
3031 pw.println(mPowerSaveWhitelistApps.valueAt(j));
3032 }
3033 for (int j=0; j<mPowerSaveWhitelistUserApps.size(); j++) {
3034 pw.print("user,");
3035 pw.print(mPowerSaveWhitelistUserApps.keyAt(j));
3036 pw.print(",");
3037 pw.println(mPowerSaveWhitelistUserApps.valueAt(j));
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003038 }
3039 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003040 }
3041 } else if ("tempwhitelist".equals(cmd)) {
Dianne Hackborn85e35642017-01-12 15:10:57 -08003042 long duration = 10000;
Sudheer Shanka326b3112017-11-27 14:40:57 -08003043 boolean removePkg = false;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003044 String opt;
3045 while ((opt=shell.getNextOption()) != null) {
3046 if ("-u".equals(opt)) {
3047 opt = shell.getNextArg();
3048 if (opt == null) {
3049 pw.println("-u requires a user number");
3050 return -1;
3051 }
3052 shell.userId = Integer.parseInt(opt);
Dianne Hackborn85e35642017-01-12 15:10:57 -08003053 } else if ("-d".equals(opt)) {
3054 opt = shell.getNextArg();
3055 if (opt == null) {
3056 pw.println("-d requires a duration");
3057 return -1;
3058 }
3059 duration = Long.parseLong(opt);
Sudheer Shanka326b3112017-11-27 14:40:57 -08003060 } else if ("-r".equals(opt)) {
3061 removePkg = true;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003062 }
3063 }
3064 String arg = shell.getNextArg();
3065 if (arg != null) {
3066 try {
Sudheer Shanka326b3112017-11-27 14:40:57 -08003067 if (removePkg) {
3068 removePowerSaveTempWhitelistAppChecked(arg, shell.userId);
3069 } else {
3070 addPowerSaveTempWhitelistAppChecked(arg, duration, shell.userId, "shell");
3071 }
Christopher Tateec3a9f32017-03-21 17:43:47 -07003072 } catch (Exception e) {
3073 pw.println("Failed: " + e);
3074 return -1;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003075 }
Sudheer Shanka326b3112017-11-27 14:40:57 -08003076 } else if (removePkg) {
3077 pw.println("[-r] requires a package name");
3078 return -1;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003079 } else {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003080 dumpTempWhitelistSchedule(pw, false);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003081 }
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07003082 } else if ("except-idle-whitelist".equals(cmd)) {
3083 getContext().enforceCallingOrSelfPermission(
3084 android.Manifest.permission.DEVICE_POWER, null);
3085 final long token = Binder.clearCallingIdentity();
3086 try {
3087 String arg = shell.getNextArg();
3088 if (arg == null) {
3089 pw.println("No arguments given");
3090 return -1;
3091 } else if ("reset".equals(arg)) {
3092 resetPowerSaveWhitelistExceptIdleInternal();
3093 } else {
3094 do {
3095 if (arg.length() < 1 || (arg.charAt(0) != '-'
3096 && arg.charAt(0) != '+' && arg.charAt(0) != '=')) {
3097 pw.println("Package must be prefixed with +, -, or =: " + arg);
3098 return -1;
3099 }
3100 char op = arg.charAt(0);
3101 String pkg = arg.substring(1);
3102 if (op == '+') {
3103 if (addPowerSaveWhitelistExceptIdleInternal(pkg)) {
3104 pw.println("Added: " + pkg);
3105 } else {
3106 pw.println("Unknown package: " + pkg);
3107 }
3108 } else if (op == '=') {
3109 pw.println(getPowerSaveWhitelistExceptIdleInternal(pkg));
3110 } else {
3111 pw.println("Unknown argument: " + arg);
3112 return -1;
3113 }
3114 } while ((arg = shell.getNextArg()) != null);
3115 }
3116 } finally {
3117 Binder.restoreCallingIdentity(token);
3118 }
Suprabh Shukla08105642017-09-26 14:45:30 -07003119 } else if ("sys-whitelist".equals(cmd)) {
3120 String arg = shell.getNextArg();
3121 if (arg != null) {
3122 getContext().enforceCallingOrSelfPermission(
3123 android.Manifest.permission.DEVICE_POWER, null);
3124 final long token = Binder.clearCallingIdentity();
3125 try {
3126 if ("reset".equals(arg)) {
3127 resetSystemPowerWhitelistInternal();
3128 } else {
3129 do {
3130 if (arg.length() < 1
3131 || (arg.charAt(0) != '-' && arg.charAt(0) != '+')) {
3132 pw.println("Package must be prefixed with + or - " + arg);
3133 return -1;
3134 }
3135 final char op = arg.charAt(0);
3136 final String pkg = arg.substring(1);
3137 switch (op) {
3138 case '+':
3139 if (restoreSystemPowerWhitelistAppInternal(pkg)) {
3140 pw.println("Restored " + pkg);
3141 }
3142 break;
3143 case '-':
3144 if (removeSystemPowerWhitelistAppInternal(pkg)) {
3145 pw.println("Removed " + pkg);
3146 }
3147 break;
3148 }
3149 } while ((arg = shell.getNextArg()) != null);
3150 }
3151 } finally {
3152 Binder.restoreCallingIdentity(token);
3153 }
3154 } else {
3155 synchronized (this) {
3156 for (int j=0; j<mPowerSaveWhitelistApps.size(); j++) {
3157 pw.print(mPowerSaveWhitelistApps.keyAt(j));
3158 pw.print(",");
3159 pw.println(mPowerSaveWhitelistApps.valueAt(j));
3160 }
3161 }
3162 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003163 } else {
3164 return shell.handleDefaultCommands(cmd);
3165 }
3166 return 0;
3167 }
3168
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003169 void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003170 if (!DumpUtils.checkDumpPermission(getContext(), TAG, pw)) return;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003171
3172 if (args != null) {
Xiaohui Chen7c696362015-09-16 09:56:14 -07003173 int userId = UserHandle.USER_SYSTEM;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003174 for (int i=0; i<args.length; i++) {
3175 String arg = args[i];
3176 if ("-h".equals(arg)) {
3177 dumpHelp(pw);
3178 return;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003179 } else if ("-u".equals(arg)) {
3180 i++;
3181 if (i < args.length) {
3182 arg = args[i];
3183 userId = Integer.parseInt(arg);
3184 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003185 } else if ("-a".equals(arg)) {
3186 // Ignore, we always dump all.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003187 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
3188 pw.println("Unknown option: " + arg);
3189 return;
3190 } else {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003191 Shell shell = new Shell();
3192 shell.userId = userId;
3193 String[] newArgs = new String[args.length-i];
3194 System.arraycopy(args, i, newArgs, 0, args.length-i);
Dianne Hackborn354736e2016-08-22 17:00:05 -07003195 shell.exec(mBinderService, null, fd, null, newArgs, null,
3196 new ResultReceiver(null));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003197 return;
3198 }
3199 }
3200 }
3201
3202 synchronized (this) {
Dianne Hackborna750a632015-06-16 17:18:23 -07003203 mConstants.dump(pw);
3204
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08003205 if (mEventCmds[0] != EVENT_NULL) {
3206 pw.println(" Idling history:");
3207 long now = SystemClock.elapsedRealtime();
3208 for (int i=EVENT_BUFFER_SIZE-1; i>=0; i--) {
3209 int cmd = mEventCmds[i];
3210 if (cmd == EVENT_NULL) {
3211 continue;
3212 }
3213 String label;
3214 switch (mEventCmds[i]) {
3215 case EVENT_NORMAL: label = " normal"; break;
3216 case EVENT_LIGHT_IDLE: label = " light-idle"; break;
3217 case EVENT_LIGHT_MAINTENANCE: label = "light-maint"; break;
Dianne Hackbornb6843652016-02-22 12:20:13 -08003218 case EVENT_DEEP_IDLE: label = " deep-idle"; break;
3219 case EVENT_DEEP_MAINTENANCE: label = " deep-maint"; break;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08003220 default: label = " ??"; break;
3221 }
3222 pw.print(" ");
3223 pw.print(label);
3224 pw.print(": ");
3225 TimeUtils.formatDuration(mEventTimes[i], now, pw);;
3226 pw.println();
3227 }
3228 }
3229
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003230 int size = mPowerSaveWhitelistAppsExceptIdle.size();
3231 if (size > 0) {
3232 pw.println(" Whitelist (except idle) system apps:");
3233 for (int i = 0; i < size; i++) {
3234 pw.print(" ");
3235 pw.println(mPowerSaveWhitelistAppsExceptIdle.keyAt(i));
3236 }
3237 }
3238 size = mPowerSaveWhitelistApps.size();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003239 if (size > 0) {
3240 pw.println(" Whitelist system apps:");
3241 for (int i = 0; i < size; i++) {
3242 pw.print(" ");
3243 pw.println(mPowerSaveWhitelistApps.keyAt(i));
3244 }
3245 }
Suprabh Shukla08105642017-09-26 14:45:30 -07003246 size = mRemovedFromSystemWhitelistApps.size();
3247 if (size > 0) {
3248 pw.println(" Removed from whitelist system apps:");
3249 for (int i = 0; i < size; i++) {
3250 pw.print(" ");
3251 pw.println(mRemovedFromSystemWhitelistApps.keyAt(i));
3252 }
3253 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003254 size = mPowerSaveWhitelistUserApps.size();
3255 if (size > 0) {
3256 pw.println(" Whitelist user apps:");
3257 for (int i = 0; i < size; i++) {
3258 pw.print(" ");
3259 pw.println(mPowerSaveWhitelistUserApps.keyAt(i));
3260 }
3261 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003262 size = mPowerSaveWhitelistExceptIdleAppIds.size();
3263 if (size > 0) {
3264 pw.println(" Whitelist (except idle) all app ids:");
3265 for (int i = 0; i < size; i++) {
3266 pw.print(" ");
3267 pw.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
3268 pw.println();
3269 }
3270 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08003271 size = mPowerSaveWhitelistUserAppIds.size();
3272 if (size > 0) {
3273 pw.println(" Whitelist user app ids:");
3274 for (int i = 0; i < size; i++) {
3275 pw.print(" ");
3276 pw.print(mPowerSaveWhitelistUserAppIds.keyAt(i));
3277 pw.println();
3278 }
3279 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07003280 size = mPowerSaveWhitelistAllAppIds.size();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003281 if (size > 0) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07003282 pw.println(" Whitelist all app ids:");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003283 for (int i = 0; i < size; i++) {
Dianne Hackborna750a632015-06-16 17:18:23 -07003284 pw.print(" ");
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07003285 pw.print(mPowerSaveWhitelistAllAppIds.keyAt(i));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003286 pw.println();
3287 }
3288 }
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003289 dumpTempWhitelistSchedule(pw, true);
3290
Dianne Hackborna750a632015-06-16 17:18:23 -07003291 size = mTempWhitelistAppIdArray != null ? mTempWhitelistAppIdArray.length : 0;
3292 if (size > 0) {
3293 pw.println(" Temp whitelist app ids:");
3294 for (int i = 0; i < size; i++) {
3295 pw.print(" ");
3296 pw.print(mTempWhitelistAppIdArray[i]);
3297 pw.println();
3298 }
3299 }
Adam Lesinski31c05d12015-06-09 17:34:04 -07003300
Dianne Hackbornb6843652016-02-22 12:20:13 -08003301 pw.print(" mLightEnabled="); pw.print(mLightEnabled);
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003302 pw.print(" mDeepEnabled="); pw.println(mDeepEnabled);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003303 pw.print(" mForceIdle="); pw.println(mForceIdle);
Nick Vaccaro20feaea2015-09-17 17:22:44 -07003304 pw.print(" mMotionSensor="); pw.println(mMotionSensor);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003305 pw.print(" mScreenOn="); pw.println(mScreenOn);
Dianne Hackborn88c41352016-04-07 15:18:58 -07003306 pw.print(" mNetworkConnected="); pw.println(mNetworkConnected);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003307 pw.print(" mCharging="); pw.println(mCharging);
Nick Vaccaro20feaea2015-09-17 17:22:44 -07003308 pw.print(" mMotionActive="); pw.println(mMotionListener.active);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003309 pw.print(" mNotMoving="); pw.println(mNotMoving);
Joe LaPenna23d681b2015-08-27 15:12:11 -07003310 pw.print(" mLocating="); pw.print(mLocating); pw.print(" mHasGps=");
3311 pw.print(mHasGps); pw.print(" mHasNetwork=");
3312 pw.print(mHasNetworkLocation); pw.print(" mLocated="); pw.println(mLocated);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07003313 if (mLastGenericLocation != null) {
3314 pw.print(" mLastGenericLocation="); pw.println(mLastGenericLocation);
3315 }
3316 if (mLastGpsLocation != null) {
3317 pw.print(" mLastGpsLocation="); pw.println(mLastGpsLocation);
3318 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003319 pw.print(" mState="); pw.print(stateToString(mState));
3320 pw.print(" mLightState=");
3321 pw.println(lightStateToString(mLightState));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003322 pw.print(" mInactiveTimeout="); TimeUtils.formatDuration(mInactiveTimeout, pw);
3323 pw.println();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003324 if (mActiveIdleOpCount != 0) {
3325 pw.print(" mActiveIdleOpCount="); pw.println(mActiveIdleOpCount);
3326 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003327 if (mNextAlarmTime != 0) {
3328 pw.print(" mNextAlarmTime=");
3329 TimeUtils.formatDuration(mNextAlarmTime, SystemClock.elapsedRealtime(), pw);
3330 pw.println();
3331 }
3332 if (mNextIdlePendingDelay != 0) {
3333 pw.print(" mNextIdlePendingDelay=");
3334 TimeUtils.formatDuration(mNextIdlePendingDelay, pw);
3335 pw.println();
3336 }
3337 if (mNextIdleDelay != 0) {
3338 pw.print(" mNextIdleDelay=");
3339 TimeUtils.formatDuration(mNextIdleDelay, pw);
3340 pw.println();
3341 }
Dianne Hackborn953fc942016-03-29 15:36:24 -07003342 if (mNextLightIdleDelay != 0) {
3343 pw.print(" mNextIdleDelay=");
3344 TimeUtils.formatDuration(mNextLightIdleDelay, pw);
3345 pw.println();
3346 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003347 if (mNextLightAlarmTime != 0) {
3348 pw.print(" mNextLightAlarmTime=");
3349 TimeUtils.formatDuration(mNextLightAlarmTime, SystemClock.elapsedRealtime(), pw);
3350 pw.println();
3351 }
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08003352 if (mCurIdleBudget != 0) {
3353 pw.print(" mCurIdleBudget=");
3354 TimeUtils.formatDuration(mCurIdleBudget, pw);
3355 pw.println();
3356 }
3357 if (mMaintenanceStartTime != 0) {
3358 pw.print(" mMaintenanceStartTime=");
3359 TimeUtils.formatDuration(mMaintenanceStartTime, SystemClock.elapsedRealtime(), pw);
3360 pw.println();
3361 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003362 if (mJobsActive) {
3363 pw.print(" mJobsActive="); pw.println(mJobsActive);
3364 }
3365 if (mAlarmsActive) {
3366 pw.print(" mAlarmsActive="); pw.println(mAlarmsActive);
3367 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003368 }
3369 }
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003370
3371 void dumpTempWhitelistSchedule(PrintWriter pw, boolean printTitle) {
3372 final int size = mTempWhitelistAppIdEndTimes.size();
3373 if (size > 0) {
3374 String prefix = "";
3375 if (printTitle) {
3376 pw.println(" Temp whitelist schedule:");
3377 prefix = " ";
3378 }
3379 final long timeNow = SystemClock.elapsedRealtime();
3380 for (int i = 0; i < size; i++) {
3381 pw.print(prefix);
3382 pw.print("UID=");
3383 pw.print(mTempWhitelistAppIdEndTimes.keyAt(i));
3384 pw.print(": ");
3385 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.valueAt(i);
3386 TimeUtils.formatDuration(entry.first.value, timeNow, pw);
3387 pw.print(" - ");
3388 pw.println(entry.second);
3389 }
3390 }
3391 }
3392 }