blob: 4c7b52362a01899d5bf331eed9438e35059945c8 [file] [log] [blame]
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Amith Yamasaniaf575b92015-05-29 15:35:26 -070019import android.Manifest;
20import android.app.ActivityManagerNative;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070021import android.app.AlarmManager;
Amith Yamasaniaf575b92015-05-29 15:35:26 -070022import android.app.AppGlobals;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070023import android.app.PendingIntent;
24import android.content.BroadcastReceiver;
25import android.content.Context;
26import android.content.Intent;
27import android.content.IntentFilter;
28import android.content.pm.ApplicationInfo;
Amith Yamasaniaf575b92015-05-29 15:35:26 -070029import android.content.pm.PackageInfo;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070030import android.content.pm.PackageManager;
Amith Yamasaniaf575b92015-05-29 15:35:26 -070031import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070032import android.hardware.Sensor;
33import android.hardware.SensorManager;
34import android.hardware.TriggerEvent;
35import android.hardware.TriggerEventListener;
36import android.hardware.display.DisplayManager;
37import android.net.INetworkPolicyManager;
38import android.os.Binder;
39import android.os.Environment;
40import android.os.FileUtils;
41import android.os.Handler;
42import android.os.IDeviceIdleController;
43import android.os.Looper;
44import android.os.Message;
45import android.os.PowerManager;
46import android.os.PowerManagerInternal;
47import android.os.RemoteException;
48import android.os.ServiceManager;
49import android.os.SystemClock;
50import android.os.UserHandle;
51import android.util.ArrayMap;
52import android.util.ArraySet;
Amith Yamasani520d8f22015-05-08 16:36:21 -070053import android.util.Log;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070054import android.util.Slog;
Amith Yamasaniaf575b92015-05-29 15:35:26 -070055import android.util.SparseArray;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070056import android.util.SparseBooleanArray;
Amith Yamasaniaf575b92015-05-29 15:35:26 -070057import android.util.SparseLongArray;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070058import android.util.TimeUtils;
59import android.util.Xml;
60import android.view.Display;
Amith Yamasani520d8f22015-05-08 16:36:21 -070061
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070062import com.android.internal.app.IBatteryStats;
63import com.android.internal.os.AtomicFile;
64import com.android.internal.os.BackgroundThread;
Amith Yamasaniaf575b92015-05-29 15:35:26 -070065import com.android.internal.util.ArrayUtils;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070066import com.android.internal.util.FastXmlSerializer;
67import com.android.internal.util.XmlUtils;
68import com.android.server.am.BatteryStatsService;
Amith Yamasani520d8f22015-05-08 16:36:21 -070069
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070070import org.xmlpull.v1.XmlPullParser;
71import org.xmlpull.v1.XmlPullParserException;
72import org.xmlpull.v1.XmlSerializer;
73
74import java.io.ByteArrayOutputStream;
75import java.io.File;
76import java.io.FileDescriptor;
77import java.io.FileInputStream;
78import java.io.FileNotFoundException;
79import java.io.FileOutputStream;
80import java.io.IOException;
81import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010082import java.nio.charset.StandardCharsets;
Amith Yamasaniaf575b92015-05-29 15:35:26 -070083import java.util.Arrays;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070084
85/**
86 * Keeps track of device idleness and drives low power mode based on that.
87 */
Kevin Gabayan89ecf822015-05-18 12:10:07 -070088public class DeviceIdleController extends SystemService
89 implements AnyMotionDetector.DeviceIdleCallback {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070090 private static final String TAG = "DeviceIdleController";
91
Amith Yamasaniaf575b92015-05-29 15:35:26 -070092 private static final boolean DEBUG = false;
Kevin Gabayan89ecf822015-05-18 12:10:07 -070093
Amith Yamasaniaf575b92015-05-29 15:35:26 -070094 private static final boolean COMPRESS_TIME = false;
Amith Yamasani520d8f22015-05-08 16:36:21 -070095
Dianne Hackborn0b4daca2015-04-27 09:47:32 -070096 public static final String SERVICE_NAME = "deviceidle";
97
98 private static final String ACTION_STEP_IDLE_STATE =
99 "com.android.server.device_idle.STEP_IDLE_STATE";
100
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700101 private static final String ACTION_ENTER_INACTIVE_STATE =
102 "com.android.server.device_idle.ENTER_INACTIVE_STATE";
103
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700104 // TODO: These need to be moved to system settings.
105
106 /**
107 * This is the time, after becoming inactive, at which we start looking at the
108 * motion sensor to determine if the device is being left alone. We don't do this
109 * immediately after going inactive just because we don't want to be continually running
110 * the significant motion sensor whenever the screen is off.
111 */
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700112
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700113 private static final long DEFAULT_INACTIVE_TIMEOUT = !COMPRESS_TIME ? 30*60*1000L
114 : 3 * 60 * 1000L;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700115
116 /**
117 * If we don't receive a callback from AnyMotion in this amount of time, we will change from
118 * STATE_SENSING to STATE_INACTIVE, and any AnyMotion callbacks while not in STATE_SENSING will
119 * be ignored.
120 */
121 private static final long DEFAULT_SENSING_TIMEOUT = !DEBUG ? 5 * 60 * 1000L : 60 * 1000L;
122
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700123 /**
124 * This is the time, after seeing motion, that we wait after becoming inactive from
125 * that until we start looking for motion again.
126 */
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700127 private static final long DEFAULT_MOTION_INACTIVE_TIMEOUT = !COMPRESS_TIME ? 10*60*1000L
Amith Yamasani520d8f22015-05-08 16:36:21 -0700128 : 60 * 1000L;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700129
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700130 /**
131 * This is the time, after the inactive timeout elapses, that we will wait looking
132 * for significant motion until we truly consider the device to be idle.
133 */
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700134
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700135 private static final long DEFAULT_IDLE_AFTER_INACTIVE_TIMEOUT = !COMPRESS_TIME ? 30*60*1000L
136 : 3 * 60 * 1000L;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700137
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700138 /**
139 * This is the initial time, after being idle, that we will allow ourself to be back
140 * in the IDLE_PENDING state allowing the system to run normally until we return to idle.
141 */
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700142
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700143 private static final long DEFAULT_IDLE_PENDING_TIMEOUT = !COMPRESS_TIME ? 5*60*1000L
144 : 30 * 1000L;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700145
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700146 /**
147 * Maximum pending idle timeout (time spent running) we will be allowed to use.
148 */
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700149 private static final long DEFAULT_MAX_IDLE_PENDING_TIMEOUT = !COMPRESS_TIME ? 10*60*1000L
150 : 60 * 1000L;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700151 /**
152 * Scaling factor to apply to current pending idle timeout each time we cycle through
153 * that state.
154 */
155 private static final float DEFAULT_IDLE_PENDING_FACTOR = 2f;
156 /**
157 * This is the initial time that we want to sit in the idle state before waking up
158 * again to return to pending idle and allowing normal work to run.
159 */
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700160
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700161 private static final long DEFAULT_IDLE_TIMEOUT = !COMPRESS_TIME ? 60*60*1000L
162 : 6 * 60 * 1000L;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700163
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700164 /**
165 * Maximum idle duration we will be allowed to use.
166 */
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700167 private static final long DEFAULT_MAX_IDLE_TIMEOUT = !COMPRESS_TIME ? 6*60*60*1000L
168 : 30 * 60 * 1000L;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700169 /**
170 * Scaling factor to apply to current idle timeout each time we cycle through that state.
171 */
172 private static final float DEFAULT_IDLE_FACTOR = 2f;
173 /**
174 * This is the minimum time we will allow until the next upcoming alarm for us to
175 * actually go in to idle mode.
176 */
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700177 private static final long DEFAULT_MIN_TIME_TO_ALARM = !COMPRESS_TIME ? 60*60*1000L
178 : 6 * 60 * 1000L;
179
180 /**
181 * Max amount of time to temporarily whitelist an app when it receives a high priority tickle.
182 */
183 private static final long MAX_TEMP_APP_WHITELIST_DURATION = 5 * 60 * 1000L;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700184
185 private AlarmManager mAlarmManager;
186 private IBatteryStats mBatteryStats;
187 private PowerManagerInternal mLocalPowerManager;
188 private INetworkPolicyManager mNetworkPolicyManager;
189 private DisplayManager mDisplayManager;
190 private SensorManager mSensorManager;
191 private Sensor mSigMotionSensor;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700192 private PendingIntent mSensingAlarmIntent;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700193 private PendingIntent mAlarmIntent;
194 private Intent mIdleIntent;
195 private Display mCurDisplay;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700196 private AnyMotionDetector mAnyMotionDetector;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700197 private boolean mIdleDisabled;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700198 private boolean mScreenOn;
199 private boolean mCharging;
200 private boolean mSigMotionActive;
201
202 /** Device is currently active. */
203 private static final int STATE_ACTIVE = 0;
204 /** Device is inactve (screen off, no motion) and we are waiting to for idle. */
205 private static final int STATE_INACTIVE = 1;
206 /** Device is past the initial inactive period, and waiting for the next idle period. */
207 private static final int STATE_IDLE_PENDING = 2;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700208 /** Device is currently sensing motion. */
209 private static final int STATE_SENSING = 3;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700210 /** Device is in the idle state, trying to stay asleep as much as possible. */
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700211 private static final int STATE_IDLE = 4;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700212 /** Device is in the idle state, but temporarily out of idle to do regular maintenance. */
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700213 private static final int STATE_IDLE_MAINTENANCE = 5;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700214 private static String stateToString(int state) {
215 switch (state) {
216 case STATE_ACTIVE: return "ACTIVE";
217 case STATE_INACTIVE: return "INACTIVE";
218 case STATE_IDLE_PENDING: return "IDLE_PENDING";
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700219 case STATE_SENSING: return "SENSING";
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700220 case STATE_IDLE: return "IDLE";
221 case STATE_IDLE_MAINTENANCE: return "IDLE_MAINTENANCE";
222 default: return Integer.toString(state);
223 }
224 }
225
226 private int mState;
227
228 private long mInactiveTimeout;
229 private long mNextAlarmTime;
230 private long mNextIdlePendingDelay;
231 private long mNextIdleDelay;
232
233 public final AtomicFile mConfigFile;
234
235 /**
236 * Package names the system has white-listed to opt out of power save restrictions.
237 */
238 private final ArrayMap<String, Integer> mPowerSaveWhitelistApps = new ArrayMap<>();
239
240 /**
241 * Package names the user has white-listed to opt out of power save restrictions.
242 */
243 private final ArrayMap<String, Integer> mPowerSaveWhitelistUserApps = new ArrayMap<>();
244
245 /**
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700246 * App IDs that have been white-listed to opt out of power save restrictions.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700247 */
248 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
249
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700250 /**
251 * Current app IDs that are in the complete power save white list. This array can
252 * be shared with others because it will not be modified once set.
253 */
254 private int[] mPowerSaveWhitelistAppIdArray = new int[0];
255
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700256 /**
257 * List of end times for UIDs that are temporarily marked as being allowed to access
258 * the network and acquire wakelocks. Times are in milliseconds.
259 */
260 private SparseLongArray mTempWhitelistAppIdEndTimes = new SparseLongArray();
261
262 /**
263 * Current app IDs of temporarily whitelist apps for high-priority messages.
264 */
265 private int[] mTempWhitelistAppIdArray = new int[0];
266
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700267 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
268 @Override public void onReceive(Context context, Intent intent) {
269 if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
270 int plugged = intent.getIntExtra("plugged", 0);
271 updateChargingLocked(plugged != 0);
272 } else if (ACTION_STEP_IDLE_STATE.equals(intent.getAction())) {
273 synchronized (DeviceIdleController.this) {
274 stepIdleStateLocked();
275 }
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700276 } else if (ACTION_ENTER_INACTIVE_STATE.equals(intent.getAction())) {
277 synchronized (DeviceIdleController.this) {
278 enterInactiveStateLocked();
279 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700280 }
281 }
282 };
283
284 private final DisplayManager.DisplayListener mDisplayListener
285 = new DisplayManager.DisplayListener() {
286 @Override public void onDisplayAdded(int displayId) {
287 }
288
289 @Override public void onDisplayRemoved(int displayId) {
290 }
291
292 @Override public void onDisplayChanged(int displayId) {
293 if (displayId == Display.DEFAULT_DISPLAY) {
294 synchronized (DeviceIdleController.this) {
295 updateDisplayLocked();
296 }
297 }
298 }
299 };
300
301 private final TriggerEventListener mSigMotionListener = new TriggerEventListener() {
302 @Override public void onTrigger(TriggerEvent event) {
303 synchronized (DeviceIdleController.this) {
304 significantMotionLocked();
305 }
306 }
307 };
308
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700309 @Override
310 public void onAnyMotionResult(int result) {
311 if (DEBUG) Slog.d(TAG, "onAnyMotionResult(" + result + ")");
312 if (mState == STATE_SENSING) {
313 if (result == AnyMotionDetector.RESULT_STATIONARY) {
314 if (DEBUG) Slog.d(TAG, "RESULT_STATIONARY received.");
315 synchronized (this) {
316 stepIdleStateLocked();
317 }
318 } else if (result == AnyMotionDetector.RESULT_MOVED) {
319 if (DEBUG) Slog.d(TAG, "RESULT_MOVED received.");
320 synchronized (this) {
321 enterInactiveStateLocked();
322 }
323 }
324 }
325 }
326
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700327 static final int MSG_WRITE_CONFIG = 1;
328 static final int MSG_REPORT_IDLE_ON = 2;
329 static final int MSG_REPORT_IDLE_OFF = 3;
330 static final int MSG_REPORT_ACTIVE = 4;
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700331 static final int MSG_TEMP_APP_WHITELIST_TIMEOUT = 5;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700332
333 final class MyHandler extends Handler {
334 MyHandler(Looper looper) {
335 super(looper);
336 }
337
338 @Override public void handleMessage(Message msg) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700339 if (DEBUG) Slog.d(TAG, "handleMessage(" + msg.what + ")");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700340 switch (msg.what) {
341 case MSG_WRITE_CONFIG: {
342 handleWriteConfigFile();
343 } break;
344 case MSG_REPORT_IDLE_ON: {
345 mLocalPowerManager.setDeviceIdleMode(true);
346 try {
347 mNetworkPolicyManager.setDeviceIdleMode(true);
348 mBatteryStats.noteDeviceIdleMode(true, false, false);
349 } catch (RemoteException e) {
350 }
351 getContext().sendBroadcastAsUser(mIdleIntent, UserHandle.ALL);
352 } break;
353 case MSG_REPORT_IDLE_OFF: {
354 mLocalPowerManager.setDeviceIdleMode(false);
355 try {
356 mNetworkPolicyManager.setDeviceIdleMode(false);
357 mBatteryStats.noteDeviceIdleMode(false, false, false);
358 } catch (RemoteException e) {
359 }
360 getContext().sendBroadcastAsUser(mIdleIntent, UserHandle.ALL);
361 } break;
362 case MSG_REPORT_ACTIVE: {
363 boolean fromMotion = msg.arg1 != 0;
364 boolean needBroadcast = msg.arg2 != 0;
365 mLocalPowerManager.setDeviceIdleMode(false);
366 try {
367 mNetworkPolicyManager.setDeviceIdleMode(false);
368 mBatteryStats.noteDeviceIdleMode(false, !fromMotion, fromMotion);
369 } catch (RemoteException e) {
370 }
371 if (needBroadcast) {
372 getContext().sendBroadcastAsUser(mIdleIntent, UserHandle.ALL);
373 }
374 } break;
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700375 case MSG_TEMP_APP_WHITELIST_TIMEOUT: {
376 int uid = msg.arg1;
377 checkTempAppWhitelistTimeout(uid);
378 } break;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700379 }
380 }
381 }
382
383 final MyHandler mHandler;
384
385 private final class BinderService extends IDeviceIdleController.Stub {
386 @Override public void addPowerSaveWhitelistApp(String name) {
387 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
388 null);
389 addPowerSaveWhitelistAppInternal(name);
390 }
391
392 @Override public void removePowerSaveWhitelistApp(String name) {
393 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
394 null);
395 removePowerSaveWhitelistAppInternal(name);
396 }
397
398 @Override public String[] getSystemPowerWhitelist() {
399 return getSystemPowerWhitelistInternal();
400 }
401
402 @Override public String[] getFullPowerWhitelist() {
403 return getFullPowerWhitelistInternal();
404 }
405
406 @Override public int[] getAppIdWhitelist() {
407 return getAppIdWhitelistInternal();
408 }
409
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700410 @Override public int[] getAppIdTempWhitelist() {
411 return getAppIdTempWhitelistInternal();
412 }
413
Amith Yamasani06bf8242015-05-08 16:36:21 -0700414 @Override public boolean isPowerSaveWhitelistApp(String name) {
415 return isPowerSaveWhitelistAppInternal(name);
416 }
417
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700418 @Override public void addPowerSaveTempWhitelistApp(String packageName, long duration,
419 int userId) throws RemoteException {
420 getContext().enforceCallingPermission(
421 Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
422 "No permission to change device idle whitelist");
423 userId = ActivityManagerNative.getDefault().handleIncomingUser(
424 Binder.getCallingPid(),
425 Binder.getCallingUid(),
426 userId,
427 /*allowAll=*/ false,
428 /*requireFull=*/ false,
429 "addAppBrieflyToWhitelist", null);
430 final long token = Binder.clearCallingIdentity();
431 try {
432 PackageInfo pi = AppGlobals.getPackageManager()
433 .getPackageInfo(packageName, 0, userId);
434 if (pi == null) return;
435 DeviceIdleController.this.addPowerSaveTempWhitelistAppInternal(packageName,
436 duration, userId);
437 } catch (RemoteException re) {
438 } finally {
439 Binder.restoreCallingIdentity(token);
440 }
441 }
442
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700443 @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
444 DeviceIdleController.this.dump(fd, pw, args);
445 }
446 }
447
448 public DeviceIdleController(Context context) {
449 super(context);
450 mConfigFile = new AtomicFile(new File(getSystemDir(), "deviceidle.xml"));
451 mHandler = new MyHandler(BackgroundThread.getHandler().getLooper());
452 }
453
454 private static File getSystemDir() {
455 return new File(Environment.getDataDirectory(), "system");
456 }
457
458 @Override
459 public void onStart() {
460 final PackageManager pm = getContext().getPackageManager();
461
462 synchronized (this) {
463 SystemConfig sysConfig = SystemConfig.getInstance();
464 ArraySet<String> allowPower = sysConfig.getAllowInPowerSave();
465 for (int i=0; i<allowPower.size(); i++) {
466 String pkg = allowPower.valueAt(i);
467 try {
468 ApplicationInfo ai = pm.getApplicationInfo(pkg, 0);
469 if ((ai.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
470 mPowerSaveWhitelistApps.put(ai.packageName,
471 UserHandle.getAppId(ai.uid));
472 }
473 } catch (PackageManager.NameNotFoundException e) {
474 }
475 }
476
477 readConfigFileLocked();
478 updateWhitelistAppIdsLocked();
479
480 mScreenOn = true;
481 // Start out assuming we are charging. If we aren't, we will at least get
482 // a battery update the next time the level drops.
483 mCharging = true;
484 mState = STATE_ACTIVE;
485 mInactiveTimeout = DEFAULT_INACTIVE_TIMEOUT;
486 }
487
488 publishBinderService(SERVICE_NAME, new BinderService());
489 }
490
491 @Override
492 public void onBootPhase(int phase) {
493 if (phase == PHASE_SYSTEM_SERVICES_READY) {
494 synchronized (this) {
495 mAlarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
496 mBatteryStats = BatteryStatsService.getService();
497 mLocalPowerManager = getLocalService(PowerManagerInternal.class);
498 mNetworkPolicyManager = INetworkPolicyManager.Stub.asInterface(
499 ServiceManager.getService(Context.NETWORK_POLICY_SERVICE));
500 mDisplayManager = (DisplayManager) getContext().getSystemService(
501 Context.DISPLAY_SERVICE);
502 mSensorManager = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
503 mSigMotionSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_SIGNIFICANT_MOTION);
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700504 mAnyMotionDetector = new AnyMotionDetector(
505 mAlarmManager,
506 (PowerManager) getContext().getSystemService(Context.POWER_SERVICE),
507 mHandler, mSensorManager, this);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700508
509 Intent intent = new Intent(ACTION_STEP_IDLE_STATE)
510 .setPackage("android")
511 .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
512 mAlarmIntent = PendingIntent.getBroadcast(getContext(), 0, intent, 0);
513
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700514 Intent intentSensing = new Intent(ACTION_STEP_IDLE_STATE)
515 .setPackage("android")
516 .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
517 mSensingAlarmIntent = PendingIntent.getBroadcast(getContext(), 0, intentSensing, 0);
518
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700519 mIdleIntent = new Intent(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
520 mIdleIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
521
522 IntentFilter filter = new IntentFilter();
523 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
524 filter.addAction(ACTION_STEP_IDLE_STATE);
525 getContext().registerReceiver(mReceiver, filter);
526
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700527 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAppIdArray);
528
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700529 mDisplayManager.registerDisplayListener(mDisplayListener, null);
530 updateDisplayLocked();
531 }
532 }
533 }
534
535 public boolean addPowerSaveWhitelistAppInternal(String name) {
536 synchronized (this) {
537 try {
538 ApplicationInfo ai = getContext().getPackageManager().getApplicationInfo(name, 0);
539 if (mPowerSaveWhitelistUserApps.put(name, UserHandle.getAppId(ai.uid)) == null) {
540 reportPowerSaveWhitelistChangedLocked();
541 updateWhitelistAppIdsLocked();
542 writeConfigFileLocked();
543 }
544 return true;
545 } catch (PackageManager.NameNotFoundException e) {
546 return false;
547 }
548 }
549 }
550
551 public boolean removePowerSaveWhitelistAppInternal(String name) {
552 synchronized (this) {
553 if (mPowerSaveWhitelistUserApps.remove(name) != null) {
554 reportPowerSaveWhitelistChangedLocked();
555 updateWhitelistAppIdsLocked();
556 writeConfigFileLocked();
557 return true;
558 }
559 }
560 return false;
561 }
562
563 public String[] getSystemPowerWhitelistInternal() {
564 synchronized (this) {
565 int size = mPowerSaveWhitelistApps.size();
566 String[] apps = new String[size];
567 for (int i = 0; i < mPowerSaveWhitelistApps.size(); i++) {
568 apps[i] = mPowerSaveWhitelistApps.keyAt(i);
569 }
570 return apps;
571 }
572 }
573
574 public String[] getFullPowerWhitelistInternal() {
575 synchronized (this) {
576 int size = mPowerSaveWhitelistApps.size() + mPowerSaveWhitelistUserApps.size();
577 String[] apps = new String[size];
578 int cur = 0;
579 for (int i = 0; i < mPowerSaveWhitelistApps.size(); i++) {
580 apps[cur] = mPowerSaveWhitelistApps.keyAt(i);
581 cur++;
582 }
583 for (int i = 0; i < mPowerSaveWhitelistUserApps.size(); i++) {
584 apps[cur] = mPowerSaveWhitelistUserApps.keyAt(i);
585 cur++;
586 }
587 return apps;
588 }
589 }
590
Amith Yamasani06bf8242015-05-08 16:36:21 -0700591 public boolean isPowerSaveWhitelistAppInternal(String packageName) {
592 synchronized (this) {
593 return mPowerSaveWhitelistApps.containsKey(packageName)
594 || mPowerSaveWhitelistUserApps.containsKey(packageName);
595 }
596 }
597
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700598 public int[] getAppIdWhitelistInternal() {
599 synchronized (this) {
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700600 return mPowerSaveWhitelistAppIdArray;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700601 }
602 }
603
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700604 public int[] getAppIdTempWhitelistInternal() {
605 synchronized (this) {
606 return mTempWhitelistAppIdArray;
607 }
608 }
609
610 /**
611 * Adds an app to the temporary whitelist and resets the endTime for granting the
612 * app an exemption to access network and acquire wakelocks.
613 */
614 public void addPowerSaveTempWhitelistAppInternal(String packageName, long duration,
615 int userId) {
616 if (duration > MAX_TEMP_APP_WHITELIST_DURATION) {
617 duration = MAX_TEMP_APP_WHITELIST_DURATION;
618 }
619 try {
620 int uid = getContext().getPackageManager().getPackageUid(packageName, userId);
621 int appId = UserHandle.getAppId(uid);
622 final long timeNow = System.currentTimeMillis();
623 synchronized (this) {
624 long currentEndTime = mTempWhitelistAppIdEndTimes.get(appId);
625 // Set the new end time
626 mTempWhitelistAppIdEndTimes.put(appId, timeNow + duration);
627 if (DEBUG) {
628 Slog.d(TAG, "Adding AppId " + appId + " to temp whitelist");
629 }
630 if (currentEndTime == 0) {
631 // No pending timeout for the app id, post a delayed message
632 postTempActiveTimeoutMessage(appId, duration);
633 updateTempWhitelistAppIdsLocked();
634 reportTempWhitelistChangedLocked();
635 }
636 }
637 } catch (NameNotFoundException e) {
638 }
639 }
640
641 private void postTempActiveTimeoutMessage(int uid, long delay) {
642 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_TEMP_APP_WHITELIST_TIMEOUT, uid, 0),
643 delay);
644 }
645
646 void checkTempAppWhitelistTimeout(int uid) {
647 final long timeNow = System.currentTimeMillis();
648 synchronized (this) {
649 long endTime = mTempWhitelistAppIdEndTimes.get(uid);
650 if (endTime == 0) {
651 // Nothing to do
652 return;
653 }
654 if (timeNow >= endTime) {
655 mTempWhitelistAppIdEndTimes.delete(uid);
656 if (DEBUG) {
657 Slog.d(TAG, "Removing UID " + uid + " from temp whitelist");
658 }
659 updateTempWhitelistAppIdsLocked();
660 reportTempWhitelistChangedLocked();
661 } else {
662 // Need more time
663 postTempActiveTimeoutMessage(uid, endTime - timeNow);
664 }
665 }
666 }
667
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700668 void updateDisplayLocked() {
669 mCurDisplay = mDisplayManager.getDisplay(Display.DEFAULT_DISPLAY);
670 // We consider any situation where the display is showing something to be it on,
671 // because if there is anything shown we are going to be updating it at some
672 // frequency so can't be allowed to go into deep sleeps.
673 boolean screenOn = mCurDisplay.getState() != Display.STATE_OFF;;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700674 if (DEBUG) Slog.d(TAG, "updateDisplayLocked: screenOn=" + screenOn);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700675 if (!screenOn && mScreenOn) {
676 mScreenOn = false;
677 becomeInactiveIfAppropriateLocked();
678 } else if (screenOn) {
679 mScreenOn = true;
680 becomeActiveLocked("screen");
681 }
682 }
683
684 void updateChargingLocked(boolean charging) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700685 if (DEBUG) Slog.i(TAG, "updateChargingLocked: charging=" + charging);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700686 if (!charging && mCharging) {
687 mCharging = false;
688 becomeInactiveIfAppropriateLocked();
689 } else if (charging) {
690 mCharging = charging;
691 becomeActiveLocked("charging");
692 }
693 }
694
695 void scheduleReportActiveLocked(boolean fromMotion) {
696 Message msg = mHandler.obtainMessage(MSG_REPORT_ACTIVE, fromMotion ? 1 : 0,
697 mState == STATE_IDLE ? 1 : 0);
698 mHandler.sendMessage(msg);
699 }
700
701 void becomeActiveLocked(String reason) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700702 if (DEBUG) Slog.i(TAG, "becomeActiveLocked, reason = " + reason);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700703 if (mState != STATE_ACTIVE) {
704 EventLogTags.writeDeviceIdle(STATE_ACTIVE, reason);
705 scheduleReportActiveLocked(false);
706 mState = STATE_ACTIVE;
707 mInactiveTimeout = DEFAULT_INACTIVE_TIMEOUT;
708 mNextIdlePendingDelay = 0;
709 mNextIdleDelay = 0;
710 cancelAlarmLocked();
711 stopMonitoringSignificantMotion();
712 }
713 }
714
715 void becomeInactiveIfAppropriateLocked() {
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700716 if (DEBUG) Slog.d(TAG, "becomeInactiveIfAppropriateLocked()");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700717 if (!mScreenOn && !mCharging && !mIdleDisabled && mState == STATE_ACTIVE) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700718 // Screen has turned off; we are now going to become inactive and start
719 // waiting to see if we will ultimately go idle.
720 mState = STATE_INACTIVE;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700721 if (DEBUG) Slog.d(TAG, "Moved from STATE_ACTIVE to STATE_INACTIVE");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700722 mNextIdlePendingDelay = 0;
723 mNextIdleDelay = 0;
724 scheduleAlarmLocked(mInactiveTimeout, false);
725 EventLogTags.writeDeviceIdle(mState, "no activity");
726 }
727 }
728
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700729 /**
730 * This is called when we've failed to receive a callback from AnyMotionDetector
731 * within the DEFAULT_SENSING_TIMEOUT, to return to STATE_INACTIVE.
732 */
733 void enterInactiveStateLocked() {
734 mInactiveTimeout = DEFAULT_INACTIVE_TIMEOUT;
735 becomeInactiveIfAppropriateLocked();
736 }
737
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700738 void stepIdleStateLocked() {
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700739 if (DEBUG) Slog.d(TAG, "stepIdleStateLocked: mState=" + mState);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700740 EventLogTags.writeDeviceIdleStep();
741
742 final long now = SystemClock.elapsedRealtime();
743 if ((now+DEFAULT_MIN_TIME_TO_ALARM) > mAlarmManager.getNextWakeFromIdleTime()) {
744 // Whoops, there is an upcoming alarm. We don't actually want to go idle.
745 if (mState != STATE_ACTIVE) {
746 becomeActiveLocked("alarm");
747 }
748 return;
749 }
750
751 switch (mState) {
752 case STATE_INACTIVE:
753 // We have now been inactive long enough, it is time to start looking
754 // for significant motion and sleep some more while doing so.
755 startMonitoringSignificantMotion();
756 scheduleAlarmLocked(DEFAULT_IDLE_AFTER_INACTIVE_TIMEOUT, false);
757 // Reset the upcoming idle delays.
758 mNextIdlePendingDelay = DEFAULT_IDLE_PENDING_TIMEOUT;
759 mNextIdleDelay = DEFAULT_IDLE_TIMEOUT;
760 mState = STATE_IDLE_PENDING;
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700761 if (DEBUG) Slog.d(TAG, "Moved from STATE_INACTIVE to STATE_IDLE_PENDING.");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700762 EventLogTags.writeDeviceIdle(mState, "step");
763 break;
764 case STATE_IDLE_PENDING:
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700765 mState = STATE_SENSING;
766 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE_PENDING to STATE_SENSING.");
767 scheduleSensingAlarmLocked(DEFAULT_SENSING_TIMEOUT);
768 mAnyMotionDetector.checkForAnyMotion();
769 break;
770 case STATE_SENSING:
771 cancelSensingAlarmLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700772 case STATE_IDLE_MAINTENANCE:
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700773 scheduleAlarmLocked(mNextIdleDelay, true);
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700774 if (DEBUG) Slog.d(TAG, "Moved to STATE_IDLE. Next alarm in " + mNextIdleDelay +
775 " ms.");
776 mNextIdleDelay = (long)(mNextIdleDelay * DEFAULT_IDLE_FACTOR);
777 if (DEBUG) Slog.d(TAG, "Setting mNextIdleDelay = " + mNextIdleDelay);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700778 if (mNextIdleDelay > DEFAULT_MAX_IDLE_TIMEOUT) {
779 mNextIdleDelay = DEFAULT_MAX_IDLE_TIMEOUT;
780 }
781 mState = STATE_IDLE;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700782 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON);
783 break;
784 case STATE_IDLE:
785 // We have been idling long enough, now it is time to do some work.
786 scheduleAlarmLocked(mNextIdlePendingDelay, false);
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700787 if (DEBUG) Slog.d(TAG, "Moved from STATE_IDLE to STATE_IDLE_MAINTENANCE. " +
788 "Next alarm in " + mNextIdlePendingDelay + " ms.");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700789 mNextIdlePendingDelay = (long)(mNextIdlePendingDelay*DEFAULT_IDLE_PENDING_FACTOR);
790 if (mNextIdlePendingDelay > DEFAULT_MAX_IDLE_PENDING_TIMEOUT) {
791 mNextIdlePendingDelay = DEFAULT_MAX_IDLE_PENDING_TIMEOUT;
792 }
793 mState = STATE_IDLE_MAINTENANCE;
794 EventLogTags.writeDeviceIdle(mState, "step");
795 mHandler.sendEmptyMessage(MSG_REPORT_IDLE_OFF);
796 break;
797 }
798 }
799
800 void significantMotionLocked() {
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700801 if (DEBUG) Slog.d(TAG, "significantMotionLocked()");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700802 // When the sensor goes off, its trigger is automatically removed.
803 mSigMotionActive = false;
804 // The device is not yet active, so we want to go back to the pending idle
805 // state to wait again for no motion. Note that we only monitor for significant
806 // motion after moving out of the inactive state, so no need to worry about that.
807 if (mState != STATE_ACTIVE) {
808 scheduleReportActiveLocked(true);
809 mState = STATE_ACTIVE;
810 mInactiveTimeout = DEFAULT_MOTION_INACTIVE_TIMEOUT;
811 EventLogTags.writeDeviceIdle(mState, "motion");
812 becomeInactiveIfAppropriateLocked();
813 }
814 }
815
816 void startMonitoringSignificantMotion() {
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700817 if (DEBUG) Slog.d(TAG, "startMonitoringSignificantMotion()");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700818 if (mSigMotionSensor != null && !mSigMotionActive) {
819 mSensorManager.requestTriggerSensor(mSigMotionListener, mSigMotionSensor);
820 mSigMotionActive = true;
821 }
822 }
823
824 void stopMonitoringSignificantMotion() {
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700825 if (DEBUG) Slog.d(TAG, "stopMonitoringSignificantMotion()");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700826 if (mSigMotionActive) {
827 mSensorManager.cancelTriggerSensor(mSigMotionListener, mSigMotionSensor);
828 mSigMotionActive = false;
829 }
830 }
831
832 void cancelAlarmLocked() {
833 if (mNextAlarmTime != 0) {
834 mNextAlarmTime = 0;
835 mAlarmManager.cancel(mAlarmIntent);
836 }
837 }
838
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700839 void cancelSensingAlarmLocked() {
840 if (DEBUG) Slog.d(TAG, "cancelSensingAlarmLocked()");
841 mAlarmManager.cancel(mSensingAlarmIntent);
842 }
843
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700844 void scheduleAlarmLocked(long delay, boolean idleUntil) {
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700845 if (DEBUG) Slog.d(TAG, "scheduleAlarmLocked(" + delay + ", " + idleUntil + ")");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700846 if (mSigMotionSensor == null) {
847 // If there is no significant motion sensor on this device, then we won't schedule
848 // alarms, because we can't determine if the device is not moving. This effectively
849 // turns off normal exeuction of device idling, although it is still possible to
850 // manually poke it by pretending like the alarm is going off.
851 return;
852 }
853 mNextAlarmTime = SystemClock.elapsedRealtime() + delay;
854 if (idleUntil) {
855 mAlarmManager.setIdleUntil(AlarmManager.ELAPSED_REALTIME_WAKEUP,
856 mNextAlarmTime, mAlarmIntent);
857 } else {
858 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
859 mNextAlarmTime, mAlarmIntent);
860 }
861 }
862
Kevin Gabayan89ecf822015-05-18 12:10:07 -0700863 void scheduleSensingAlarmLocked(long delay) {
864 if (DEBUG) Slog.d(TAG, "scheduleSensingAlarmLocked(" + delay + ")");
865 mNextAlarmTime = SystemClock.elapsedRealtime() + delay;
866 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
867 mNextAlarmTime, mSensingAlarmIntent);
868 }
869
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700870 private void updateWhitelistAppIdsLocked() {
871 mPowerSaveWhitelistAppIds.clear();
872 for (int i=0; i<mPowerSaveWhitelistApps.size(); i++) {
873 mPowerSaveWhitelistAppIds.put(mPowerSaveWhitelistApps.valueAt(i), true);
874 }
875 for (int i=0; i<mPowerSaveWhitelistUserApps.size(); i++) {
876 mPowerSaveWhitelistAppIds.put(mPowerSaveWhitelistUserApps.valueAt(i), true);
877 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700878 int size = mPowerSaveWhitelistAppIds.size();
879 int[] appids = new int[size];
880 for (int i = 0; i < size; i++) {
881 appids[i] = mPowerSaveWhitelistAppIds.keyAt(i);
882 }
883 mPowerSaveWhitelistAppIdArray = appids;
884 if (mLocalPowerManager != null) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700885 if (DEBUG) {
886 Slog.d(TAG, "Setting wakelock whitelist to "
887 + Arrays.toString(mPowerSaveWhitelistAppIdArray));
888 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700889 mLocalPowerManager.setDeviceIdleWhitelist(mPowerSaveWhitelistAppIdArray);
890 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700891 }
892
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700893 private void updateTempWhitelistAppIdsLocked() {
894 final int size = mTempWhitelistAppIdEndTimes.size();
895 if (mTempWhitelistAppIdArray.length != size) {
896 mTempWhitelistAppIdArray = new int[size];
897 }
898 for (int i = 0; i < size; i++) {
899 mTempWhitelistAppIdArray[i] = mTempWhitelistAppIdEndTimes.keyAt(i);
900 }
901 if (mLocalPowerManager != null) {
902 if (DEBUG) {
903 Slog.d(TAG, "Setting wakelock temp whitelist to "
904 + Arrays.toString(mTempWhitelistAppIdArray));
905 }
906 mLocalPowerManager.setDeviceIdleTempWhitelist(mTempWhitelistAppIdArray);
907 }
908 }
909
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700910 private void reportPowerSaveWhitelistChangedLocked() {
911 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
912 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700913 getContext().sendBroadcastAsUser(intent, UserHandle.OWNER);
914 }
915
916 private void reportTempWhitelistChangedLocked() {
917 Intent intent = new Intent(PowerManager.ACTION_POWER_SAVE_TEMP_WHITELIST_CHANGED);
918 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
919 getContext().sendBroadcastAsUser(intent, UserHandle.OWNER);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700920 }
921
922 void readConfigFileLocked() {
923 Slog.d(TAG, "Reading config from " + mConfigFile.getBaseFile());
924 mPowerSaveWhitelistUserApps.clear();
925 FileInputStream stream;
926 try {
927 stream = mConfigFile.openRead();
928 } catch (FileNotFoundException e) {
929 return;
930 }
931 try {
932 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100933 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700934 readConfigFileLocked(parser);
935 } catch (XmlPullParserException e) {
936 } finally {
937 try {
938 stream.close();
939 } catch (IOException e) {
940 }
941 }
942
943 }
944
945 private void readConfigFileLocked(XmlPullParser parser) {
946 final PackageManager pm = getContext().getPackageManager();
947
948 try {
949 int type;
950 while ((type = parser.next()) != XmlPullParser.START_TAG
951 && type != XmlPullParser.END_DOCUMENT) {
952 ;
953 }
954
955 if (type != XmlPullParser.START_TAG) {
956 throw new IllegalStateException("no start tag found");
957 }
958
959 int outerDepth = parser.getDepth();
960 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
961 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
962 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
963 continue;
964 }
965
966 String tagName = parser.getName();
967 if (tagName.equals("wl")) {
968 String name = parser.getAttributeValue(null, "n");
969 if (name != null) {
970 try {
971 ApplicationInfo ai = pm.getApplicationInfo(name, 0);
972 mPowerSaveWhitelistUserApps.put(ai.packageName,
973 UserHandle.getAppId(ai.uid));
974 } catch (PackageManager.NameNotFoundException e) {
975 }
976 }
977 } else {
978 Slog.w(TAG, "Unknown element under <config>: "
979 + parser.getName());
980 XmlUtils.skipCurrentTag(parser);
981 }
982 }
983
984 } catch (IllegalStateException e) {
985 Slog.w(TAG, "Failed parsing config " + e);
986 } catch (NullPointerException e) {
987 Slog.w(TAG, "Failed parsing config " + e);
988 } catch (NumberFormatException e) {
989 Slog.w(TAG, "Failed parsing config " + e);
990 } catch (XmlPullParserException e) {
991 Slog.w(TAG, "Failed parsing config " + e);
992 } catch (IOException e) {
993 Slog.w(TAG, "Failed parsing config " + e);
994 } catch (IndexOutOfBoundsException e) {
995 Slog.w(TAG, "Failed parsing config " + e);
996 }
997 }
998
999 void writeConfigFileLocked() {
1000 mHandler.removeMessages(MSG_WRITE_CONFIG);
1001 mHandler.sendEmptyMessageDelayed(MSG_WRITE_CONFIG, 5000);
1002 }
1003
1004 void handleWriteConfigFile() {
1005 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
1006
1007 try {
1008 synchronized (this) {
1009 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001010 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001011 writeConfigFileLocked(out);
1012 }
1013 } catch (IOException e) {
1014 }
1015
1016 synchronized (mConfigFile) {
1017 FileOutputStream stream = null;
1018 try {
1019 stream = mConfigFile.startWrite();
1020 memStream.writeTo(stream);
1021 stream.flush();
1022 FileUtils.sync(stream);
1023 stream.close();
1024 mConfigFile.finishWrite(stream);
1025 } catch (IOException e) {
1026 Slog.w(TAG, "Error writing config file", e);
1027 mConfigFile.failWrite(stream);
1028 }
1029 }
1030 }
1031
1032 void writeConfigFileLocked(XmlSerializer out) throws IOException {
1033 out.startDocument(null, true);
1034 out.startTag(null, "config");
1035 for (int i=0; i<mPowerSaveWhitelistUserApps.size(); i++) {
1036 String name = mPowerSaveWhitelistUserApps.keyAt(i);
1037 out.startTag(null, "wl");
1038 out.attribute(null, "n", name);
1039 out.endTag(null, "wl");
1040 }
1041 out.endTag(null, "config");
1042 out.endDocument();
1043 }
1044
1045 private void dumpHelp(PrintWriter pw) {
1046 pw.println("Device idle controller (deviceidle) dump options:");
1047 pw.println(" [-h] [CMD]");
1048 pw.println(" -h: print this help text.");
1049 pw.println("Commands:");
1050 pw.println(" step");
1051 pw.println(" Immediately step to next state, without waiting for alarm.");
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07001052 pw.println(" disable");
1053 pw.println(" Completely disable device idle mode.");
1054 pw.println(" enable");
1055 pw.println(" Re-enable device idle mode after it had previously been disabled.");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001056 pw.println(" whitelist");
1057 pw.println(" Add (prefix with +) or remove (prefix with -) packages.");
1058 }
1059
1060 void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1061 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1062 != PackageManager.PERMISSION_GRANTED) {
1063 pw.println("Permission Denial: can't dump DeviceIdleController from from pid="
1064 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1065 + " without permission " + android.Manifest.permission.DUMP);
1066 return;
1067 }
1068
1069 if (args != null) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001070 int userId = UserHandle.USER_OWNER;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001071 for (int i=0; i<args.length; i++) {
1072 String arg = args[i];
1073 if ("-h".equals(arg)) {
1074 dumpHelp(pw);
1075 return;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001076 } else if ("-u".equals(arg)) {
1077 i++;
1078 if (i < args.length) {
1079 arg = args[i];
1080 userId = Integer.parseInt(arg);
1081 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07001082 } else if ("-a".equals(arg)) {
1083 // Ignore, we always dump all.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001084 } else if ("step".equals(arg)) {
1085 synchronized (this) {
1086 stepIdleStateLocked();
1087 pw.print("Stepped to: "); pw.println(stateToString(mState));
1088 }
1089 return;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07001090 } else if ("disable".equals(arg)) {
1091 synchronized (this) {
1092 if (!mIdleDisabled) {
1093 mIdleDisabled = true;
1094 becomeActiveLocked("disabled");
1095 pw.println("Idle mode disabled");
1096 }
1097 }
1098 return;
1099 } else if ("enable".equals(arg)) {
1100 synchronized (this) {
1101 if (mIdleDisabled) {
1102 mIdleDisabled = false;
1103 becomeInactiveIfAppropriateLocked();
1104 pw.println("Idle mode enabled");
1105 }
1106 }
1107 return;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001108 } else if ("whitelist".equals(arg)) {
1109 i++;
1110 while (i < args.length) {
1111 arg = args[i];
1112 i++;
1113 if (arg.length() < 1 || (arg.charAt(0) != '-'
1114 && arg.charAt(0) != '+')) {
1115 pw.println("Package must be prefixed with + or -: " + arg);
1116 return;
1117 }
1118 char op = arg.charAt(0);
1119 String pkg = arg.substring(1);
1120 if (op == '+') {
1121 if (addPowerSaveWhitelistAppInternal(pkg)) {
1122 pw.println("Added: " + pkg);
1123 } else {
1124 pw.println("Unknown package: " + pkg);
1125 }
1126 } else {
1127 if (removePowerSaveWhitelistAppInternal(pkg)) {
1128 pw.println("Removed: " + pkg);
1129 }
1130 }
1131 }
1132 return;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07001133 } else if ("tempwhitelist".equals(arg)) {
1134 i++;
1135 if (i >= args.length) {
1136 pw.println("At least one package name must be specified");
1137 return;
1138 }
1139 while (i < args.length) {
1140 arg = args[i];
1141 i++;
1142 addPowerSaveTempWhitelistAppInternal(arg, 10000L, userId);
1143 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001144 } else if (arg.length() > 0 && arg.charAt(0) == '-'){
1145 pw.println("Unknown option: " + arg);
1146 return;
1147 } else {
1148 pw.println("Unknown command: " + arg);
1149 return;
1150 }
1151 }
1152 }
1153
1154 synchronized (this) {
1155 int size = mPowerSaveWhitelistApps.size();
1156 if (size > 0) {
1157 pw.println(" Whitelist system apps:");
1158 for (int i = 0; i < size; i++) {
1159 pw.print(" ");
1160 pw.println(mPowerSaveWhitelistApps.keyAt(i));
1161 }
1162 }
1163 size = mPowerSaveWhitelistUserApps.size();
1164 if (size > 0) {
1165 pw.println(" Whitelist user apps:");
1166 for (int i = 0; i < size; i++) {
1167 pw.print(" ");
1168 pw.println(mPowerSaveWhitelistUserApps.keyAt(i));
1169 }
1170 }
1171 size = mPowerSaveWhitelistAppIds.size();
1172 if (size > 0) {
1173 pw.println(" Whitelist app uids:");
1174 for (int i = 0; i < size; i++) {
1175 pw.print(" UID=");
1176 pw.print(mPowerSaveWhitelistAppIds.keyAt(i));
1177 pw.print(": ");
1178 pw.print(mPowerSaveWhitelistAppIds.valueAt(i));
1179 pw.println();
1180 }
1181 }
1182 pw.print(" mSigMotionSensor="); pw.println(mSigMotionSensor);
1183 pw.print(" mCurDisplay="); pw.println(mCurDisplay);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07001184 pw.print(" mIdleDisabled="); pw.println(mIdleDisabled);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001185 pw.print(" mScreenOn="); pw.println(mScreenOn);
1186 pw.print(" mCharging="); pw.println(mCharging);
1187 pw.print(" mSigMotionActive="); pw.println(mSigMotionActive);
1188 pw.print(" mState="); pw.println(stateToString(mState));
1189 pw.print(" mInactiveTimeout="); TimeUtils.formatDuration(mInactiveTimeout, pw);
1190 pw.println();
1191 if (mNextAlarmTime != 0) {
1192 pw.print(" mNextAlarmTime=");
1193 TimeUtils.formatDuration(mNextAlarmTime, SystemClock.elapsedRealtime(), pw);
1194 pw.println();
1195 }
1196 if (mNextIdlePendingDelay != 0) {
1197 pw.print(" mNextIdlePendingDelay=");
1198 TimeUtils.formatDuration(mNextIdlePendingDelay, pw);
1199 pw.println();
1200 }
1201 if (mNextIdleDelay != 0) {
1202 pw.print(" mNextIdleDelay=");
1203 TimeUtils.formatDuration(mNextIdleDelay, pw);
1204 pw.println();
1205 }
1206 }
1207 }
1208}