blob: 985f16d910bc7e065886c5aa02fddaa5f6143b0e [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
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800798 LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT = mParser.getDurationMillis(
Dianne Hackborn953fc942016-03-29 15:36:24 -0700799 KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT,
800 !COMPRESS_TIME ? 5 * 60 * 1000L : 15 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800801 LIGHT_PRE_IDLE_TIMEOUT = mParser.getDurationMillis(KEY_LIGHT_PRE_IDLE_TIMEOUT,
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700802 !COMPRESS_TIME ? 10 * 60 * 1000L : 30 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800803 LIGHT_IDLE_TIMEOUT = mParser.getDurationMillis(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);
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800807 LIGHT_MAX_IDLE_TIMEOUT = mParser.getDurationMillis(KEY_LIGHT_MAX_IDLE_TIMEOUT,
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700808 !COMPRESS_TIME ? 15 * 60 * 1000L : 60 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800809 LIGHT_IDLE_MAINTENANCE_MIN_BUDGET = mParser.getDurationMillis(
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800810 KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET,
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700811 !COMPRESS_TIME ? 1 * 60 * 1000L : 15 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800812 LIGHT_IDLE_MAINTENANCE_MAX_BUDGET = mParser.getDurationMillis(
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800813 KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET,
814 !COMPRESS_TIME ? 5 * 60 * 1000L : 30 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800815 MIN_LIGHT_MAINTENANCE_TIME = mParser.getDurationMillis(
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700816 KEY_MIN_LIGHT_MAINTENANCE_TIME,
817 !COMPRESS_TIME ? 5 * 1000L : 1 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800818 MIN_DEEP_MAINTENANCE_TIME = mParser.getDurationMillis(
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700819 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;
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800822 INACTIVE_TIMEOUT = mParser.getDurationMillis(KEY_INACTIVE_TIMEOUT,
Joe LaPenna0c5d3e92016-03-24 13:29:56 -0700823 !COMPRESS_TIME ? inactiveTimeoutDefault : (inactiveTimeoutDefault / 10));
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800824 SENSING_TIMEOUT = mParser.getDurationMillis(KEY_SENSING_TIMEOUT,
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700825 !DEBUG ? 4 * 60 * 1000L : 60 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800826 LOCATING_TIMEOUT = mParser.getDurationMillis(KEY_LOCATING_TIMEOUT,
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700827 !DEBUG ? 30 * 1000L : 15 * 1000L);
828 LOCATION_ACCURACY = mParser.getFloat(KEY_LOCATION_ACCURACY, 20);
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800829 MOTION_INACTIVE_TIMEOUT = mParser.getDurationMillis(KEY_MOTION_INACTIVE_TIMEOUT,
Adam Lesinski31c05d12015-06-09 17:34:04 -0700830 !COMPRESS_TIME ? 10 * 60 * 1000L : 60 * 1000L);
Michael Kwan88871462017-08-21 13:13:37 -0700831 long idleAfterInactiveTimeout = (mSmallBatteryDevice ? 15 : 30) * 60 * 1000L;
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800832 IDLE_AFTER_INACTIVE_TIMEOUT = mParser.getDurationMillis(
833 KEY_IDLE_AFTER_INACTIVE_TIMEOUT,
Joe LaPenna0c5d3e92016-03-24 13:29:56 -0700834 !COMPRESS_TIME ? idleAfterInactiveTimeout
835 : (idleAfterInactiveTimeout / 10));
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800836 IDLE_PENDING_TIMEOUT = mParser.getDurationMillis(KEY_IDLE_PENDING_TIMEOUT,
Adam Lesinski31c05d12015-06-09 17:34:04 -0700837 !COMPRESS_TIME ? 5 * 60 * 1000L : 30 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800838 MAX_IDLE_PENDING_TIMEOUT = mParser.getDurationMillis(KEY_MAX_IDLE_PENDING_TIMEOUT,
Adam Lesinski31c05d12015-06-09 17:34:04 -0700839 !COMPRESS_TIME ? 10 * 60 * 1000L : 60 * 1000L);
840 IDLE_PENDING_FACTOR = mParser.getFloat(KEY_IDLE_PENDING_FACTOR,
841 2f);
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800842 IDLE_TIMEOUT = mParser.getDurationMillis(KEY_IDLE_TIMEOUT,
Adam Lesinski31c05d12015-06-09 17:34:04 -0700843 !COMPRESS_TIME ? 60 * 60 * 1000L : 6 * 60 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800844 MAX_IDLE_TIMEOUT = mParser.getDurationMillis(KEY_MAX_IDLE_TIMEOUT,
Adam Lesinski31c05d12015-06-09 17:34:04 -0700845 !COMPRESS_TIME ? 6 * 60 * 60 * 1000L : 30 * 60 * 1000L);
846 IDLE_FACTOR = mParser.getFloat(KEY_IDLE_FACTOR,
847 2f);
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800848 MIN_TIME_TO_ALARM = mParser.getDurationMillis(KEY_MIN_TIME_TO_ALARM,
Adam Lesinski31c05d12015-06-09 17:34:04 -0700849 !COMPRESS_TIME ? 60 * 60 * 1000L : 6 * 60 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800850 MAX_TEMP_APP_WHITELIST_DURATION = mParser.getDurationMillis(
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700851 KEY_MAX_TEMP_APP_WHITELIST_DURATION, 5 * 60 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800852 MMS_TEMP_APP_WHITELIST_DURATION = mParser.getDurationMillis(
Dianne Hackborn0b6134b2015-07-14 18:48:07 -0700853 KEY_MMS_TEMP_APP_WHITELIST_DURATION, 60 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800854 SMS_TEMP_APP_WHITELIST_DURATION = mParser.getDurationMillis(
Dianne Hackborn451c3462015-07-21 17:39:46 -0700855 KEY_SMS_TEMP_APP_WHITELIST_DURATION, 20 * 1000L);
Amith Yamasani761d3ff2017-12-14 17:50:03 -0800856 NOTIFICATION_WHITELIST_DURATION = mParser.getDurationMillis(
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700857 KEY_NOTIFICATION_WHITELIST_DURATION, 30 * 1000L);
Adam Lesinski31c05d12015-06-09 17:34:04 -0700858 }
859 }
860
861 void dump(PrintWriter pw) {
862 pw.println(" Settings:");
863
Dianne Hackborn953fc942016-03-29 15:36:24 -0700864 pw.print(" "); pw.print(KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT); pw.print("=");
865 TimeUtils.formatDuration(LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT, pw);
866 pw.println();
867
Dianne Hackborn945c9c92016-03-30 14:55:00 -0700868 pw.print(" "); pw.print(KEY_LIGHT_PRE_IDLE_TIMEOUT); pw.print("=");
869 TimeUtils.formatDuration(LIGHT_PRE_IDLE_TIMEOUT, pw);
870 pw.println();
871
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700872 pw.print(" "); pw.print(KEY_LIGHT_IDLE_TIMEOUT); pw.print("=");
873 TimeUtils.formatDuration(LIGHT_IDLE_TIMEOUT, pw);
874 pw.println();
875
Dianne Hackborn953fc942016-03-29 15:36:24 -0700876 pw.print(" "); pw.print(KEY_LIGHT_IDLE_FACTOR); pw.print("=");
877 pw.print(LIGHT_IDLE_FACTOR);
878 pw.println();
879
880 pw.print(" "); pw.print(KEY_LIGHT_MAX_IDLE_TIMEOUT); pw.print("=");
881 TimeUtils.formatDuration(LIGHT_MAX_IDLE_TIMEOUT, pw);
882 pw.println();
883
Dianne Hackborn8ed2b972015-11-18 14:52:04 -0800884 pw.print(" "); pw.print(KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET); pw.print("=");
885 TimeUtils.formatDuration(LIGHT_IDLE_MAINTENANCE_MIN_BUDGET, pw);
886 pw.println();
887
888 pw.print(" "); pw.print(KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET); pw.print("=");
889 TimeUtils.formatDuration(LIGHT_IDLE_MAINTENANCE_MAX_BUDGET, pw);
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700890 pw.println();
891
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700892 pw.print(" "); pw.print(KEY_MIN_LIGHT_MAINTENANCE_TIME); pw.print("=");
893 TimeUtils.formatDuration(MIN_LIGHT_MAINTENANCE_TIME, pw);
894 pw.println();
895
896 pw.print(" "); pw.print(KEY_MIN_DEEP_MAINTENANCE_TIME); pw.print("=");
897 TimeUtils.formatDuration(MIN_DEEP_MAINTENANCE_TIME, pw);
898 pw.println();
899
Dianne Hackborna750a632015-06-16 17:18:23 -0700900 pw.print(" "); pw.print(KEY_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700901 TimeUtils.formatDuration(INACTIVE_TIMEOUT, pw);
902 pw.println();
903
Dianne Hackborna750a632015-06-16 17:18:23 -0700904 pw.print(" "); pw.print(KEY_SENSING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700905 TimeUtils.formatDuration(SENSING_TIMEOUT, pw);
906 pw.println();
907
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700908 pw.print(" "); pw.print(KEY_LOCATING_TIMEOUT); pw.print("=");
909 TimeUtils.formatDuration(LOCATING_TIMEOUT, pw);
910 pw.println();
911
912 pw.print(" "); pw.print(KEY_LOCATION_ACCURACY); pw.print("=");
913 pw.print(LOCATION_ACCURACY); pw.print("m");
914 pw.println();
915
Dianne Hackborna750a632015-06-16 17:18:23 -0700916 pw.print(" "); pw.print(KEY_MOTION_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700917 TimeUtils.formatDuration(MOTION_INACTIVE_TIMEOUT, pw);
918 pw.println();
919
Dianne Hackborna750a632015-06-16 17:18:23 -0700920 pw.print(" "); pw.print(KEY_IDLE_AFTER_INACTIVE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700921 TimeUtils.formatDuration(IDLE_AFTER_INACTIVE_TIMEOUT, pw);
922 pw.println();
923
Dianne Hackborna750a632015-06-16 17:18:23 -0700924 pw.print(" "); pw.print(KEY_IDLE_PENDING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700925 TimeUtils.formatDuration(IDLE_PENDING_TIMEOUT, pw);
926 pw.println();
927
Dianne Hackborna750a632015-06-16 17:18:23 -0700928 pw.print(" "); pw.print(KEY_MAX_IDLE_PENDING_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700929 TimeUtils.formatDuration(MAX_IDLE_PENDING_TIMEOUT, pw);
930 pw.println();
931
Dianne Hackborna750a632015-06-16 17:18:23 -0700932 pw.print(" "); pw.print(KEY_IDLE_PENDING_FACTOR); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700933 pw.println(IDLE_PENDING_FACTOR);
934
Dianne Hackborna750a632015-06-16 17:18:23 -0700935 pw.print(" "); pw.print(KEY_IDLE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700936 TimeUtils.formatDuration(IDLE_TIMEOUT, pw);
937 pw.println();
938
Dianne Hackborna750a632015-06-16 17:18:23 -0700939 pw.print(" "); pw.print(KEY_MAX_IDLE_TIMEOUT); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700940 TimeUtils.formatDuration(MAX_IDLE_TIMEOUT, pw);
941 pw.println();
942
Dianne Hackborna750a632015-06-16 17:18:23 -0700943 pw.print(" "); pw.print(KEY_IDLE_FACTOR); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700944 pw.println(IDLE_FACTOR);
945
Dianne Hackborna750a632015-06-16 17:18:23 -0700946 pw.print(" "); pw.print(KEY_MIN_TIME_TO_ALARM); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700947 TimeUtils.formatDuration(MIN_TIME_TO_ALARM, pw);
948 pw.println();
949
Dianne Hackborna750a632015-06-16 17:18:23 -0700950 pw.print(" "); pw.print(KEY_MAX_TEMP_APP_WHITELIST_DURATION); pw.print("=");
Adam Lesinski31c05d12015-06-09 17:34:04 -0700951 TimeUtils.formatDuration(MAX_TEMP_APP_WHITELIST_DURATION, pw);
952 pw.println();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700953
954 pw.print(" "); pw.print(KEY_MMS_TEMP_APP_WHITELIST_DURATION); pw.print("=");
955 TimeUtils.formatDuration(MMS_TEMP_APP_WHITELIST_DURATION, pw);
956 pw.println();
Dianne Hackborn451c3462015-07-21 17:39:46 -0700957
958 pw.print(" "); pw.print(KEY_SMS_TEMP_APP_WHITELIST_DURATION); pw.print("=");
959 TimeUtils.formatDuration(SMS_TEMP_APP_WHITELIST_DURATION, pw);
960 pw.println();
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700961
962 pw.print(" "); pw.print(KEY_NOTIFICATION_WHITELIST_DURATION); pw.print("=");
963 TimeUtils.formatDuration(NOTIFICATION_WHITELIST_DURATION, pw);
964 pw.println();
Adam Lesinski31c05d12015-06-09 17:34:04 -0700965 }
966 }
967
968 private Constants mConstants;
969
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700970 @Override
971 public void onAnyMotionResult(int result) {
972 if (DEBUG) Slog.d(TAG, "onAnyMotionResult(" + result + ")");
Kevin Gabayan92f15e62016-04-04 17:52:22 -0700973 if (result != AnyMotionDetector.RESULT_UNKNOWN) {
974 synchronized (this) {
975 cancelSensingTimeoutAlarmLocked();
976 }
977 }
Kevin Gabayandcf47012016-07-08 10:41:24 -0700978 if ((result == AnyMotionDetector.RESULT_MOVED) ||
979 (result == AnyMotionDetector.RESULT_UNKNOWN)) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700980 synchronized (this) {
Kevin Gabayandcf47012016-07-08 10:41:24 -0700981 handleMotionDetectedLocked(mConstants.INACTIVE_TIMEOUT, "non_stationary");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700982 }
983 } else if (result == AnyMotionDetector.RESULT_STATIONARY) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700984 if (mState == STATE_SENSING) {
985 // If we are currently sensing, it is time to move to locating.
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700986 synchronized (this) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700987 mNotMoving = true;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800988 stepIdleStateLocked("s:stationary");
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700989 }
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700990 } else if (mState == STATE_LOCATING) {
991 // If we are currently locating, note that we are not moving and step
992 // if we have located the position.
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700993 synchronized (this) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700994 mNotMoving = true;
995 if (mLocated) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800996 stepIdleStateLocked("s:stationary");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -0700997 }
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700998 }
999 }
1000 }
1001 }
1002
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001003 private static final int MSG_WRITE_CONFIG = 1;
1004 private static final int MSG_REPORT_IDLE_ON = 2;
1005 private static final int MSG_REPORT_IDLE_ON_LIGHT = 3;
1006 private static final int MSG_REPORT_IDLE_OFF = 4;
1007 private static final int MSG_REPORT_ACTIVE = 5;
1008 private static final int MSG_TEMP_APP_WHITELIST_TIMEOUT = 6;
1009 private static final int MSG_REPORT_MAINTENANCE_ACTIVITY = 7;
1010 private static final int MSG_FINISH_IDLE_OP = 8;
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001011 private static final int MSG_REPORT_TEMP_APP_WHITELIST_CHANGED = 9;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001012
1013 final class MyHandler extends Handler {
1014 MyHandler(Looper looper) {
1015 super(looper);
1016 }
1017
1018 @Override public void handleMessage(Message msg) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001019 if (DEBUG) Slog.d(TAG, "handleMessage(" + msg.what + ")");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001020 switch (msg.what) {
1021 case MSG_WRITE_CONFIG: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001022 // Does not hold a wakelock. Just let this happen whenever.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001023 handleWriteConfigFile();
1024 } break;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001025 case MSG_REPORT_IDLE_ON:
1026 case MSG_REPORT_IDLE_ON_LIGHT: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001027 // mGoingIdleWakeLock is held at this point
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001028 EventLogTags.writeDeviceIdleOnStart();
Dianne Hackbornb6843652016-02-22 12:20:13 -08001029 final boolean deepChanged;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001030 final boolean lightChanged;
1031 if (msg.what == MSG_REPORT_IDLE_ON) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001032 deepChanged = mLocalPowerManager.setDeviceIdleMode(true);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001033 lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
1034 } else {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001035 deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001036 lightChanged = mLocalPowerManager.setLightDeviceIdleMode(true);
1037 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001038 try {
1039 mNetworkPolicyManager.setDeviceIdleMode(true);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001040 mBatteryStats.noteDeviceIdleMode(msg.what == MSG_REPORT_IDLE_ON
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07001041 ? BatteryStats.DEVICE_IDLE_MODE_DEEP
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001042 : BatteryStats.DEVICE_IDLE_MODE_LIGHT, null, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001043 } catch (RemoteException e) {
1044 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001045 if (deepChanged) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001046 getContext().sendBroadcastAsUser(mIdleIntent, UserHandle.ALL);
1047 }
1048 if (lightChanged) {
1049 getContext().sendBroadcastAsUser(mLightIdleIntent, UserHandle.ALL);
1050 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001051 EventLogTags.writeDeviceIdleOnComplete();
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001052 mGoingIdleWakeLock.release();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001053 } break;
1054 case MSG_REPORT_IDLE_OFF: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001055 // mActiveIdleWakeLock is held at this point
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001056 EventLogTags.writeDeviceIdleOffStart("unknown");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001057 final boolean deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001058 final boolean lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001059 try {
1060 mNetworkPolicyManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001061 mBatteryStats.noteDeviceIdleMode(BatteryStats.DEVICE_IDLE_MODE_OFF,
1062 null, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001063 } catch (RemoteException e) {
1064 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001065 if (deepChanged) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001066 incActiveIdleOps();
1067 getContext().sendOrderedBroadcastAsUser(mIdleIntent, UserHandle.ALL,
1068 null, mIdleStartedDoneReceiver, null, 0, null, null);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001069 }
1070 if (lightChanged) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001071 incActiveIdleOps();
1072 getContext().sendOrderedBroadcastAsUser(mLightIdleIntent, UserHandle.ALL,
1073 null, mIdleStartedDoneReceiver, null, 0, null, null);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001074 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001075 // Always start with one active op for the message being sent here.
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001076 // Now we are done!
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001077 decActiveIdleOps();
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001078 EventLogTags.writeDeviceIdleOffComplete();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001079 } break;
1080 case MSG_REPORT_ACTIVE: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001081 // The device is awake at this point, so no wakelock necessary.
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001082 String activeReason = (String)msg.obj;
1083 int activeUid = msg.arg1;
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001084 EventLogTags.writeDeviceIdleOffStart(
1085 activeReason != null ? activeReason : "unknown");
Dianne Hackbornb6843652016-02-22 12:20:13 -08001086 final boolean deepChanged = mLocalPowerManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001087 final boolean lightChanged = mLocalPowerManager.setLightDeviceIdleMode(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001088 try {
1089 mNetworkPolicyManager.setDeviceIdleMode(false);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001090 mBatteryStats.noteDeviceIdleMode(BatteryStats.DEVICE_IDLE_MODE_OFF,
1091 activeReason, activeUid);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001092 } catch (RemoteException e) {
1093 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08001094 if (deepChanged) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001095 getContext().sendBroadcastAsUser(mIdleIntent, UserHandle.ALL);
1096 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001097 if (lightChanged) {
1098 getContext().sendBroadcastAsUser(mLightIdleIntent, UserHandle.ALL);
1099 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001100 EventLogTags.writeDeviceIdleOffComplete();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001101 } break;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001102 case MSG_TEMP_APP_WHITELIST_TIMEOUT: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001103 // TODO: What is keeping the device awake at this point? Does it need to be?
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001104 int uid = msg.arg1;
1105 checkTempAppWhitelistTimeout(uid);
1106 } break;
Yao Chenca5edbb2016-01-13 14:44:36 -08001107 case MSG_REPORT_MAINTENANCE_ACTIVITY: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001108 // TODO: What is keeping the device awake at this point? Does it need to be?
Yao Chenca5edbb2016-01-13 14:44:36 -08001109 boolean active = (msg.arg1 == 1);
1110 final int size = mMaintenanceActivityListeners.beginBroadcast();
1111 try {
1112 for (int i = 0; i < size; i++) {
1113 try {
1114 mMaintenanceActivityListeners.getBroadcastItem(i)
1115 .onMaintenanceActivityChanged(active);
1116 } catch (RemoteException ignored) {
1117 }
1118 }
1119 } finally {
1120 mMaintenanceActivityListeners.finishBroadcast();
1121 }
1122 } break;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001123 case MSG_FINISH_IDLE_OP: {
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001124 // mActiveIdleWakeLock is held at this point
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001125 decActiveIdleOps();
1126 } break;
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001127 case MSG_REPORT_TEMP_APP_WHITELIST_CHANGED: {
1128 final int appId = msg.arg1;
1129 final boolean added = (msg.arg2 == 1);
1130 mNetworkPolicyManagerInternal.onTempPowerSaveWhitelistChange(appId, added);
1131 } break;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001132 }
1133 }
1134 }
1135
1136 final MyHandler mHandler;
1137
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001138 BinderService mBinderService;
1139
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001140 private final class BinderService extends IDeviceIdleController.Stub {
1141 @Override public void addPowerSaveWhitelistApp(String name) {
Eugene Susla6a7006a2017-03-13 12:57:58 -07001142 if (DEBUG) {
1143 Slog.i(TAG, "addPowerSaveWhitelistApp(name = " + name + ")");
1144 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001145 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1146 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001147 long ident = Binder.clearCallingIdentity();
1148 try {
1149 addPowerSaveWhitelistAppInternal(name);
1150 } finally {
1151 Binder.restoreCallingIdentity(ident);
1152 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001153 }
1154
1155 @Override public void removePowerSaveWhitelistApp(String name) {
Eugene Susla6a7006a2017-03-13 12:57:58 -07001156 if (DEBUG) {
1157 Slog.i(TAG, "removePowerSaveWhitelistApp(name = " + name + ")");
1158 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001159 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1160 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001161 long ident = Binder.clearCallingIdentity();
1162 try {
1163 removePowerSaveWhitelistAppInternal(name);
1164 } finally {
1165 Binder.restoreCallingIdentity(ident);
1166 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001167 }
1168
Suprabh Shukla08105642017-09-26 14:45:30 -07001169 @Override public void removeSystemPowerWhitelistApp(String name) {
1170 if (DEBUG) {
1171 Slog.d(TAG, "removeAppFromSystemWhitelist(name = " + name + ")");
1172 }
1173 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1174 null);
1175 long ident = Binder.clearCallingIdentity();
1176 try {
1177 removeSystemPowerWhitelistAppInternal(name);
1178 } finally {
1179 Binder.restoreCallingIdentity(ident);
1180 }
1181 }
1182
1183 @Override public void restoreSystemPowerWhitelistApp(String name) {
1184 if (DEBUG) {
1185 Slog.d(TAG, "restoreAppToSystemWhitelist(name = " + name + ")");
1186 }
1187 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
1188 null);
1189 long ident = Binder.clearCallingIdentity();
1190 try {
1191 restoreSystemPowerWhitelistAppInternal(name);
1192 } finally {
1193 Binder.restoreCallingIdentity(ident);
1194 }
1195 }
1196
1197 public String[] getRemovedSystemPowerWhitelistApps() {
1198 return getRemovedSystemPowerWhitelistAppsInternal();
1199 }
1200
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001201 @Override public String[] getSystemPowerWhitelistExceptIdle() {
1202 return getSystemPowerWhitelistExceptIdleInternal();
1203 }
1204
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001205 @Override public String[] getSystemPowerWhitelist() {
1206 return getSystemPowerWhitelistInternal();
1207 }
1208
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001209 @Override public String[] getUserPowerWhitelist() {
1210 return getUserPowerWhitelistInternal();
1211 }
1212
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001213 @Override public String[] getFullPowerWhitelistExceptIdle() {
1214 return getFullPowerWhitelistExceptIdleInternal();
1215 }
1216
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001217 @Override public String[] getFullPowerWhitelist() {
1218 return getFullPowerWhitelistInternal();
1219 }
1220
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001221 @Override public int[] getAppIdWhitelistExceptIdle() {
1222 return getAppIdWhitelistExceptIdleInternal();
1223 }
1224
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001225 @Override public int[] getAppIdWhitelist() {
1226 return getAppIdWhitelistInternal();
1227 }
1228
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001229 @Override public int[] getAppIdUserWhitelist() {
1230 return getAppIdUserWhitelistInternal();
1231 }
1232
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001233 @Override public int[] getAppIdTempWhitelist() {
1234 return getAppIdTempWhitelistInternal();
1235 }
1236
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001237 @Override public boolean isPowerSaveWhitelistExceptIdleApp(String name) {
1238 return isPowerSaveWhitelistExceptIdleAppInternal(name);
1239 }
1240
Amith Yamasani06bf8242015-05-08 16:36:21 -07001241 @Override public boolean isPowerSaveWhitelistApp(String name) {
1242 return isPowerSaveWhitelistAppInternal(name);
1243 }
1244
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001245 @Override public void addPowerSaveTempWhitelistApp(String packageName, long duration,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001246 int userId, String reason) throws RemoteException {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001247 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001248 }
1249
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001250 @Override public long addPowerSaveTempWhitelistAppForMms(String packageName,
1251 int userId, String reason) throws RemoteException {
1252 long duration = mConstants.MMS_TEMP_APP_WHITELIST_DURATION;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001253 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001254 return duration;
1255 }
1256
Dianne Hackborn451c3462015-07-21 17:39:46 -07001257 @Override public long addPowerSaveTempWhitelistAppForSms(String packageName,
1258 int userId, String reason) throws RemoteException {
1259 long duration = mConstants.SMS_TEMP_APP_WHITELIST_DURATION;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001260 addPowerSaveTempWhitelistAppChecked(packageName, duration, userId, reason);
Dianne Hackborn451c3462015-07-21 17:39:46 -07001261 return duration;
1262 }
1263
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001264 @Override public void exitIdle(String reason) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001265 getContext().enforceCallingOrSelfPermission(Manifest.permission.DEVICE_POWER,
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001266 null);
Dianne Hackbornc9b2cd12016-01-20 10:54:29 -08001267 long ident = Binder.clearCallingIdentity();
1268 try {
1269 exitIdleInternal(reason);
1270 } finally {
1271 Binder.restoreCallingIdentity(ident);
1272 }
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001273 }
1274
Yao Chenca5edbb2016-01-13 14:44:36 -08001275 @Override public boolean registerMaintenanceActivityListener(
1276 IMaintenanceActivityListener listener) {
1277 return DeviceIdleController.this.registerMaintenanceActivityListener(listener);
1278 }
1279
1280 @Override public void unregisterMaintenanceActivityListener(
1281 IMaintenanceActivityListener listener) {
1282 DeviceIdleController.this.unregisterMaintenanceActivityListener(listener);
1283 }
1284
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001285 @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1286 DeviceIdleController.this.dump(fd, pw, args);
1287 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001288
1289 @Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07001290 FileDescriptor err, String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
1291 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001292 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001293 }
1294
Felipe Lemeef134662016-08-10 14:46:39 -07001295 public class LocalService {
Christopher Tatee0be7e82017-02-08 17:38:20 -08001296 // duration in milliseconds
1297 public void addPowerSaveTempWhitelistApp(int callingUid, String packageName,
1298 long duration, int userId, boolean sync, String reason) {
1299 addPowerSaveTempWhitelistAppInternal(callingUid, packageName, duration,
1300 userId, sync, reason);
1301 }
1302
1303 // duration in milliseconds
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001304 public void addPowerSaveTempWhitelistAppDirect(int appId, long duration, boolean sync,
1305 String reason) {
1306 addPowerSaveTempWhitelistAppDirectInternal(0, appId, duration, sync, reason);
1307 }
1308
Christopher Tatee0be7e82017-02-08 17:38:20 -08001309 // duration in milliseconds
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001310 public long getNotificationWhitelistDuration() {
1311 return mConstants.NOTIFICATION_WHITELIST_DURATION;
1312 }
1313
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001314 public void setJobsActive(boolean active) {
1315 DeviceIdleController.this.setJobsActive(active);
1316 }
1317
1318 // Up-call from alarm manager.
1319 public void setAlarmsActive(boolean active) {
1320 DeviceIdleController.this.setAlarmsActive(active);
1321 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001322
Christopher Tate42a386b2016-11-07 12:21:21 -08001323 /** Is the app on any of the power save whitelists, whether system or user? */
1324 public boolean isAppOnWhitelist(int appid) {
1325 return DeviceIdleController.this.isAppOnWhitelistInternal(appid);
1326 }
1327
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001328 /**
1329 * Returns the array of app ids whitelisted by user. Take care not to
1330 * modify this, as it is a reference to the original copy. But the reference
1331 * can change when the list changes, so it needs to be re-acquired when
1332 * {@link PowerManager#ACTION_POWER_SAVE_WHITELIST_CHANGED} is sent.
1333 */
1334 public int[] getPowerSaveWhitelistUserAppIds() {
1335 return DeviceIdleController.this.getPowerSaveWhitelistUserAppIds();
1336 }
Suprabh Shuklaa78acfd2017-10-13 19:29:36 -07001337
1338 public int[] getPowerSaveTempWhitelistAppIds() {
1339 return DeviceIdleController.this.getAppIdTempWhitelistInternal();
1340 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001341 }
1342
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001343 public DeviceIdleController(Context context) {
1344 super(context);
1345 mConfigFile = new AtomicFile(new File(getSystemDir(), "deviceidle.xml"));
1346 mHandler = new MyHandler(BackgroundThread.getHandler().getLooper());
1347 }
1348
Christopher Tate42a386b2016-11-07 12:21:21 -08001349 boolean isAppOnWhitelistInternal(int appid) {
1350 synchronized (this) {
1351 return Arrays.binarySearch(mPowerSaveWhitelistAllAppIdArray, appid) >= 0;
1352 }
1353 }
1354
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001355 int[] getPowerSaveWhitelistUserAppIds() {
1356 synchronized (this) {
1357 return mPowerSaveWhitelistUserAppIdArray;
1358 }
1359 }
1360
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001361 private static File getSystemDir() {
1362 return new File(Environment.getDataDirectory(), "system");
1363 }
1364
1365 @Override
1366 public void onStart() {
1367 final PackageManager pm = getContext().getPackageManager();
1368
1369 synchronized (this) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08001370 mLightEnabled = mDeepEnabled = getContext().getResources().getBoolean(
Dianne Hackborn92617032015-06-19 15:32:19 -07001371 com.android.internal.R.bool.config_enableAutoPowerModes);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001372 SystemConfig sysConfig = SystemConfig.getInstance();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001373 ArraySet<String> allowPowerExceptIdle = sysConfig.getAllowInPowerSaveExceptIdle();
1374 for (int i=0; i<allowPowerExceptIdle.size(); i++) {
1375 String pkg = allowPowerExceptIdle.valueAt(i);
1376 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001377 ApplicationInfo ai = pm.getApplicationInfo(pkg,
1378 PackageManager.MATCH_SYSTEM_ONLY);
1379 int appid = UserHandle.getAppId(ai.uid);
1380 mPowerSaveWhitelistAppsExceptIdle.put(ai.packageName, appid);
1381 mPowerSaveWhitelistSystemAppIdsExceptIdle.put(appid, true);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001382 } catch (PackageManager.NameNotFoundException e) {
1383 }
1384 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001385 ArraySet<String> allowPower = sysConfig.getAllowInPowerSave();
1386 for (int i=0; i<allowPower.size(); i++) {
1387 String pkg = allowPower.valueAt(i);
1388 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07001389 ApplicationInfo ai = pm.getApplicationInfo(pkg,
1390 PackageManager.MATCH_SYSTEM_ONLY);
1391 int appid = UserHandle.getAppId(ai.uid);
1392 // These apps are on both the whitelist-except-idle as well
1393 // as the full whitelist, so they apply in all cases.
1394 mPowerSaveWhitelistAppsExceptIdle.put(ai.packageName, appid);
1395 mPowerSaveWhitelistSystemAppIdsExceptIdle.put(appid, true);
1396 mPowerSaveWhitelistApps.put(ai.packageName, appid);
1397 mPowerSaveWhitelistSystemAppIds.put(appid, true);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001398 } catch (PackageManager.NameNotFoundException e) {
1399 }
1400 }
1401
Adam Lesinski31c05d12015-06-09 17:34:04 -07001402 mConstants = new Constants(mHandler, getContext().getContentResolver());
1403
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001404 readConfigFileLocked();
1405 updateWhitelistAppIdsLocked();
1406
Dianne Hackborn88c41352016-04-07 15:18:58 -07001407 mNetworkConnected = true;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001408 mScreenOn = true;
1409 // Start out assuming we are charging. If we aren't, we will at least get
1410 // a battery update the next time the level drops.
1411 mCharging = true;
1412 mState = STATE_ACTIVE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001413 mLightState = LIGHT_STATE_ACTIVE;
Adam Lesinski31c05d12015-06-09 17:34:04 -07001414 mInactiveTimeout = mConstants.INACTIVE_TIMEOUT;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001415 }
1416
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001417 mBinderService = new BinderService();
1418 publishBinderService(Context.DEVICE_IDLE_CONTROLLER, mBinderService);
Dianne Hackborna750a632015-06-16 17:18:23 -07001419 publishLocalService(LocalService.class, new LocalService());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001420 }
1421
1422 @Override
1423 public void onBootPhase(int phase) {
1424 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1425 synchronized (this) {
1426 mAlarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
1427 mBatteryStats = BatteryStatsService.getService();
Dianne Hackborn85e35642017-01-12 15:10:57 -08001428 mLocalActivityManager = getLocalService(ActivityManagerInternal.class);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001429 mLocalPowerManager = getLocalService(PowerManagerInternal.class);
Dianne Hackborn945c9c92016-03-30 14:55:00 -07001430 mPowerManager = getContext().getSystemService(PowerManager.class);
1431 mActiveIdleWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
1432 "deviceidle_maint");
1433 mActiveIdleWakeLock.setReferenceCounted(false);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08001434 mGoingIdleWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
1435 "deviceidle_going_idle");
1436 mGoingIdleWakeLock.setReferenceCounted(true);
Dianne Hackborn88c41352016-04-07 15:18:58 -07001437 mConnectivityService = (ConnectivityService)ServiceManager.getService(
1438 Context.CONNECTIVITY_SERVICE);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001439 mNetworkPolicyManager = INetworkPolicyManager.Stub.asInterface(
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07001440 ServiceManager.getService(Context.NETWORK_POLICY_SERVICE));
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001441 mNetworkPolicyManagerInternal = getLocalService(NetworkPolicyManagerInternal.class);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001442 mSensorManager = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001443 int sigMotionSensorId = getContext().getResources().getInteger(
1444 com.android.internal.R.integer.config_autoPowerModeAnyMotionSensor);
1445 if (sigMotionSensorId > 0) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001446 mMotionSensor = mSensorManager.getDefaultSensor(sigMotionSensorId, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001447 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001448 if (mMotionSensor == null && getContext().getResources().getBoolean(
Joe LaPenna23d681b2015-08-27 15:12:11 -07001449 com.android.internal.R.bool.config_autoPowerModePreferWristTilt)) {
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001450 mMotionSensor = mSensorManager.getDefaultSensor(
1451 Sensor.TYPE_WRIST_TILT_GESTURE, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001452 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001453 if (mMotionSensor == null) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07001454 // As a last ditch, fall back to SMD.
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001455 mMotionSensor = mSensorManager.getDefaultSensor(
1456 Sensor.TYPE_SIGNIFICANT_MOTION, true);
Joe LaPenna23d681b2015-08-27 15:12:11 -07001457 }
Nick Vaccaro20feaea2015-09-17 17:22:44 -07001458
Joe LaPenna23d681b2015-08-27 15:12:11 -07001459 if (getContext().getResources().getBoolean(
1460 com.android.internal.R.bool.config_autoPowerModePrefetchLocation)) {
1461 mLocationManager = (LocationManager) getContext().getSystemService(
1462 Context.LOCATION_SERVICE);
1463 mLocationRequest = new LocationRequest()
1464 .setQuality(LocationRequest.ACCURACY_FINE)
1465 .setInterval(0)
1466 .setFastestInterval(0)
1467 .setNumUpdates(1);
1468 }
1469
1470 float angleThreshold = getContext().getResources().getInteger(
1471 com.android.internal.R.integer.config_autoPowerModeThresholdAngle) / 100f;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001472 mAnyMotionDetector = new AnyMotionDetector(
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001473 (PowerManager) getContext().getSystemService(Context.POWER_SERVICE),
Joe LaPenna23d681b2015-08-27 15:12:11 -07001474 mHandler, mSensorManager, this, angleThreshold);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001475
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001476 mIdleIntent = new Intent(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001477 mIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1478 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001479 mLightIdleIntent = new Intent(PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED);
1480 mLightIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1481 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001482
1483 IntentFilter filter = new IntentFilter();
1484 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001485 getContext().registerReceiver(mReceiver, filter);
Amith Yamasaniac59f75e2016-05-05 12:38:17 -07001486
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001487 filter = new IntentFilter();
1488 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1489 filter.addDataScheme("package");
Amith Yamasaniac59f75e2016-05-05 12:38:17 -07001490 getContext().registerReceiver(mReceiver, filter);
1491
Dianne Hackborn88c41352016-04-07 15:18:58 -07001492 filter = new IntentFilter();
1493 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001494 getContext().registerReceiver(mReceiver, filter);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001495
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -07001496 filter = new IntentFilter();
1497 filter.addAction(Intent.ACTION_SCREEN_OFF);
1498 filter.addAction(Intent.ACTION_SCREEN_ON);
1499 getContext().registerReceiver(mInteractivityReceiver, filter);
1500
Dianne Hackborn85e35642017-01-12 15:10:57 -08001501 mLocalActivityManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001502 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -07001503
Makoto Onuki2206af32017-11-21 16:25:35 -08001504 passWhiteListToForceAppStandbyTrackerLocked();
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -07001505 updateInteractivityLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001506 }
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -07001507 updateConnectivityState(null);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001508 }
1509 }
1510
1511 public boolean addPowerSaveWhitelistAppInternal(String name) {
1512 synchronized (this) {
1513 try {
Dianne Hackborn1b79ad72015-10-12 10:59:47 -07001514 ApplicationInfo ai = getContext().getPackageManager().getApplicationInfo(name,
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07001515 PackageManager.MATCH_ANY_USER);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001516 if (mPowerSaveWhitelistUserApps.put(name, UserHandle.getAppId(ai.uid)) == null) {
1517 reportPowerSaveWhitelistChangedLocked();
1518 updateWhitelistAppIdsLocked();
1519 writeConfigFileLocked();
1520 }
1521 return true;
1522 } catch (PackageManager.NameNotFoundException e) {
1523 return false;
1524 }
1525 }
1526 }
1527
1528 public boolean removePowerSaveWhitelistAppInternal(String name) {
1529 synchronized (this) {
1530 if (mPowerSaveWhitelistUserApps.remove(name) != null) {
1531 reportPowerSaveWhitelistChangedLocked();
1532 updateWhitelistAppIdsLocked();
1533 writeConfigFileLocked();
1534 return true;
1535 }
1536 }
1537 return false;
1538 }
1539
Felipe Lemef8a46232016-02-10 13:51:54 -08001540 public boolean getPowerSaveWhitelistAppInternal(String name) {
1541 synchronized (this) {
1542 return mPowerSaveWhitelistUserApps.containsKey(name);
1543 }
1544 }
1545
Suprabh Shukla08105642017-09-26 14:45:30 -07001546 void resetSystemPowerWhitelistInternal() {
1547 synchronized (this) {
1548 mPowerSaveWhitelistApps.putAll(mRemovedFromSystemWhitelistApps);
1549 mRemovedFromSystemWhitelistApps.clear();
1550 reportPowerSaveWhitelistChangedLocked();
1551 updateWhitelistAppIdsLocked();
1552 writeConfigFileLocked();
1553 }
1554 }
1555
1556 public boolean restoreSystemPowerWhitelistAppInternal(String name) {
1557 synchronized (this) {
1558 if (!mRemovedFromSystemWhitelistApps.containsKey(name)) {
1559 return false;
1560 }
1561 mPowerSaveWhitelistApps.put(name, mRemovedFromSystemWhitelistApps.remove(name));
1562 reportPowerSaveWhitelistChangedLocked();
1563 updateWhitelistAppIdsLocked();
1564 writeConfigFileLocked();
1565 return true;
1566 }
1567 }
1568
1569 public boolean removeSystemPowerWhitelistAppInternal(String name) {
1570 synchronized (this) {
1571 if (!mPowerSaveWhitelistApps.containsKey(name)) {
1572 return false;
1573 }
1574 mRemovedFromSystemWhitelistApps.put(name, mPowerSaveWhitelistApps.remove(name));
1575 reportPowerSaveWhitelistChangedLocked();
1576 updateWhitelistAppIdsLocked();
1577 writeConfigFileLocked();
1578 return true;
1579 }
1580 }
1581
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07001582 public boolean addPowerSaveWhitelistExceptIdleInternal(String name) {
1583 synchronized (this) {
1584 try {
1585 final ApplicationInfo ai = getContext().getPackageManager().getApplicationInfo(name,
1586 PackageManager.MATCH_ANY_USER);
1587 if (mPowerSaveWhitelistAppsExceptIdle.put(name, UserHandle.getAppId(ai.uid))
1588 == null) {
1589 mPowerSaveWhitelistUserAppsExceptIdle.add(name);
1590 reportPowerSaveWhitelistChangedLocked();
1591 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(
1592 mPowerSaveWhitelistAppsExceptIdle, mPowerSaveWhitelistUserApps,
1593 mPowerSaveWhitelistExceptIdleAppIds);
1594 }
1595 return true;
1596 } catch (PackageManager.NameNotFoundException e) {
1597 return false;
1598 }
1599 }
1600 }
1601
1602 public void resetPowerSaveWhitelistExceptIdleInternal() {
1603 synchronized (this) {
1604 if (mPowerSaveWhitelistAppsExceptIdle.removeAll(
1605 mPowerSaveWhitelistUserAppsExceptIdle)) {
1606 reportPowerSaveWhitelistChangedLocked();
1607 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(
1608 mPowerSaveWhitelistAppsExceptIdle, mPowerSaveWhitelistUserApps,
1609 mPowerSaveWhitelistExceptIdleAppIds);
1610 mPowerSaveWhitelistUserAppsExceptIdle.clear();
1611 }
1612 }
1613 }
1614
1615 public boolean getPowerSaveWhitelistExceptIdleInternal(String name) {
1616 synchronized (this) {
1617 return mPowerSaveWhitelistAppsExceptIdle.containsKey(name);
1618 }
1619 }
1620
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001621 public String[] getSystemPowerWhitelistExceptIdleInternal() {
1622 synchronized (this) {
1623 int size = mPowerSaveWhitelistAppsExceptIdle.size();
1624 String[] apps = new String[size];
1625 for (int i = 0; i < size; i++) {
1626 apps[i] = mPowerSaveWhitelistAppsExceptIdle.keyAt(i);
1627 }
1628 return apps;
1629 }
1630 }
1631
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001632 public String[] getSystemPowerWhitelistInternal() {
1633 synchronized (this) {
1634 int size = mPowerSaveWhitelistApps.size();
1635 String[] apps = new String[size];
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001636 for (int i = 0; i < size; i++) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001637 apps[i] = mPowerSaveWhitelistApps.keyAt(i);
1638 }
1639 return apps;
1640 }
1641 }
1642
Suprabh Shukla08105642017-09-26 14:45:30 -07001643 public String[] getRemovedSystemPowerWhitelistAppsInternal() {
1644 synchronized (this) {
1645 int size = mRemovedFromSystemWhitelistApps.size();
1646 final String[] apps = new String[size];
1647 for (int i = 0; i < size; i++) {
1648 apps[i] = mRemovedFromSystemWhitelistApps.keyAt(i);
1649 }
1650 return apps;
1651 }
1652 }
1653
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001654 public String[] getUserPowerWhitelistInternal() {
1655 synchronized (this) {
1656 int size = mPowerSaveWhitelistUserApps.size();
1657 String[] apps = new String[size];
1658 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1659 apps[i] = mPowerSaveWhitelistUserApps.keyAt(i);
1660 }
1661 return apps;
1662 }
1663 }
1664
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001665 public String[] getFullPowerWhitelistExceptIdleInternal() {
1666 synchronized (this) {
1667 int size = mPowerSaveWhitelistAppsExceptIdle.size() + mPowerSaveWhitelistUserApps.size();
1668 String[] apps = new String[size];
1669 int cur = 0;
1670 for (int i = 0; i < mPowerSaveWhitelistAppsExceptIdle.size(); i++) {
1671 apps[cur] = mPowerSaveWhitelistAppsExceptIdle.keyAt(i);
1672 cur++;
1673 }
1674 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1675 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
1676 cur++;
1677 }
1678 return apps;
1679 }
1680 }
1681
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001682 public String[] getFullPowerWhitelistInternal() {
1683 synchronized (this) {
1684 int size = mPowerSaveWhitelistApps.size() + mPowerSaveWhitelistUserApps.size();
1685 String[] apps = new String[size];
1686 int cur = 0;
1687 for (int i = 0; i < mPowerSaveWhitelistApps.size(); i++) {
1688 apps[cur] = mPowerSaveWhitelistApps.keyAt(i);
1689 cur++;
1690 }
1691 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
1692 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
1693 cur++;
1694 }
1695 return apps;
1696 }
1697 }
1698
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001699 public boolean isPowerSaveWhitelistExceptIdleAppInternal(String packageName) {
1700 synchronized (this) {
1701 return mPowerSaveWhitelistAppsExceptIdle.containsKey(packageName)
1702 || mPowerSaveWhitelistUserApps.containsKey(packageName);
1703 }
1704 }
1705
Amith Yamasani06bf8242015-05-08 16:36:21 -07001706 public boolean isPowerSaveWhitelistAppInternal(String packageName) {
1707 synchronized (this) {
1708 return mPowerSaveWhitelistApps.containsKey(packageName)
1709 || mPowerSaveWhitelistUserApps.containsKey(packageName);
1710 }
1711 }
1712
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001713 public int[] getAppIdWhitelistExceptIdleInternal() {
1714 synchronized (this) {
1715 return mPowerSaveWhitelistExceptIdleAppIdArray;
1716 }
1717 }
1718
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001719 public int[] getAppIdWhitelistInternal() {
1720 synchronized (this) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001721 return mPowerSaveWhitelistAllAppIdArray;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001722 }
1723 }
1724
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001725 public int[] getAppIdUserWhitelistInternal() {
1726 synchronized (this) {
1727 return mPowerSaveWhitelistUserAppIdArray;
1728 }
1729 }
1730
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001731 public int[] getAppIdTempWhitelistInternal() {
1732 synchronized (this) {
1733 return mTempWhitelistAppIdArray;
1734 }
1735 }
1736
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001737 void addPowerSaveTempWhitelistAppChecked(String packageName, long duration,
1738 int userId, String reason) throws RemoteException {
1739 getContext().enforceCallingPermission(
1740 Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
1741 "No permission to change device idle whitelist");
1742 final int callingUid = Binder.getCallingUid();
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001743 userId = ActivityManager.getService().handleIncomingUser(
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001744 Binder.getCallingPid(),
1745 callingUid,
1746 userId,
1747 /*allowAll=*/ false,
1748 /*requireFull=*/ false,
1749 "addPowerSaveTempWhitelistApp", null);
1750 final long token = Binder.clearCallingIdentity();
1751 try {
1752 addPowerSaveTempWhitelistAppInternal(callingUid,
1753 packageName, duration, userId, true, reason);
1754 } finally {
1755 Binder.restoreCallingIdentity(token);
1756 }
1757 }
1758
Sudheer Shanka326b3112017-11-27 14:40:57 -08001759 void removePowerSaveTempWhitelistAppChecked(String packageName, int userId)
1760 throws RemoteException {
1761 getContext().enforceCallingPermission(
1762 Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
1763 "No permission to change device idle whitelist");
1764 final int callingUid = Binder.getCallingUid();
1765 userId = ActivityManager.getService().handleIncomingUser(
1766 Binder.getCallingPid(),
1767 callingUid,
1768 userId,
1769 /*allowAll=*/ false,
1770 /*requireFull=*/ false,
1771 "removePowerSaveTempWhitelistApp", null);
1772 final long token = Binder.clearCallingIdentity();
1773 try {
1774 removePowerSaveTempWhitelistAppInternal(packageName, userId);
1775 } finally {
1776 Binder.restoreCallingIdentity(token);
1777 }
1778 }
1779
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001780 /**
1781 * Adds an app to the temporary whitelist and resets the endTime for granting the
1782 * app an exemption to access network and acquire wakelocks.
1783 */
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001784 void addPowerSaveTempWhitelistAppInternal(int callingUid, String packageName,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001785 long duration, int userId, boolean sync, String reason) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001786 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001787 int uid = getContext().getPackageManager().getPackageUidAsUser(packageName, userId);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001788 int appId = UserHandle.getAppId(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001789 addPowerSaveTempWhitelistAppDirectInternal(callingUid, appId, duration, sync, reason);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001790 } catch (NameNotFoundException e) {
1791 }
1792 }
1793
Dianne Hackborna750a632015-06-16 17:18:23 -07001794 /**
1795 * Adds an app to the temporary whitelist and resets the endTime for granting the
1796 * app an exemption to access network and acquire wakelocks.
1797 */
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07001798 void addPowerSaveTempWhitelistAppDirectInternal(int callingUid, int appId,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001799 long duration, boolean sync, String reason) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001800 final long timeNow = SystemClock.elapsedRealtime();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001801 boolean informWhitelistChanged = false;
Dianne Hackborna750a632015-06-16 17:18:23 -07001802 synchronized (this) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001803 int callingAppId = UserHandle.getAppId(callingUid);
1804 if (callingAppId >= Process.FIRST_APPLICATION_UID) {
1805 if (!mPowerSaveWhitelistSystemAppIds.get(callingAppId)) {
1806 throw new SecurityException("Calling app " + UserHandle.formatUid(callingUid)
1807 + " is not on whitelist");
1808 }
1809 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001810 duration = Math.min(duration, mConstants.MAX_TEMP_APP_WHITELIST_DURATION);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001811 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.get(appId);
1812 final boolean newEntry = entry == null;
Dianne Hackborna750a632015-06-16 17:18:23 -07001813 // Set the new end time
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001814 if (newEntry) {
1815 entry = new Pair<>(new MutableLong(0), reason);
1816 mTempWhitelistAppIdEndTimes.put(appId, entry);
1817 }
1818 entry.first.value = timeNow + duration;
Dianne Hackborna750a632015-06-16 17:18:23 -07001819 if (DEBUG) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001820 Slog.d(TAG, "Adding AppId " + appId + " to temp whitelist. New entry: " + newEntry);
Dianne Hackborna750a632015-06-16 17:18:23 -07001821 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001822 if (newEntry) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001823 // No pending timeout for the app id, post a delayed message
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001824 try {
1825 mBatteryStats.noteEvent(BatteryStats.HistoryItem.EVENT_TEMP_WHITELIST_START,
1826 reason, appId);
1827 } catch (RemoteException e) {
1828 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001829 postTempActiveTimeoutMessage(appId, duration);
Dianne Hackborn85e35642017-01-12 15:10:57 -08001830 updateTempWhitelistAppIdsLocked(appId, true);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001831 if (sync) {
1832 informWhitelistChanged = true;
1833 } else {
1834 mHandler.obtainMessage(MSG_REPORT_TEMP_APP_WHITELIST_CHANGED, appId, 1)
1835 .sendToTarget();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001836 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001837 reportTempWhitelistChangedLocked();
1838 }
1839 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07001840 if (informWhitelistChanged) {
1841 mNetworkPolicyManagerInternal.onTempPowerSaveWhitelistChange(appId, true);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001842 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001843 }
1844
Sudheer Shanka326b3112017-11-27 14:40:57 -08001845 /**
1846 * Removes an app from the temporary whitelist and notifies the observers.
1847 */
1848 private void removePowerSaveTempWhitelistAppInternal(String packageName, int userId) {
1849 try {
1850 final int uid = getContext().getPackageManager().getPackageUidAsUser(
1851 packageName, userId);
1852 final int appId = UserHandle.getAppId(uid);
1853 removePowerSaveTempWhitelistAppDirectInternal(appId);
1854 } catch (NameNotFoundException e) {
1855 }
1856 }
1857
1858 private void removePowerSaveTempWhitelistAppDirectInternal(int appId) {
1859 synchronized (this) {
1860 final int idx = mTempWhitelistAppIdEndTimes.indexOfKey(appId);
1861 if (idx < 0) {
1862 // Nothing else to do
1863 return;
1864 }
1865 final String reason = mTempWhitelistAppIdEndTimes.valueAt(idx).second;
1866 mTempWhitelistAppIdEndTimes.removeAt(idx);
1867 onAppRemovedFromTempWhitelistLocked(appId, reason);
1868 }
1869 }
1870
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001871 private void postTempActiveTimeoutMessage(int uid, long delay) {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001872 if (DEBUG) {
1873 Slog.d(TAG, "postTempActiveTimeoutMessage: uid=" + uid + ", delay=" + delay);
1874 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001875 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_TEMP_APP_WHITELIST_TIMEOUT, uid, 0),
1876 delay);
1877 }
1878
1879 void checkTempAppWhitelistTimeout(int uid) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001880 final long timeNow = SystemClock.elapsedRealtime();
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001881 if (DEBUG) {
1882 Slog.d(TAG, "checkTempAppWhitelistTimeout: uid=" + uid + ", timeNow=" + timeNow);
1883 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001884 synchronized (this) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001885 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.get(uid);
1886 if (entry == null) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001887 // Nothing to do
1888 return;
1889 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001890 if (timeNow >= entry.first.value) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001891 mTempWhitelistAppIdEndTimes.delete(uid);
Sudheer Shanka326b3112017-11-27 14:40:57 -08001892 onAppRemovedFromTempWhitelistLocked(uid, entry.second);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001893 } else {
1894 // Need more time
Felipe Lemea1b79bf2016-05-24 13:06:54 -07001895 if (DEBUG) {
1896 Slog.d(TAG, "Time to remove UID " + uid + ": " + entry.first.value);
1897 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001898 postTempActiveTimeoutMessage(uid, entry.first.value - timeNow);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001899 }
1900 }
1901 }
1902
Sudheer Shanka326b3112017-11-27 14:40:57 -08001903 @GuardedBy("this")
1904 private void onAppRemovedFromTempWhitelistLocked(int appId, String reason) {
1905 if (DEBUG) {
1906 Slog.d(TAG, "Removing appId " + appId + " from temp whitelist");
1907 }
1908 updateTempWhitelistAppIdsLocked(appId, false);
1909 mHandler.obtainMessage(MSG_REPORT_TEMP_APP_WHITELIST_CHANGED, appId, 0)
1910 .sendToTarget();
1911 reportTempWhitelistChangedLocked();
1912 try {
1913 mBatteryStats.noteEvent(BatteryStats.HistoryItem.EVENT_TEMP_WHITELIST_FINISH,
1914 reason, appId);
1915 } catch (RemoteException e) {
1916 }
1917 }
1918
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001919 public void exitIdleInternal(String reason) {
1920 synchronized (this) {
1921 becomeActiveLocked(reason, Binder.getCallingUid());
1922 }
1923 }
1924
Dianne Hackborn4cb96ca2016-05-17 13:55:29 -07001925 void updateConnectivityState(Intent connIntent) {
1926 ConnectivityService cm;
1927 synchronized (this) {
1928 cm = mConnectivityService;
1929 }
1930 if (cm == null) {
1931 return;
1932 }
1933 // Note: can't call out to ConnectivityService with our lock held.
1934 NetworkInfo ni = cm.getActiveNetworkInfo();
1935 synchronized (this) {
Dianne Hackborn88c41352016-04-07 15:18:58 -07001936 boolean conn;
1937 if (ni == null) {
1938 conn = false;
1939 } else {
1940 if (connIntent == null) {
1941 conn = ni.isConnected();
1942 } else {
1943 final int networkType =
1944 connIntent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,
1945 ConnectivityManager.TYPE_NONE);
1946 if (ni.getType() != networkType) {
1947 return;
1948 }
1949 conn = !connIntent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,
1950 false);
1951 }
1952 }
1953 if (conn != mNetworkConnected) {
1954 mNetworkConnected = conn;
1955 if (conn && mLightState == LIGHT_STATE_WAITING_FOR_NETWORK) {
1956 stepLightIdleStateLocked("network");
1957 }
1958 }
1959 }
1960 }
1961
Dianne Hackborn3dba8ce2017-09-01 17:07:04 -07001962 void updateInteractivityLocked() {
1963 // The interactivity state from the power manager tells us whether the display is
1964 // in a state that we need to keep things running so they will update at a normal
1965 // frequency.
1966 boolean screenOn = mPowerManager.isInteractive();
1967 if (DEBUG) Slog.d(TAG, "updateInteractivityLocked: screenOn=" + screenOn);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001968 if (!screenOn && mScreenOn) {
1969 mScreenOn = false;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001970 if (!mForceIdle) {
1971 becomeInactiveIfAppropriateLocked();
1972 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001973 } else if (screenOn) {
1974 mScreenOn = true;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001975 if (!mForceIdle) {
1976 becomeActiveLocked("screen", Process.myUid());
1977 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001978 }
1979 }
1980
1981 void updateChargingLocked(boolean charging) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07001982 if (DEBUG) Slog.i(TAG, "updateChargingLocked: charging=" + charging);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001983 if (!charging && mCharging) {
1984 mCharging = false;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001985 if (!mForceIdle) {
1986 becomeInactiveIfAppropriateLocked();
1987 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001988 } else if (charging) {
1989 mCharging = charging;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001990 if (!mForceIdle) {
1991 becomeActiveLocked("charging", Process.myUid());
1992 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001993 }
1994 }
1995
Dianne Hackbornb6683c42015-06-18 17:40:33 -07001996 void scheduleReportActiveLocked(String activeReason, int activeUid) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07001997 Message msg = mHandler.obtainMessage(MSG_REPORT_ACTIVE, activeUid, 0, activeReason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001998 mHandler.sendMessage(msg);
1999 }
2000
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002001 void becomeActiveLocked(String activeReason, int activeUid) {
2002 if (DEBUG) Slog.i(TAG, "becomeActiveLocked, reason = " + activeReason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002003 if (mState != STATE_ACTIVE || mLightState != STATE_ACTIVE) {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002004 EventLogTags.writeDeviceIdle(STATE_ACTIVE, activeReason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002005 EventLogTags.writeDeviceIdleLight(LIGHT_STATE_ACTIVE, activeReason);
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002006 scheduleReportActiveLocked(activeReason, activeUid);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002007 mState = STATE_ACTIVE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002008 mLightState = LIGHT_STATE_ACTIVE;
Adam Lesinski31c05d12015-06-09 17:34:04 -07002009 mInactiveTimeout = mConstants.INACTIVE_TIMEOUT;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002010 mCurIdleBudget = 0;
2011 mMaintenanceStartTime = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002012 resetIdleManagementLocked();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002013 resetLightIdleManagementLocked();
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002014 addEvent(EVENT_NORMAL);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002015 }
2016 }
2017
2018 void becomeInactiveIfAppropriateLocked() {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002019 if (DEBUG) Slog.d(TAG, "becomeInactiveIfAppropriateLocked()");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002020 if ((!mScreenOn && !mCharging) || mForceIdle) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002021 // Screen has turned off; we are now going to become inactive and start
2022 // waiting to see if we will ultimately go idle.
Dianne Hackbornb6843652016-02-22 12:20:13 -08002023 if (mState == STATE_ACTIVE && mDeepEnabled) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002024 mState = STATE_INACTIVE;
2025 if (DEBUG) Slog.d(TAG, "Moved from STATE_ACTIVE to STATE_INACTIVE");
2026 resetIdleManagementLocked();
2027 scheduleAlarmLocked(mInactiveTimeout, false);
2028 EventLogTags.writeDeviceIdle(mState, "no activity");
2029 }
Dianne Hackbornb6843652016-02-22 12:20:13 -08002030 if (mLightState == LIGHT_STATE_ACTIVE && mLightEnabled) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002031 mLightState = LIGHT_STATE_INACTIVE;
2032 if (DEBUG) Slog.d(TAG, "Moved from LIGHT_STATE_ACTIVE to LIGHT_STATE_INACTIVE");
2033 resetLightIdleManagementLocked();
Dianne Hackborn953fc942016-03-29 15:36:24 -07002034 scheduleLightAlarmLocked(mConstants.LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002035 EventLogTags.writeDeviceIdleLight(mLightState, "no activity");
2036 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002037 }
2038 }
2039
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002040 void resetIdleManagementLocked() {
2041 mNextIdlePendingDelay = 0;
2042 mNextIdleDelay = 0;
Dianne Hackborn953fc942016-03-29 15:36:24 -07002043 mNextLightIdleDelay = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002044 cancelAlarmLocked();
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002045 cancelSensingTimeoutAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002046 cancelLocatingLocked();
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002047 stopMonitoringMotionLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002048 mAnyMotionDetector.stop();
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002049 }
2050
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002051 void resetLightIdleManagementLocked() {
2052 cancelLightAlarmLocked();
2053 }
2054
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002055 void exitForceIdleLocked() {
2056 if (mForceIdle) {
2057 mForceIdle = false;
2058 if (mScreenOn || mCharging) {
Dianne Hackborn88c41352016-04-07 15:18:58 -07002059 becomeActiveLocked("exit-force", Process.myUid());
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002060 }
2061 }
2062 }
2063
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002064 void stepLightIdleStateLocked(String reason) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002065 if (mLightState == LIGHT_STATE_OVERRIDE) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002066 // If we are already in deep device idle mode, then
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002067 // there is nothing left to do for light mode.
2068 return;
2069 }
2070
2071 if (DEBUG) Slog.d(TAG, "stepLightIdleStateLocked: mLightState=" + mLightState);
2072 EventLogTags.writeDeviceIdleLightStep();
2073
2074 switch (mLightState) {
2075 case LIGHT_STATE_INACTIVE:
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002076 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
Dianne Hackborn953fc942016-03-29 15:36:24 -07002077 // Reset the upcoming idle delays.
2078 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002079 mMaintenanceStartTime = 0;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002080 if (!isOpsInactiveLocked()) {
2081 // We have some active ops going on... give them a chance to finish
2082 // before going in to our first idle.
2083 mLightState = LIGHT_STATE_PRE_IDLE;
2084 EventLogTags.writeDeviceIdleLight(mLightState, reason);
2085 scheduleLightAlarmLocked(mConstants.LIGHT_PRE_IDLE_TIMEOUT);
2086 break;
2087 }
2088 // Nothing active, fall through to immediately idle.
2089 case LIGHT_STATE_PRE_IDLE:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002090 case LIGHT_STATE_IDLE_MAINTENANCE:
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002091 if (mMaintenanceStartTime != 0) {
2092 long duration = SystemClock.elapsedRealtime() - mMaintenanceStartTime;
2093 if (duration < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
2094 // We didn't use up all of our minimum budget; add this to the reserve.
2095 mCurIdleBudget += (mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET-duration);
2096 } else {
2097 // We used more than our minimum budget; this comes out of the reserve.
2098 mCurIdleBudget -= (duration-mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET);
2099 }
2100 }
2101 mMaintenanceStartTime = 0;
Dianne Hackborn953fc942016-03-29 15:36:24 -07002102 scheduleLightAlarmLocked(mNextLightIdleDelay);
2103 mNextLightIdleDelay = Math.min(mConstants.LIGHT_MAX_IDLE_TIMEOUT,
2104 (long)(mNextLightIdleDelay * mConstants.LIGHT_IDLE_FACTOR));
2105 if (mNextLightIdleDelay < mConstants.LIGHT_IDLE_TIMEOUT) {
2106 mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
2107 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002108 if (DEBUG) Slog.d(TAG, "Moved to LIGHT_STATE_IDLE.");
2109 mLightState = LIGHT_STATE_IDLE;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002110 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002111 addEvent(EVENT_LIGHT_IDLE);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08002112 mGoingIdleWakeLock.acquire();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002113 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON_LIGHT);
2114 break;
2115 case LIGHT_STATE_IDLE:
Dianne Hackborn88c41352016-04-07 15:18:58 -07002116 case LIGHT_STATE_WAITING_FOR_NETWORK:
2117 if (mNetworkConnected || mLightState == LIGHT_STATE_WAITING_FOR_NETWORK) {
2118 // We have been idling long enough, now it is time to do some work.
2119 mActiveIdleOpCount = 1;
2120 mActiveIdleWakeLock.acquire();
2121 mMaintenanceStartTime = SystemClock.elapsedRealtime();
2122 if (mCurIdleBudget < mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET) {
2123 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
2124 } else if (mCurIdleBudget > mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET) {
2125 mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MAX_BUDGET;
2126 }
2127 scheduleLightAlarmLocked(mCurIdleBudget);
2128 if (DEBUG) Slog.d(TAG,
2129 "Moved from LIGHT_STATE_IDLE to LIGHT_STATE_IDLE_MAINTENANCE.");
2130 mLightState = LIGHT_STATE_IDLE_MAINTENANCE;
2131 EventLogTags.writeDeviceIdleLight(mLightState, reason);
2132 addEvent(EVENT_LIGHT_MAINTENANCE);
2133 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
2134 } else {
2135 // We'd like to do maintenance, but currently don't have network
2136 // connectivity... let's try to wait until the network comes back.
2137 // We'll only wait for another full idle period, however, and then give up.
2138 scheduleLightAlarmLocked(mNextLightIdleDelay);
2139 if (DEBUG) Slog.d(TAG, "Moved to LIGHT_WAITING_FOR_NETWORK.");
2140 mLightState = LIGHT_STATE_WAITING_FOR_NETWORK;
2141 EventLogTags.writeDeviceIdleLight(mLightState, reason);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002142 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002143 break;
2144 }
2145 }
2146
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002147 void stepIdleStateLocked(String reason) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002148 if (DEBUG) Slog.d(TAG, "stepIdleStateLocked: mState=" + mState);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002149 EventLogTags.writeDeviceIdleStep();
2150
2151 final long now = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07002152 if ((now+mConstants.MIN_TIME_TO_ALARM) > mAlarmManager.getNextWakeFromIdleTime()) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002153 // Whoops, there is an upcoming alarm. We don't actually want to go idle.
2154 if (mState != STATE_ACTIVE) {
Dianne Hackbornb6683c42015-06-18 17:40:33 -07002155 becomeActiveLocked("alarm", Process.myUid());
Koji Fukui27b33302015-12-16 19:43:01 +09002156 becomeInactiveIfAppropriateLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002157 }
2158 return;
2159 }
2160
2161 switch (mState) {
2162 case STATE_INACTIVE:
2163 // We have now been inactive long enough, it is time to start looking
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002164 // for motion and sleep some more while doing so.
2165 startMonitoringMotionLocked();
Adam Lesinski31c05d12015-06-09 17:34:04 -07002166 scheduleAlarmLocked(mConstants.IDLE_AFTER_INACTIVE_TIMEOUT, false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002167 // Reset the upcoming idle delays.
Adam Lesinski31c05d12015-06-09 17:34:04 -07002168 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
2169 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002170 mState = STATE_IDLE_PENDING;
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002171 if (DEBUG) Slog.d(TAG, "Moved from STATE_INACTIVE to STATE_IDLE_PENDING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002172 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002173 break;
2174 case STATE_IDLE_PENDING:
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002175 mState = STATE_SENSING;
2176 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE_PENDING to STATE_SENSING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002177 EventLogTags.writeDeviceIdle(mState, reason);
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002178 scheduleSensingTimeoutAlarmLocked(mConstants.SENSING_TIMEOUT);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002179 cancelLocatingLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002180 mNotMoving = false;
2181 mLocated = false;
2182 mLastGenericLocation = null;
2183 mLastGpsLocation = null;
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002184 mAnyMotionDetector.checkForAnyMotion();
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002185 break;
2186 case STATE_SENSING:
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002187 cancelSensingTimeoutAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002188 mState = STATE_LOCATING;
2189 if (DEBUG) Slog.d(TAG, "Moved from STATE_SENSING to STATE_LOCATING.");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002190 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002191 scheduleAlarmLocked(mConstants.LOCATING_TIMEOUT, false);
Joe LaPenna23d681b2015-08-27 15:12:11 -07002192 if (mLocationManager != null
2193 && mLocationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
2194 mLocationManager.requestLocationUpdates(mLocationRequest,
2195 mGenericLocationListener, mHandler.getLooper());
2196 mLocating = true;
2197 } else {
2198 mHasNetworkLocation = false;
2199 }
2200 if (mLocationManager != null
2201 && mLocationManager.getProvider(LocationManager.GPS_PROVIDER) != null) {
2202 mHasGps = true;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002203 mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 5,
2204 mGpsLocationListener, mHandler.getLooper());
Joe LaPenna23d681b2015-08-27 15:12:11 -07002205 mLocating = true;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002206 } else {
Joe LaPenna23d681b2015-08-27 15:12:11 -07002207 mHasGps = false;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002208 }
Joe LaPenna23d681b2015-08-27 15:12:11 -07002209 // If we have a location provider, we're all set, the listeners will move state
2210 // forward.
2211 if (mLocating) {
2212 break;
2213 }
2214
2215 // Otherwise, we have to move from locating into idle maintenance.
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002216 case STATE_LOCATING:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002217 cancelAlarmLocked();
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002218 cancelLocatingLocked();
2219 mAnyMotionDetector.stop();
Dianne Hackborn953fc942016-03-29 15:36:24 -07002220
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002221 case STATE_IDLE_MAINTENANCE:
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002222 scheduleAlarmLocked(mNextIdleDelay, true);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002223 if (DEBUG) Slog.d(TAG, "Moved to STATE_IDLE. Next alarm in " + mNextIdleDelay +
2224 " ms.");
Adam Lesinski31c05d12015-06-09 17:34:04 -07002225 mNextIdleDelay = (long)(mNextIdleDelay * mConstants.IDLE_FACTOR);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002226 if (DEBUG) Slog.d(TAG, "Setting mNextIdleDelay = " + mNextIdleDelay);
Adam Lesinski31c05d12015-06-09 17:34:04 -07002227 mNextIdleDelay = Math.min(mNextIdleDelay, mConstants.MAX_IDLE_TIMEOUT);
Dianne Hackborn953fc942016-03-29 15:36:24 -07002228 if (mNextIdleDelay < mConstants.IDLE_TIMEOUT) {
2229 mNextIdleDelay = mConstants.IDLE_TIMEOUT;
2230 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002231 mState = STATE_IDLE;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002232 if (mLightState != LIGHT_STATE_OVERRIDE) {
2233 mLightState = LIGHT_STATE_OVERRIDE;
2234 cancelLightAlarmLocked();
2235 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002236 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackbornb6843652016-02-22 12:20:13 -08002237 addEvent(EVENT_DEEP_IDLE);
Joe Onorato8f0e9ced2016-12-08 17:48:49 -08002238 mGoingIdleWakeLock.acquire();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002239 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON);
2240 break;
2241 case STATE_IDLE:
2242 // We have been idling long enough, now it is time to do some work.
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002243 mActiveIdleOpCount = 1;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002244 mActiveIdleWakeLock.acquire();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002245 scheduleAlarmLocked(mNextIdlePendingDelay, false);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002246 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE to STATE_IDLE_MAINTENANCE. " +
2247 "Next alarm in " + mNextIdlePendingDelay + " ms.");
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002248 mMaintenanceStartTime = SystemClock.elapsedRealtime();
Adam Lesinski31c05d12015-06-09 17:34:04 -07002249 mNextIdlePendingDelay = Math.min(mConstants.MAX_IDLE_PENDING_TIMEOUT,
2250 (long)(mNextIdlePendingDelay * mConstants.IDLE_PENDING_FACTOR));
Dianne Hackborn953fc942016-03-29 15:36:24 -07002251 if (mNextIdlePendingDelay < mConstants.IDLE_PENDING_TIMEOUT) {
2252 mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
2253 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002254 mState = STATE_IDLE_MAINTENANCE;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002255 EventLogTags.writeDeviceIdle(mState, reason);
Dianne Hackbornb6843652016-02-22 12:20:13 -08002256 addEvent(EVENT_DEEP_MAINTENANCE);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002257 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
2258 break;
2259 }
2260 }
2261
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002262 void incActiveIdleOps() {
2263 synchronized (this) {
2264 mActiveIdleOpCount++;
2265 }
2266 }
2267
2268 void decActiveIdleOps() {
2269 synchronized (this) {
2270 mActiveIdleOpCount--;
2271 if (mActiveIdleOpCount <= 0) {
2272 exitMaintenanceEarlyIfNeededLocked();
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002273 mActiveIdleWakeLock.release();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002274 }
2275 }
2276 }
2277
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002278 void setJobsActive(boolean active) {
2279 synchronized (this) {
2280 mJobsActive = active;
Yao Chenca5edbb2016-01-13 14:44:36 -08002281 reportMaintenanceActivityIfNeededLocked();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002282 if (!active) {
2283 exitMaintenanceEarlyIfNeededLocked();
2284 }
2285 }
2286 }
2287
2288 void setAlarmsActive(boolean active) {
2289 synchronized (this) {
2290 mAlarmsActive = active;
2291 if (!active) {
2292 exitMaintenanceEarlyIfNeededLocked();
2293 }
2294 }
2295 }
2296
Yao Chenca5edbb2016-01-13 14:44:36 -08002297 boolean registerMaintenanceActivityListener(IMaintenanceActivityListener listener) {
2298 synchronized (this) {
2299 mMaintenanceActivityListeners.register(listener);
2300 return mReportedMaintenanceActivity;
2301 }
2302 }
2303
2304 void unregisterMaintenanceActivityListener(IMaintenanceActivityListener listener) {
2305 synchronized (this) {
2306 mMaintenanceActivityListeners.unregister(listener);
2307 }
2308 }
2309
2310 void reportMaintenanceActivityIfNeededLocked() {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07002311 boolean active = mJobsActive;
Yao Chenca5edbb2016-01-13 14:44:36 -08002312 if (active == mReportedMaintenanceActivity) {
2313 return;
2314 }
2315 mReportedMaintenanceActivity = active;
2316 Message msg = mHandler.obtainMessage(MSG_REPORT_MAINTENANCE_ACTIVITY,
2317 mReportedMaintenanceActivity ? 1 : 0, 0);
2318 mHandler.sendMessage(msg);
2319 }
2320
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002321 boolean isOpsInactiveLocked() {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07002322 return mActiveIdleOpCount <= 0 && !mJobsActive && !mAlarmsActive;
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002323 }
2324
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002325 void exitMaintenanceEarlyIfNeededLocked() {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002326 if (mState == STATE_IDLE_MAINTENANCE || mLightState == LIGHT_STATE_IDLE_MAINTENANCE
2327 || mLightState == LIGHT_STATE_PRE_IDLE) {
2328 if (isOpsInactiveLocked()) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002329 final long now = SystemClock.elapsedRealtime();
2330 if (DEBUG) {
2331 StringBuilder sb = new StringBuilder();
2332 sb.append("Exit: start=");
2333 TimeUtils.formatDuration(mMaintenanceStartTime, sb);
2334 sb.append(" now=");
2335 TimeUtils.formatDuration(now, sb);
2336 Slog.d(TAG, sb.toString());
2337 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002338 if (mState == STATE_IDLE_MAINTENANCE) {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002339 stepIdleStateLocked("s:early");
2340 } else if (mLightState == LIGHT_STATE_PRE_IDLE) {
2341 stepLightIdleStateLocked("s:predone");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002342 } else {
Dianne Hackborn945c9c92016-03-30 14:55:00 -07002343 stepLightIdleStateLocked("s:early");
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002344 }
2345 }
2346 }
2347 }
2348
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002349 void motionLocked() {
2350 if (DEBUG) Slog.d(TAG, "motionLocked()");
2351 // The motion sensor will have been disabled at this point
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002352 handleMotionDetectedLocked(mConstants.MOTION_INACTIVE_TIMEOUT, "motion");
2353 }
2354
2355 void handleMotionDetectedLocked(long timeout, String type) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002356 // The device is not yet active, so we want to go back to the pending idle
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002357 // state to wait again for no motion. Note that we only monitor for motion
2358 // after moving out of the inactive state, so no need to worry about that.
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002359 boolean becomeInactive = false;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002360 if (mState != STATE_ACTIVE) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002361 scheduleReportActiveLocked(type, Process.myUid());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002362 mState = STATE_ACTIVE;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002363 mInactiveTimeout = timeout;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002364 mCurIdleBudget = 0;
2365 mMaintenanceStartTime = 0;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002366 EventLogTags.writeDeviceIdle(mState, type);
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08002367 addEvent(EVENT_NORMAL);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002368 becomeInactive = true;
2369 }
2370 if (mLightState == LIGHT_STATE_OVERRIDE) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002371 // We went out of light idle mode because we had started deep idle mode... let's
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002372 // now go back and reset things so we resume light idling if appropriate.
2373 mLightState = STATE_ACTIVE;
2374 EventLogTags.writeDeviceIdleLight(mLightState, type);
2375 becomeInactive = true;
2376 }
2377 if (becomeInactive) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002378 becomeInactiveIfAppropriateLocked();
2379 }
2380 }
2381
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002382 void receivedGenericLocationLocked(Location location) {
2383 if (mState != STATE_LOCATING) {
2384 cancelLocatingLocked();
2385 return;
2386 }
2387 if (DEBUG) Slog.d(TAG, "Generic location: " + location);
2388 mLastGenericLocation = new Location(location);
Joe LaPenna23d681b2015-08-27 15:12:11 -07002389 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY && mHasGps) {
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002390 return;
2391 }
2392 mLocated = true;
2393 if (mNotMoving) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002394 stepIdleStateLocked("s:location");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002395 }
2396 }
2397
2398 void receivedGpsLocationLocked(Location location) {
2399 if (mState != STATE_LOCATING) {
2400 cancelLocatingLocked();
2401 return;
2402 }
2403 if (DEBUG) Slog.d(TAG, "GPS location: " + location);
2404 mLastGpsLocation = new Location(location);
2405 if (location.getAccuracy() > mConstants.LOCATION_ACCURACY) {
2406 return;
2407 }
2408 mLocated = true;
2409 if (mNotMoving) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002410 stepIdleStateLocked("s:gps");
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002411 }
2412 }
2413
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002414 void startMonitoringMotionLocked() {
2415 if (DEBUG) Slog.d(TAG, "startMonitoringMotionLocked()");
2416 if (mMotionSensor != null && !mMotionListener.active) {
2417 mMotionListener.registerLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002418 }
2419 }
2420
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002421 void stopMonitoringMotionLocked() {
2422 if (DEBUG) Slog.d(TAG, "stopMonitoringMotionLocked()");
2423 if (mMotionSensor != null && mMotionListener.active) {
2424 mMotionListener.unregisterLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002425 }
2426 }
2427
2428 void cancelAlarmLocked() {
2429 if (mNextAlarmTime != 0) {
2430 mNextAlarmTime = 0;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002431 mAlarmManager.cancel(mDeepAlarmListener);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002432 }
2433 }
2434
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002435 void cancelLightAlarmLocked() {
2436 if (mNextLightAlarmTime != 0) {
2437 mNextLightAlarmTime = 0;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002438 mAlarmManager.cancel(mLightAlarmListener);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002439 }
2440 }
2441
2442 void cancelLocatingLocked() {
2443 if (mLocating) {
2444 mLocationManager.removeUpdates(mGenericLocationListener);
2445 mLocationManager.removeUpdates(mGpsLocationListener);
2446 mLocating = false;
2447 }
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002448 }
2449
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002450 void cancelSensingTimeoutAlarmLocked() {
2451 if (mNextSensingTimeoutAlarmTime != 0) {
2452 mNextSensingTimeoutAlarmTime = 0;
2453 mAlarmManager.cancel(mSensingTimeoutAlarmListener);
2454 }
2455 }
2456
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002457 void scheduleAlarmLocked(long delay, boolean idleUntil) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002458 if (DEBUG) Slog.d(TAG, "scheduleAlarmLocked(" + delay + ", " + idleUntil + ")");
Nick Vaccaro20feaea2015-09-17 17:22:44 -07002459 if (mMotionSensor == null) {
Joe LaPenna23d681b2015-08-27 15:12:11 -07002460 // If there is no motion sensor on this device, then we won't schedule
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002461 // alarms, because we can't determine if the device is not moving. This effectively
Joe LaPenna23d681b2015-08-27 15:12:11 -07002462 // turns off normal execution of device idling, although it is still possible to
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002463 // manually poke it by pretending like the alarm is going off.
2464 return;
2465 }
2466 mNextAlarmTime = SystemClock.elapsedRealtime() + delay;
2467 if (idleUntil) {
2468 mAlarmManager.setIdleUntil(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002469 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002470 } else {
2471 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002472 mNextAlarmTime, "DeviceIdleController.deep", mDeepAlarmListener, mHandler);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002473 }
2474 }
2475
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002476 void scheduleLightAlarmLocked(long delay) {
2477 if (DEBUG) Slog.d(TAG, "scheduleLightAlarmLocked(" + delay + ")");
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002478 mNextLightAlarmTime = SystemClock.elapsedRealtime() + delay;
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07002479 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002480 mNextLightAlarmTime, "DeviceIdleController.light", mLightAlarmListener, mHandler);
Kevin Gabayan89ecf822015-05-18 12:10:07 -07002481 }
2482
Kevin Gabayan92f15e62016-04-04 17:52:22 -07002483 void scheduleSensingTimeoutAlarmLocked(long delay) {
2484 if (DEBUG) Slog.d(TAG, "scheduleSensingAlarmLocked(" + delay + ")");
2485 mNextSensingTimeoutAlarmTime = SystemClock.elapsedRealtime() + delay;
2486 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, mNextSensingTimeoutAlarmTime,
2487 "DeviceIdleController.sensing", mSensingTimeoutAlarmListener, mHandler);
2488 }
2489
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002490 private static int[] buildAppIdArray(ArrayMap<String, Integer> systemApps,
2491 ArrayMap<String, Integer> userApps, SparseBooleanArray outAppIds) {
2492 outAppIds.clear();
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002493 if (systemApps != null) {
2494 for (int i = 0; i < systemApps.size(); i++) {
2495 outAppIds.put(systemApps.valueAt(i), true);
2496 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002497 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002498 if (userApps != null) {
2499 for (int i = 0; i < userApps.size(); i++) {
2500 outAppIds.put(userApps.valueAt(i), true);
2501 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002502 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002503 int size = outAppIds.size();
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002504 int[] appids = new int[size];
2505 for (int i = 0; i < size; i++) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002506 appids[i] = outAppIds.keyAt(i);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002507 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002508 return appids;
2509 }
2510
2511 private void updateWhitelistAppIdsLocked() {
2512 mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(mPowerSaveWhitelistAppsExceptIdle,
2513 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistExceptIdleAppIds);
2514 mPowerSaveWhitelistAllAppIdArray = buildAppIdArray(mPowerSaveWhitelistApps,
2515 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistAllAppIds);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002516 mPowerSaveWhitelistUserAppIdArray = buildAppIdArray(null,
2517 mPowerSaveWhitelistUserApps, mPowerSaveWhitelistUserAppIds);
Dianne Hackborn85e35642017-01-12 15:10:57 -08002518 if (mLocalActivityManager != null) {
2519 if (DEBUG) {
2520 Slog.d(TAG, "Setting activity manager whitelist to "
2521 + Arrays.toString(mPowerSaveWhitelistAllAppIdArray));
2522 }
2523 mLocalActivityManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
2524 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002525 if (mLocalPowerManager != null) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002526 if (DEBUG) {
2527 Slog.d(TAG, "Setting wakelock whitelist to "
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002528 + Arrays.toString(mPowerSaveWhitelistAllAppIdArray));
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002529 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002530 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAllAppIdArray);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002531 }
Makoto Onuki2206af32017-11-21 16:25:35 -08002532 passWhiteListToForceAppStandbyTrackerLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002533 }
2534
Dianne Hackborn85e35642017-01-12 15:10:57 -08002535 private void updateTempWhitelistAppIdsLocked(int appId, boolean adding) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002536 final int size = mTempWhitelistAppIdEndTimes.size();
2537 if (mTempWhitelistAppIdArray.length != size) {
2538 mTempWhitelistAppIdArray = new int[size];
2539 }
2540 for (int i = 0; i < size; i++) {
2541 mTempWhitelistAppIdArray[i] = mTempWhitelistAppIdEndTimes.keyAt(i);
2542 }
Dianne Hackborn85e35642017-01-12 15:10:57 -08002543 if (mLocalActivityManager != null) {
2544 if (DEBUG) {
2545 Slog.d(TAG, "Setting activity manager temp whitelist to "
2546 + Arrays.toString(mTempWhitelistAppIdArray));
2547 }
2548 mLocalActivityManager.updateDeviceIdleTempWhitelist(mTempWhitelistAppIdArray, appId,
2549 adding);
2550 }
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002551 if (mLocalPowerManager != null) {
2552 if (DEBUG) {
2553 Slog.d(TAG, "Setting wakelock temp whitelist to "
2554 + Arrays.toString(mTempWhitelistAppIdArray));
2555 }
2556 mLocalPowerManager.setDeviceIdleTempWhitelist(mTempWhitelistAppIdArray);
2557 }
Makoto Onuki2206af32017-11-21 16:25:35 -08002558 passWhiteListToForceAppStandbyTrackerLocked();
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002559 }
2560
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002561 private void reportPowerSaveWhitelistChangedLocked() {
2562 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
2563 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Xiaohui Chene4de5a02015-09-22 15:33:31 -07002564 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002565 }
2566
2567 private void reportTempWhitelistChangedLocked() {
2568 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_TEMP_WHITELIST_CHANGED);
2569 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Xiaohui Chene4de5a02015-09-22 15:33:31 -07002570 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002571 }
2572
Makoto Onuki2206af32017-11-21 16:25:35 -08002573 private void passWhiteListToForceAppStandbyTrackerLocked() {
2574 ForceAppStandbyTracker.getInstance(getContext()).setPowerSaveWhitelistAppIds(
2575 mPowerSaveWhitelistAllAppIdArray,
2576 mTempWhitelistAppIdArray);
2577 }
2578
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002579 void readConfigFileLocked() {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002580 if (DEBUG) Slog.d(TAG, "Reading config from " + mConfigFile.getBaseFile());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002581 mPowerSaveWhitelistUserApps.clear();
2582 FileInputStream stream;
2583 try {
2584 stream = mConfigFile.openRead();
2585 } catch (FileNotFoundException e) {
2586 return;
2587 }
2588 try {
2589 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002590 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002591 readConfigFileLocked(parser);
2592 } catch (XmlPullParserException e) {
2593 } finally {
2594 try {
2595 stream.close();
2596 } catch (IOException e) {
2597 }
2598 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002599 }
2600
2601 private void readConfigFileLocked(XmlPullParser parser) {
2602 final PackageManager pm = getContext().getPackageManager();
2603
2604 try {
2605 int type;
2606 while ((type = parser.next()) != XmlPullParser.START_TAG
2607 && type != XmlPullParser.END_DOCUMENT) {
2608 ;
2609 }
2610
2611 if (type != XmlPullParser.START_TAG) {
2612 throw new IllegalStateException("no start tag found");
2613 }
2614
2615 int outerDepth = parser.getDepth();
2616 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
2617 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2618 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2619 continue;
2620 }
2621
2622 String tagName = parser.getName();
Suprabh Shukla08105642017-09-26 14:45:30 -07002623 switch (tagName) {
2624 case "wl":
2625 String name = parser.getAttributeValue(null, "n");
2626 if (name != null) {
2627 try {
2628 ApplicationInfo ai = pm.getApplicationInfo(name,
2629 PackageManager.MATCH_ANY_USER);
2630 mPowerSaveWhitelistUserApps.put(ai.packageName,
2631 UserHandle.getAppId(ai.uid));
2632 } catch (PackageManager.NameNotFoundException e) {
2633 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002634 }
Suprabh Shukla08105642017-09-26 14:45:30 -07002635 break;
2636 case "un-wl":
2637 final String packageName = parser.getAttributeValue(null, "n");
2638 if (mPowerSaveWhitelistApps.containsKey(packageName)) {
2639 mRemovedFromSystemWhitelistApps.put(packageName,
2640 mPowerSaveWhitelistApps.remove(packageName));
2641 }
2642 break;
2643 default:
2644 Slog.w(TAG, "Unknown element under <config>: "
2645 + parser.getName());
2646 XmlUtils.skipCurrentTag(parser);
2647 break;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002648 }
2649 }
2650
2651 } catch (IllegalStateException e) {
2652 Slog.w(TAG, "Failed parsing config " + e);
2653 } catch (NullPointerException e) {
2654 Slog.w(TAG, "Failed parsing config " + e);
2655 } catch (NumberFormatException e) {
2656 Slog.w(TAG, "Failed parsing config " + e);
2657 } catch (XmlPullParserException e) {
2658 Slog.w(TAG, "Failed parsing config " + e);
2659 } catch (IOException e) {
2660 Slog.w(TAG, "Failed parsing config " + e);
2661 } catch (IndexOutOfBoundsException e) {
2662 Slog.w(TAG, "Failed parsing config " + e);
2663 }
2664 }
2665
2666 void writeConfigFileLocked() {
2667 mHandler.removeMessages(MSG_WRITE_CONFIG);
2668 mHandler.sendEmptyMessageDelayed(MSG_WRITE_CONFIG, 5000);
2669 }
2670
2671 void handleWriteConfigFile() {
2672 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
2673
2674 try {
2675 synchronized (this) {
2676 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002677 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002678 writeConfigFileLocked(out);
2679 }
2680 } catch (IOException e) {
2681 }
2682
2683 synchronized (mConfigFile) {
2684 FileOutputStream stream = null;
2685 try {
2686 stream = mConfigFile.startWrite();
2687 memStream.writeTo(stream);
2688 stream.flush();
2689 FileUtils.sync(stream);
2690 stream.close();
2691 mConfigFile.finishWrite(stream);
2692 } catch (IOException e) {
2693 Slog.w(TAG, "Error writing config file", e);
2694 mConfigFile.failWrite(stream);
2695 }
2696 }
2697 }
2698
2699 void writeConfigFileLocked(XmlSerializer out) throws IOException {
2700 out.startDocument(null, true);
2701 out.startTag(null, "config");
2702 for (int i=0; i<mPowerSaveWhitelistUserApps.size(); i++) {
2703 String name = mPowerSaveWhitelistUserApps.keyAt(i);
2704 out.startTag(null, "wl");
2705 out.attribute(null, "n", name);
2706 out.endTag(null, "wl");
2707 }
Suprabh Shukla08105642017-09-26 14:45:30 -07002708 for (int i = 0; i < mRemovedFromSystemWhitelistApps.size(); i++) {
2709 out.startTag(null, "un-wl");
2710 out.attribute(null, "n", mRemovedFromSystemWhitelistApps.keyAt(i));
2711 out.endTag(null, "un-wl");
2712 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002713 out.endTag(null, "config");
2714 out.endDocument();
2715 }
2716
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002717 static void dumpHelp(PrintWriter pw) {
2718 pw.println("Device idle controller (deviceidle) commands:");
2719 pw.println(" help");
2720 pw.println(" Print this help text.");
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002721 pw.println(" step [light|deep]");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002722 pw.println(" Immediately step to next state, without waiting for alarm.");
Dianne Hackborn88c41352016-04-07 15:18:58 -07002723 pw.println(" force-idle [light|deep]");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002724 pw.println(" Force directly into idle mode, regardless of other device state.");
Dianne Hackborn88c41352016-04-07 15:18:58 -07002725 pw.println(" force-inactive");
2726 pw.println(" Force to be inactive, ready to freely step idle states.");
2727 pw.println(" unforce");
2728 pw.println(" Resume normal functioning after force-idle or force-inactive.");
2729 pw.println(" get [light|deep|force|screen|charging|network]");
2730 pw.println(" Retrieve the current given state.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002731 pw.println(" disable [light|deep|all]");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002732 pw.println(" Completely disable device idle mode.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002733 pw.println(" enable [light|deep|all]");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002734 pw.println(" Re-enable device idle mode after it had previously been disabled.");
Dianne Hackbornb6843652016-02-22 12:20:13 -08002735 pw.println(" enabled [light|deep|all]");
Dianne Hackborn92617032015-06-19 15:32:19 -07002736 pw.println(" Print 1 if device idle mode is currently enabled, else 0.");
Dianne Hackborn1b139682015-07-06 15:13:37 -07002737 pw.println(" whitelist");
2738 pw.println(" Print currently whitelisted apps.");
Dianne Hackborn92617032015-06-19 15:32:19 -07002739 pw.println(" whitelist [package ...]");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002740 pw.println(" Add (prefix with +) or remove (prefix with -) packages.");
Suprabh Shukla08105642017-09-26 14:45:30 -07002741 pw.println(" sys-whitelist [package ...|reset]");
2742 pw.println(" Prefix the package with '-' to remove it from the system whitelist or '+'"
2743 + " to put it back in the system whitelist.");
2744 pw.println(" Note that only packages that were"
2745 + " earlier removed from the system whitelist can be added back.");
2746 pw.println(" reset will reset the whitelist to the original state");
2747 pw.println(" Prints the system whitelist if no arguments are specified");
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07002748 pw.println(" except-idle-whitelist [package ...|reset]");
2749 pw.println(" Prefix the package with '+' to add it to whitelist or "
2750 + "'=' to check if it is already whitelisted");
2751 pw.println(" [reset] will reset the whitelist to it's original state");
2752 pw.println(" Note that unlike <whitelist> cmd, "
2753 + "changes made using this won't be persisted across boots");
Felipe Lemea1b79bf2016-05-24 13:06:54 -07002754 pw.println(" tempwhitelist");
2755 pw.println(" Print packages that are temporarily whitelisted.");
Sudheer Shanka326b3112017-11-27 14:40:57 -08002756 pw.println(" tempwhitelist [-u USER] [-d DURATION] [-r] [package]");
2757 pw.println(" Temporarily place package in whitelist for DURATION milliseconds.");
Dianne Hackborn85e35642017-01-12 15:10:57 -08002758 pw.println(" If no DURATION is specified, 10 seconds is used");
Sudheer Shanka326b3112017-11-27 14:40:57 -08002759 pw.println(" If [-r] option is used, then the package is removed from temp whitelist "
2760 + "and any [-d] is ignored");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002761 }
2762
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002763 class Shell extends ShellCommand {
2764 int userId = UserHandle.USER_SYSTEM;
2765
2766 @Override
2767 public int onCommand(String cmd) {
2768 return onShellCommand(this, cmd);
2769 }
2770
2771 @Override
2772 public void onHelp() {
2773 PrintWriter pw = getOutPrintWriter();
2774 dumpHelp(pw);
2775 }
2776 }
2777
2778 int onShellCommand(Shell shell, String cmd) {
2779 PrintWriter pw = shell.getOutPrintWriter();
2780 if ("step".equals(cmd)) {
2781 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2782 null);
2783 synchronized (this) {
2784 long token = Binder.clearCallingIdentity();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002785 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002786 try {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002787 if (arg == null || "deep".equals(arg)) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002788 stepIdleStateLocked("s:shell");
2789 pw.print("Stepped to deep: ");
2790 pw.println(stateToString(mState));
2791 } else if ("light".equals(arg)) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002792 stepLightIdleStateLocked("s:shell");
2793 pw.print("Stepped to light: "); pw.println(lightStateToString(mLightState));
2794 } else {
2795 pw.println("Unknown idle mode: " + arg);
2796 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002797 } finally {
2798 Binder.restoreCallingIdentity(token);
2799 }
2800 }
2801 } else if ("force-idle".equals(cmd)) {
2802 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2803 null);
2804 synchronized (this) {
2805 long token = Binder.clearCallingIdentity();
Dianne Hackborn88c41352016-04-07 15:18:58 -07002806 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002807 try {
Dianne Hackborn88c41352016-04-07 15:18:58 -07002808 if (arg == null || "deep".equals(arg)) {
2809 if (!mDeepEnabled) {
2810 pw.println("Unable to go deep idle; not enabled");
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002811 return -1;
2812 }
Dianne Hackborn88c41352016-04-07 15:18:58 -07002813 mForceIdle = true;
2814 becomeInactiveIfAppropriateLocked();
2815 int curState = mState;
2816 while (curState != STATE_IDLE) {
2817 stepIdleStateLocked("s:shell");
2818 if (curState == mState) {
2819 pw.print("Unable to go deep idle; stopped at ");
2820 pw.println(stateToString(mState));
2821 exitForceIdleLocked();
2822 return -1;
2823 }
2824 curState = mState;
2825 }
2826 pw.println("Now forced in to deep idle mode");
2827 } else if ("light".equals(arg)) {
2828 mForceIdle = true;
2829 becomeInactiveIfAppropriateLocked();
2830 int curLightState = mLightState;
2831 while (curLightState != LIGHT_STATE_IDLE) {
Tej Singh93cf3e32017-12-07 13:05:38 -08002832 stepLightIdleStateLocked("s:shell");
Dianne Hackborn88c41352016-04-07 15:18:58 -07002833 if (curLightState == mLightState) {
2834 pw.print("Unable to go light idle; stopped at ");
2835 pw.println(lightStateToString(mLightState));
2836 exitForceIdleLocked();
2837 return -1;
2838 }
2839 curLightState = mLightState;
2840 }
2841 pw.println("Now forced in to light idle mode");
2842 } else {
2843 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002844 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002845 } finally {
2846 Binder.restoreCallingIdentity(token);
2847 }
2848 }
Dianne Hackborn88c41352016-04-07 15:18:58 -07002849 } else if ("force-inactive".equals(cmd)) {
2850 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2851 null);
2852 synchronized (this) {
2853 long token = Binder.clearCallingIdentity();
2854 try {
2855 mForceIdle = true;
2856 becomeInactiveIfAppropriateLocked();
2857 pw.print("Light state: ");
2858 pw.print(lightStateToString(mLightState));
2859 pw.print(", deep state: ");
2860 pw.println(stateToString(mState));
2861 } finally {
2862 Binder.restoreCallingIdentity(token);
2863 }
2864 }
2865 } else if ("unforce".equals(cmd)) {
2866 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2867 null);
2868 synchronized (this) {
2869 long token = Binder.clearCallingIdentity();
2870 try {
2871 exitForceIdleLocked();
2872 pw.print("Light state: ");
2873 pw.print(lightStateToString(mLightState));
2874 pw.print(", deep state: ");
2875 pw.println(stateToString(mState));
2876 } finally {
2877 Binder.restoreCallingIdentity(token);
2878 }
2879 }
2880 } else if ("get".equals(cmd)) {
2881 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2882 null);
2883 synchronized (this) {
2884 String arg = shell.getNextArg();
2885 if (arg != null) {
2886 long token = Binder.clearCallingIdentity();
2887 try {
2888 switch (arg) {
2889 case "light": pw.println(lightStateToString(mLightState)); break;
2890 case "deep": pw.println(stateToString(mState)); break;
2891 case "force": pw.println(mForceIdle); break;
2892 case "screen": pw.println(mScreenOn); break;
2893 case "charging": pw.println(mCharging); break;
2894 case "network": pw.println(mNetworkConnected); break;
2895 default: pw.println("Unknown get option: " + arg); break;
2896 }
2897 } finally {
2898 Binder.restoreCallingIdentity(token);
2899 }
2900 } else {
2901 pw.println("Argument required");
2902 }
2903 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002904 } else if ("disable".equals(cmd)) {
2905 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2906 null);
2907 synchronized (this) {
2908 long token = Binder.clearCallingIdentity();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002909 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002910 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002911 boolean becomeActive = false;
2912 boolean valid = false;
2913 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
2914 valid = true;
2915 if (mDeepEnabled) {
2916 mDeepEnabled = false;
2917 becomeActive = true;
2918 pw.println("Deep idle mode disabled");
2919 }
2920 }
2921 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
2922 valid = true;
2923 if (mLightEnabled) {
2924 mLightEnabled = false;
2925 becomeActive = true;
2926 pw.println("Light idle mode disabled");
2927 }
2928 }
2929 if (becomeActive) {
2930 becomeActiveLocked((arg == null ? "all" : arg) + "-disabled",
2931 Process.myUid());
2932 }
2933 if (!valid) {
2934 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002935 }
2936 } finally {
2937 Binder.restoreCallingIdentity(token);
2938 }
2939 }
2940 } else if ("enable".equals(cmd)) {
2941 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
2942 null);
2943 synchronized (this) {
2944 long token = Binder.clearCallingIdentity();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002945 String arg = shell.getNextArg();
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002946 try {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002947 boolean becomeInactive = false;
2948 boolean valid = false;
2949 if (arg == null || "deep".equals(arg) || "all".equals(arg)) {
2950 valid = true;
2951 if (!mDeepEnabled) {
2952 mDeepEnabled = true;
2953 becomeInactive = true;
2954 pw.println("Deep idle mode enabled");
2955 }
2956 }
2957 if (arg == null || "light".equals(arg) || "all".equals(arg)) {
2958 valid = true;
2959 if (!mLightEnabled) {
2960 mLightEnabled = true;
2961 becomeInactive = true;
2962 pw.println("Light idle mode enable");
2963 }
2964 }
2965 if (becomeInactive) {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002966 becomeInactiveIfAppropriateLocked();
Dianne Hackbornb6843652016-02-22 12:20:13 -08002967 }
2968 if (!valid) {
2969 pw.println("Unknown idle mode: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002970 }
2971 } finally {
2972 Binder.restoreCallingIdentity(token);
2973 }
2974 }
2975 } else if ("enabled".equals(cmd)) {
2976 synchronized (this) {
Dianne Hackbornb6843652016-02-22 12:20:13 -08002977 String arg = shell.getNextArg();
2978 if (arg == null || "all".equals(arg)) {
2979 pw.println(mDeepEnabled && mLightEnabled ? "1" : 0);
2980 } else if ("deep".equals(arg)) {
2981 pw.println(mDeepEnabled ? "1" : 0);
2982 } else if ("light".equals(arg)) {
2983 pw.println(mLightEnabled ? "1" : 0);
2984 } else {
2985 pw.println("Unknown idle mode: " + arg);
2986 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002987 }
2988 } else if ("whitelist".equals(cmd)) {
Dianne Hackborneb909e32016-09-29 14:35:15 -07002989 String arg = shell.getNextArg();
2990 if (arg != null) {
2991 getContext().enforceCallingOrSelfPermission(
2992 android.Manifest.permission.DEVICE_POWER, null);
2993 long token = Binder.clearCallingIdentity();
2994 try {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002995 do {
2996 if (arg.length() < 1 || (arg.charAt(0) != '-'
Felipe Lemef8a46232016-02-10 13:51:54 -08002997 && arg.charAt(0) != '+' && arg.charAt(0) != '=')) {
2998 pw.println("Package must be prefixed with +, -, or =: " + arg);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07002999 return -1;
3000 }
3001 char op = arg.charAt(0);
3002 String pkg = arg.substring(1);
3003 if (op == '+') {
3004 if (addPowerSaveWhitelistAppInternal(pkg)) {
3005 pw.println("Added: " + pkg);
3006 } else {
3007 pw.println("Unknown package: " + pkg);
3008 }
Felipe Lemef8a46232016-02-10 13:51:54 -08003009 } else if (op == '-') {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003010 if (removePowerSaveWhitelistAppInternal(pkg)) {
3011 pw.println("Removed: " + pkg);
3012 }
Felipe Lemef8a46232016-02-10 13:51:54 -08003013 } else {
3014 pw.println(getPowerSaveWhitelistAppInternal(pkg));
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003015 }
3016 } while ((arg=shell.getNextArg()) != null);
Dianne Hackborneb909e32016-09-29 14:35:15 -07003017 } finally {
3018 Binder.restoreCallingIdentity(token);
3019 }
3020 } else {
3021 synchronized (this) {
3022 for (int j=0; j<mPowerSaveWhitelistAppsExceptIdle.size(); j++) {
3023 pw.print("system-excidle,");
3024 pw.print(mPowerSaveWhitelistAppsExceptIdle.keyAt(j));
3025 pw.print(",");
3026 pw.println(mPowerSaveWhitelistAppsExceptIdle.valueAt(j));
3027 }
3028 for (int j=0; j<mPowerSaveWhitelistApps.size(); j++) {
3029 pw.print("system,");
3030 pw.print(mPowerSaveWhitelistApps.keyAt(j));
3031 pw.print(",");
3032 pw.println(mPowerSaveWhitelistApps.valueAt(j));
3033 }
3034 for (int j=0; j<mPowerSaveWhitelistUserApps.size(); j++) {
3035 pw.print("user,");
3036 pw.print(mPowerSaveWhitelistUserApps.keyAt(j));
3037 pw.print(",");
3038 pw.println(mPowerSaveWhitelistUserApps.valueAt(j));
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003039 }
3040 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003041 }
3042 } else if ("tempwhitelist".equals(cmd)) {
Dianne Hackborn85e35642017-01-12 15:10:57 -08003043 long duration = 10000;
Sudheer Shanka326b3112017-11-27 14:40:57 -08003044 boolean removePkg = false;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003045 String opt;
3046 while ((opt=shell.getNextOption()) != null) {
3047 if ("-u".equals(opt)) {
3048 opt = shell.getNextArg();
3049 if (opt == null) {
3050 pw.println("-u requires a user number");
3051 return -1;
3052 }
3053 shell.userId = Integer.parseInt(opt);
Dianne Hackborn85e35642017-01-12 15:10:57 -08003054 } else if ("-d".equals(opt)) {
3055 opt = shell.getNextArg();
3056 if (opt == null) {
3057 pw.println("-d requires a duration");
3058 return -1;
3059 }
3060 duration = Long.parseLong(opt);
Sudheer Shanka326b3112017-11-27 14:40:57 -08003061 } else if ("-r".equals(opt)) {
3062 removePkg = true;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003063 }
3064 }
3065 String arg = shell.getNextArg();
3066 if (arg != null) {
3067 try {
Sudheer Shanka326b3112017-11-27 14:40:57 -08003068 if (removePkg) {
3069 removePowerSaveTempWhitelistAppChecked(arg, shell.userId);
3070 } else {
3071 addPowerSaveTempWhitelistAppChecked(arg, duration, shell.userId, "shell");
3072 }
Christopher Tateec3a9f32017-03-21 17:43:47 -07003073 } catch (Exception e) {
3074 pw.println("Failed: " + e);
3075 return -1;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003076 }
Sudheer Shanka326b3112017-11-27 14:40:57 -08003077 } else if (removePkg) {
3078 pw.println("[-r] requires a package name");
3079 return -1;
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003080 } else {
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003081 dumpTempWhitelistSchedule(pw, false);
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003082 }
Sudheer Shanka3f4d7702017-04-28 17:38:03 -07003083 } else if ("except-idle-whitelist".equals(cmd)) {
3084 getContext().enforceCallingOrSelfPermission(
3085 android.Manifest.permission.DEVICE_POWER, null);
3086 final long token = Binder.clearCallingIdentity();
3087 try {
3088 String arg = shell.getNextArg();
3089 if (arg == null) {
3090 pw.println("No arguments given");
3091 return -1;
3092 } else if ("reset".equals(arg)) {
3093 resetPowerSaveWhitelistExceptIdleInternal();
3094 } else {
3095 do {
3096 if (arg.length() < 1 || (arg.charAt(0) != '-'
3097 && arg.charAt(0) != '+' && arg.charAt(0) != '=')) {
3098 pw.println("Package must be prefixed with +, -, or =: " + arg);
3099 return -1;
3100 }
3101 char op = arg.charAt(0);
3102 String pkg = arg.substring(1);
3103 if (op == '+') {
3104 if (addPowerSaveWhitelistExceptIdleInternal(pkg)) {
3105 pw.println("Added: " + pkg);
3106 } else {
3107 pw.println("Unknown package: " + pkg);
3108 }
3109 } else if (op == '=') {
3110 pw.println(getPowerSaveWhitelistExceptIdleInternal(pkg));
3111 } else {
3112 pw.println("Unknown argument: " + arg);
3113 return -1;
3114 }
3115 } while ((arg = shell.getNextArg()) != null);
3116 }
3117 } finally {
3118 Binder.restoreCallingIdentity(token);
3119 }
Suprabh Shukla08105642017-09-26 14:45:30 -07003120 } else if ("sys-whitelist".equals(cmd)) {
3121 String arg = shell.getNextArg();
3122 if (arg != null) {
3123 getContext().enforceCallingOrSelfPermission(
3124 android.Manifest.permission.DEVICE_POWER, null);
3125 final long token = Binder.clearCallingIdentity();
3126 try {
3127 if ("reset".equals(arg)) {
3128 resetSystemPowerWhitelistInternal();
3129 } else {
3130 do {
3131 if (arg.length() < 1
3132 || (arg.charAt(0) != '-' && arg.charAt(0) != '+')) {
3133 pw.println("Package must be prefixed with + or - " + arg);
3134 return -1;
3135 }
3136 final char op = arg.charAt(0);
3137 final String pkg = arg.substring(1);
3138 switch (op) {
3139 case '+':
3140 if (restoreSystemPowerWhitelistAppInternal(pkg)) {
3141 pw.println("Restored " + pkg);
3142 }
3143 break;
3144 case '-':
3145 if (removeSystemPowerWhitelistAppInternal(pkg)) {
3146 pw.println("Removed " + pkg);
3147 }
3148 break;
3149 }
3150 } while ((arg = shell.getNextArg()) != null);
3151 }
3152 } finally {
3153 Binder.restoreCallingIdentity(token);
3154 }
3155 } else {
3156 synchronized (this) {
3157 for (int j=0; j<mPowerSaveWhitelistApps.size(); j++) {
3158 pw.print(mPowerSaveWhitelistApps.keyAt(j));
3159 pw.print(",");
3160 pw.println(mPowerSaveWhitelistApps.valueAt(j));
3161 }
3162 }
3163 }
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003164 } else {
3165 return shell.handleDefaultCommands(cmd);
3166 }
3167 return 0;
3168 }
3169
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003170 void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003171 if (!DumpUtils.checkDumpPermission(getContext(), TAG, pw)) return;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003172
3173 if (args != null) {
Xiaohui Chen7c696362015-09-16 09:56:14 -07003174 int userId = UserHandle.USER_SYSTEM;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003175 for (int i=0; i<args.length; i++) {
3176 String arg = args[i];
3177 if ("-h".equals(arg)) {
3178 dumpHelp(pw);
3179 return;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003180 } else if ("-u".equals(arg)) {
3181 i++;
3182 if (i < args.length) {
3183 arg = args[i];
3184 userId = Integer.parseInt(arg);
3185 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003186 } else if ("-a".equals(arg)) {
3187 // Ignore, we always dump all.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003188 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
3189 pw.println("Unknown option: " + arg);
3190 return;
3191 } else {
Dianne Hackborn9461b6f2015-10-07 17:33:16 -07003192 Shell shell = new Shell();
3193 shell.userId = userId;
3194 String[] newArgs = new String[args.length-i];
3195 System.arraycopy(args, i, newArgs, 0, args.length-i);
Dianne Hackborn354736e2016-08-22 17:00:05 -07003196 shell.exec(mBinderService, null, fd, null, newArgs, null,
3197 new ResultReceiver(null));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003198 return;
3199 }
3200 }
3201 }
3202
3203 synchronized (this) {
Dianne Hackborna750a632015-06-16 17:18:23 -07003204 mConstants.dump(pw);
3205
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08003206 if (mEventCmds[0] != EVENT_NULL) {
3207 pw.println(" Idling history:");
3208 long now = SystemClock.elapsedRealtime();
3209 for (int i=EVENT_BUFFER_SIZE-1; i>=0; i--) {
3210 int cmd = mEventCmds[i];
3211 if (cmd == EVENT_NULL) {
3212 continue;
3213 }
3214 String label;
3215 switch (mEventCmds[i]) {
3216 case EVENT_NORMAL: label = " normal"; break;
3217 case EVENT_LIGHT_IDLE: label = " light-idle"; break;
3218 case EVENT_LIGHT_MAINTENANCE: label = "light-maint"; break;
Dianne Hackbornb6843652016-02-22 12:20:13 -08003219 case EVENT_DEEP_IDLE: label = " deep-idle"; break;
3220 case EVENT_DEEP_MAINTENANCE: label = " deep-maint"; break;
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08003221 default: label = " ??"; break;
3222 }
3223 pw.print(" ");
3224 pw.print(label);
3225 pw.print(": ");
3226 TimeUtils.formatDuration(mEventTimes[i], now, pw);;
3227 pw.println();
3228 }
3229 }
3230
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003231 int size = mPowerSaveWhitelistAppsExceptIdle.size();
3232 if (size > 0) {
3233 pw.println(" Whitelist (except idle) system apps:");
3234 for (int i = 0; i < size; i++) {
3235 pw.print(" ");
3236 pw.println(mPowerSaveWhitelistAppsExceptIdle.keyAt(i));
3237 }
3238 }
3239 size = mPowerSaveWhitelistApps.size();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003240 if (size > 0) {
3241 pw.println(" Whitelist system apps:");
3242 for (int i = 0; i < size; i++) {
3243 pw.print(" ");
3244 pw.println(mPowerSaveWhitelistApps.keyAt(i));
3245 }
3246 }
Suprabh Shukla08105642017-09-26 14:45:30 -07003247 size = mRemovedFromSystemWhitelistApps.size();
3248 if (size > 0) {
3249 pw.println(" Removed from whitelist system apps:");
3250 for (int i = 0; i < size; i++) {
3251 pw.print(" ");
3252 pw.println(mRemovedFromSystemWhitelistApps.keyAt(i));
3253 }
3254 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003255 size = mPowerSaveWhitelistUserApps.size();
3256 if (size > 0) {
3257 pw.println(" Whitelist user apps:");
3258 for (int i = 0; i < size; i++) {
3259 pw.print(" ");
3260 pw.println(mPowerSaveWhitelistUserApps.keyAt(i));
3261 }
3262 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003263 size = mPowerSaveWhitelistExceptIdleAppIds.size();
3264 if (size > 0) {
3265 pw.println(" Whitelist (except idle) all app ids:");
3266 for (int i = 0; i < size; i++) {
3267 pw.print(" ");
3268 pw.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
3269 pw.println();
3270 }
3271 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08003272 size = mPowerSaveWhitelistUserAppIds.size();
3273 if (size > 0) {
3274 pw.println(" Whitelist user app ids:");
3275 for (int i = 0; i < size; i++) {
3276 pw.print(" ");
3277 pw.print(mPowerSaveWhitelistUserAppIds.keyAt(i));
3278 pw.println();
3279 }
3280 }
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07003281 size = mPowerSaveWhitelistAllAppIds.size();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003282 if (size > 0) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07003283 pw.println(" Whitelist all app ids:");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003284 for (int i = 0; i < size; i++) {
Dianne Hackborna750a632015-06-16 17:18:23 -07003285 pw.print(" ");
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07003286 pw.print(mPowerSaveWhitelistAllAppIds.keyAt(i));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003287 pw.println();
3288 }
3289 }
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003290 dumpTempWhitelistSchedule(pw, true);
3291
Dianne Hackborna750a632015-06-16 17:18:23 -07003292 size = mTempWhitelistAppIdArray != null ? mTempWhitelistAppIdArray.length : 0;
3293 if (size > 0) {
3294 pw.println(" Temp whitelist app ids:");
3295 for (int i = 0; i < size; i++) {
3296 pw.print(" ");
3297 pw.print(mTempWhitelistAppIdArray[i]);
3298 pw.println();
3299 }
3300 }
Adam Lesinski31c05d12015-06-09 17:34:04 -07003301
Dianne Hackbornb6843652016-02-22 12:20:13 -08003302 pw.print(" mLightEnabled="); pw.print(mLightEnabled);
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003303 pw.print(" mDeepEnabled="); pw.println(mDeepEnabled);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003304 pw.print(" mForceIdle="); pw.println(mForceIdle);
Nick Vaccaro20feaea2015-09-17 17:22:44 -07003305 pw.print(" mMotionSensor="); pw.println(mMotionSensor);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003306 pw.print(" mScreenOn="); pw.println(mScreenOn);
Dianne Hackborn88c41352016-04-07 15:18:58 -07003307 pw.print(" mNetworkConnected="); pw.println(mNetworkConnected);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003308 pw.print(" mCharging="); pw.println(mCharging);
Nick Vaccaro20feaea2015-09-17 17:22:44 -07003309 pw.print(" mMotionActive="); pw.println(mMotionListener.active);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003310 pw.print(" mNotMoving="); pw.println(mNotMoving);
Joe LaPenna23d681b2015-08-27 15:12:11 -07003311 pw.print(" mLocating="); pw.print(mLocating); pw.print(" mHasGps=");
3312 pw.print(mHasGps); pw.print(" mHasNetwork=");
3313 pw.print(mHasNetworkLocation); pw.print(" mLocated="); pw.println(mLocated);
Dianne Hackborn42df4fb2015-08-14 16:43:14 -07003314 if (mLastGenericLocation != null) {
3315 pw.print(" mLastGenericLocation="); pw.println(mLastGenericLocation);
3316 }
3317 if (mLastGpsLocation != null) {
3318 pw.print(" mLastGpsLocation="); pw.println(mLastGpsLocation);
3319 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003320 pw.print(" mState="); pw.print(stateToString(mState));
3321 pw.print(" mLightState=");
3322 pw.println(lightStateToString(mLightState));
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003323 pw.print(" mInactiveTimeout="); TimeUtils.formatDuration(mInactiveTimeout, pw);
3324 pw.println();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003325 if (mActiveIdleOpCount != 0) {
3326 pw.print(" mActiveIdleOpCount="); pw.println(mActiveIdleOpCount);
3327 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003328 if (mNextAlarmTime != 0) {
3329 pw.print(" mNextAlarmTime=");
3330 TimeUtils.formatDuration(mNextAlarmTime, SystemClock.elapsedRealtime(), pw);
3331 pw.println();
3332 }
3333 if (mNextIdlePendingDelay != 0) {
3334 pw.print(" mNextIdlePendingDelay=");
3335 TimeUtils.formatDuration(mNextIdlePendingDelay, pw);
3336 pw.println();
3337 }
3338 if (mNextIdleDelay != 0) {
3339 pw.print(" mNextIdleDelay=");
3340 TimeUtils.formatDuration(mNextIdleDelay, pw);
3341 pw.println();
3342 }
Dianne Hackborn953fc942016-03-29 15:36:24 -07003343 if (mNextLightIdleDelay != 0) {
3344 pw.print(" mNextIdleDelay=");
3345 TimeUtils.formatDuration(mNextLightIdleDelay, pw);
3346 pw.println();
3347 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003348 if (mNextLightAlarmTime != 0) {
3349 pw.print(" mNextLightAlarmTime=");
3350 TimeUtils.formatDuration(mNextLightAlarmTime, SystemClock.elapsedRealtime(), pw);
3351 pw.println();
3352 }
Dianne Hackborn8ed2b972015-11-18 14:52:04 -08003353 if (mCurIdleBudget != 0) {
3354 pw.print(" mCurIdleBudget=");
3355 TimeUtils.formatDuration(mCurIdleBudget, pw);
3356 pw.println();
3357 }
3358 if (mMaintenanceStartTime != 0) {
3359 pw.print(" mMaintenanceStartTime=");
3360 TimeUtils.formatDuration(mMaintenanceStartTime, SystemClock.elapsedRealtime(), pw);
3361 pw.println();
3362 }
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003363 if (mJobsActive) {
3364 pw.print(" mJobsActive="); pw.println(mJobsActive);
3365 }
3366 if (mAlarmsActive) {
3367 pw.print(" mAlarmsActive="); pw.println(mAlarmsActive);
3368 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07003369 }
3370 }
Felipe Lemea1b79bf2016-05-24 13:06:54 -07003371
3372 void dumpTempWhitelistSchedule(PrintWriter pw, boolean printTitle) {
3373 final int size = mTempWhitelistAppIdEndTimes.size();
3374 if (size > 0) {
3375 String prefix = "";
3376 if (printTitle) {
3377 pw.println(" Temp whitelist schedule:");
3378 prefix = " ";
3379 }
3380 final long timeNow = SystemClock.elapsedRealtime();
3381 for (int i = 0; i < size; i++) {
3382 pw.print(prefix);
3383 pw.print("UID=");
3384 pw.print(mTempWhitelistAppIdEndTimes.keyAt(i));
3385 pw.print(": ");
3386 Pair<MutableLong, String> entry = mTempWhitelistAppIdEndTimes.valueAt(i);
3387 TimeUtils.formatDuration(entry.first.value, timeNow, pw);
3388 pw.print(" - ");
3389 pw.println(entry.second);
3390 }
3391 }
3392 }
3393 }