blob: 05ffcf071268af9081cbe5011b9216af4838069e [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 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
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080019import android.app.Activity;
Adrian Roosc42a1e12014-07-07 23:35:53 +020020import android.app.ActivityManager;
Christopher Tate57ceaaa2013-07-19 16:30:43 -070021import android.app.AlarmManager;
Christopher Tate14a7bb02015-10-01 10:24:31 -070022import android.app.AppOpsManager;
Dianne Hackborna750a632015-06-16 17:18:23 -070023import android.app.BroadcastOptions;
Christopher Tate14a7bb02015-10-01 10:24:31 -070024import android.app.IAlarmCompleteListener;
25import android.app.IAlarmListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.app.IAlarmManager;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070027import android.app.IUidObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.app.PendingIntent;
29import android.content.BroadcastReceiver;
Dianne Hackborna750a632015-06-16 17:18:23 -070030import android.content.ContentResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.content.Context;
32import android.content.Intent;
33import android.content.IntentFilter;
34import android.content.pm.PackageManager;
Dianne Hackborna750a632015-06-16 17:18:23 -070035import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.net.Uri;
37import android.os.Binder;
38import android.os.Bundle;
Christopher Tate247571462017-04-10 11:45:05 -070039import android.os.Environment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.os.Handler;
Adam Lesinski182f73f2013-12-05 16:48:06 -080041import android.os.IBinder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.os.Message;
43import android.os.PowerManager;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070044import android.os.Process;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070045import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.os.SystemClock;
47import android.os.SystemProperties;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070048import android.os.UserHandle;
Christopher Tatec4a07d12012-04-06 14:19:13 -070049import android.os.WorkSource;
Adrian Roosc42a1e12014-07-07 23:35:53 +020050import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.text.TextUtils;
Adrian Roosc42a1e12014-07-07 23:35:53 +020052import android.text.format.DateFormat;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080053import android.util.ArrayMap;
Dianne Hackborna750a632015-06-16 17:18:23 -070054import android.util.KeyValueListParser;
Adrian Roosc42a1e12014-07-07 23:35:53 +020055import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080056import android.util.Slog;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080057import android.util.SparseArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +020058import android.util.SparseBooleanArray;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -070059import android.util.SparseLongArray;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070060import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061
Christopher Tate4cb338d2013-07-26 13:11:31 -070062import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import java.io.FileDescriptor;
64import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070065import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -080067import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import java.util.Calendar;
69import java.util.Collections;
70import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -050071import java.util.Date;
Christopher Tate1590f1e2014-10-02 17:27:57 -070072import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -070073import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +020074import java.util.Locale;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070075import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import java.util.TimeZone;
John Spurlock604a5ee2015-06-01 12:27:22 -040077import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078
Christopher Tatee0a22b32013-07-11 14:43:13 -070079import static android.app.AlarmManager.RTC_WAKEUP;
80import static android.app.AlarmManager.RTC;
81import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
82import static android.app.AlarmManager.ELAPSED_REALTIME;
83
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060084import com.android.internal.util.DumpUtils;
Dianne Hackborn81038902012-11-26 17:04:09 -080085import com.android.internal.util.LocalLog;
86
Adam Lesinski182f73f2013-12-05 16:48:06 -080087class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -070088 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
89 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -080090 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -070091 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -080092 static final int TIME_CHANGED_MASK = 1 << 16;
93 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -080094
Christopher Tatee0a22b32013-07-11 14:43:13 -070095 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -080096 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -080097
Adam Lesinski182f73f2013-12-05 16:48:06 -080098 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -080099 static final boolean localLOGV = false;
100 static final boolean DEBUG_BATCH = localLOGV || false;
101 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200102 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700103 static final boolean DEBUG_LISTENER_CALLBACK = localLOGV || false;
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800104 static final boolean DEBUG_WAKELOCK = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700105 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700106 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800107 static final int ALARM_EVENT = 1;
108 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200109
Christopher Tate14a7bb02015-10-01 10:24:31 -0700110 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800112 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113
Adam Lesinski182f73f2013-12-05 16:48:06 -0800114 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700115
Christopher Tate24cd46f2016-02-02 14:28:01 -0800116 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT =
117 new Intent(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED)
118 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Adrian Roosc42a1e12014-07-07 23:35:53 +0200119
Adam Lesinski182f73f2013-12-05 16:48:06 -0800120 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800121
Christopher Tate14a7bb02015-10-01 10:24:31 -0700122 AppOpsManager mAppOps;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800123 DeviceIdleController.LocalService mLocalDeviceIdleController;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700124
Adam Lesinski182f73f2013-12-05 16:48:06 -0800125 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800126
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800127 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800128 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700129 private long mNextNonWakeup;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -0700130 private long mLastWakeupSet;
131 private long mLastWakeup;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800132 int mBroadcastRefCount = 0;
133 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700134 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700135 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
136 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800137 final AlarmHandler mHandler = new AlarmHandler();
138 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700139 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700141 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800142 PendingIntent mTimeTickSender;
143 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700144 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700145 boolean mInteractive = true;
146 long mNonInteractiveStartTime;
147 long mNonInteractiveTime;
148 long mLastAlarmDeliveryTime;
149 long mStartCurrentDelayTime;
150 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700151 long mLastTimeChangeClockTime;
152 long mLastTimeChangeRealtime;
Dianne Hackborna750a632015-06-16 17:18:23 -0700153 long mAllowWhileIdleMinTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700154 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800155
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700156 /**
Dianne Hackborn262ae5c2016-02-10 16:28:29 -0800157 * The current set of user whitelisted apps for device idle mode, meaning these are allowed
158 * to freely schedule alarms.
159 */
160 int[] mDeviceIdleUserWhitelist = new int[0];
161
162 /**
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700163 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
164 * used to determine the earliest we can dispatch the next such alarm.
165 */
166 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
167
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700168 final static class IdleDispatchEntry {
169 int uid;
170 String pkg;
171 String tag;
172 String op;
173 long elapsedRealtime;
174 long argRealtime;
175 }
176 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
177
Dianne Hackborna750a632015-06-16 17:18:23 -0700178 /**
179 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
180 */
181 Bundle mIdleOptions;
182
Jose Lima235510e2014-08-13 12:50:01 -0700183 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
184 new SparseArray<>();
185 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
186 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200187 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
188 new SparseBooleanArray();
189 private boolean mNextAlarmClockMayChange;
190
191 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700192 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
193 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200194
Dianne Hackborna750a632015-06-16 17:18:23 -0700195 /**
196 * All times are in milliseconds. These constants are kept synchronized with the system
197 * global Settings. Any access to this class or its fields should be done while
198 * holding the AlarmManagerService.mLock lock.
199 */
200 private final class Constants extends ContentObserver {
201 // Key names stored in the settings value.
202 private static final String KEY_MIN_FUTURITY = "min_futurity";
203 private static final String KEY_MIN_INTERVAL = "min_interval";
204 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
205 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
206 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
207 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700208 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Dianne Hackborna750a632015-06-16 17:18:23 -0700209
210 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
211 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tateaa244da2015-08-27 15:57:57 -0700212 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700213 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700214 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
215
Christopher Tate14a7bb02015-10-01 10:24:31 -0700216 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
217
Dianne Hackborna750a632015-06-16 17:18:23 -0700218 // Minimum futurity of a new alarm
219 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
220
221 // Minimum alarm recurrence interval
222 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
223
224 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
225 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
226
227 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
228 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
229
230 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
231 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
232 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
233
Christopher Tate14a7bb02015-10-01 10:24:31 -0700234 // Direct alarm listener callback timeout
235 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
236
Dianne Hackborna750a632015-06-16 17:18:23 -0700237 private ContentResolver mResolver;
238 private final KeyValueListParser mParser = new KeyValueListParser(',');
239 private long mLastAllowWhileIdleWhitelistDuration = -1;
240
241 public Constants(Handler handler) {
242 super(handler);
243 updateAllowWhileIdleMinTimeLocked();
244 updateAllowWhileIdleWhitelistDurationLocked();
245 }
246
247 public void start(ContentResolver resolver) {
248 mResolver = resolver;
249 mResolver.registerContentObserver(Settings.Global.getUriFor(
250 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
251 updateConstants();
252 }
253
254 public void updateAllowWhileIdleMinTimeLocked() {
255 mAllowWhileIdleMinTime = mPendingIdleUntil != null
256 ? ALLOW_WHILE_IDLE_LONG_TIME : ALLOW_WHILE_IDLE_SHORT_TIME;
257 }
258
259 public void updateAllowWhileIdleWhitelistDurationLocked() {
260 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
261 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
262 BroadcastOptions opts = BroadcastOptions.makeBasic();
263 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
264 mIdleOptions = opts.toBundle();
265 }
266 }
267
268 @Override
269 public void onChange(boolean selfChange, Uri uri) {
270 updateConstants();
271 }
272
273 private void updateConstants() {
274 synchronized (mLock) {
275 try {
276 mParser.setString(Settings.Global.getString(mResolver,
277 Settings.Global.ALARM_MANAGER_CONSTANTS));
278 } catch (IllegalArgumentException e) {
279 // Failed to parse the settings string, log this and move on
280 // with defaults.
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800281 Slog.e(TAG, "Bad alarm manager settings", e);
Dianne Hackborna750a632015-06-16 17:18:23 -0700282 }
283
284 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
285 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
286 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
287 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
288 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
289 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
290 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
291 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
292 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700293 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
294 DEFAULT_LISTENER_TIMEOUT);
Dianne Hackborna750a632015-06-16 17:18:23 -0700295
296 updateAllowWhileIdleMinTimeLocked();
297 updateAllowWhileIdleWhitelistDurationLocked();
298 }
299 }
300
301 void dump(PrintWriter pw) {
302 pw.println(" Settings:");
303
304 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
305 TimeUtils.formatDuration(MIN_FUTURITY, pw);
306 pw.println();
307
308 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
309 TimeUtils.formatDuration(MIN_INTERVAL, pw);
310 pw.println();
311
Christopher Tate14a7bb02015-10-01 10:24:31 -0700312 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
313 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
314 pw.println();
315
Dianne Hackborna750a632015-06-16 17:18:23 -0700316 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
317 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
318 pw.println();
319
320 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
321 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
322 pw.println();
323
324 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
325 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
326 pw.println();
327 }
328 }
329
330 final Constants mConstants;
331
Christopher Tate1590f1e2014-10-02 17:27:57 -0700332 // Alarm delivery ordering bookkeeping
333 static final int PRIO_TICK = 0;
334 static final int PRIO_WAKEUP = 1;
335 static final int PRIO_NORMAL = 2;
336
Dianne Hackborna750a632015-06-16 17:18:23 -0700337 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700338 int seq;
339 int priority;
340
341 PriorityClass() {
342 seq = mCurrentSeq - 1;
343 priority = PRIO_NORMAL;
344 }
345 }
346
Dianne Hackborna750a632015-06-16 17:18:23 -0700347 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700348 int mCurrentSeq = 0;
349
Dianne Hackborna750a632015-06-16 17:18:23 -0700350 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700351 public long when;
352 public int uid;
353 public String action;
354
355 public WakeupEvent(long theTime, int theUid, String theAction) {
356 when = theTime;
357 uid = theUid;
358 action = theAction;
359 }
360 }
361
Adam Lesinski182f73f2013-12-05 16:48:06 -0800362 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
363 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700364
Adrian Roosc42a1e12014-07-07 23:35:53 +0200365 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700366 long start; // These endpoints are always in ELAPSED
367 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700368 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700369
370 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
371
372 Batch() {
373 start = 0;
374 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700375 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700376 }
377
378 Batch(Alarm seed) {
379 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700380 end = seed.maxWhenElapsed;
381 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700382 alarms.add(seed);
383 }
384
385 int size() {
386 return alarms.size();
387 }
388
389 Alarm get(int index) {
390 return alarms.get(index);
391 }
392
393 boolean canHold(long whenElapsed, long maxWhen) {
394 return (end >= whenElapsed) && (start <= maxWhen);
395 }
396
397 boolean add(Alarm alarm) {
398 boolean newStart = false;
399 // narrows the batch if necessary; presumes that canHold(alarm) is true
400 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
401 if (index < 0) {
402 index = 0 - index - 1;
403 }
404 alarms.add(index, alarm);
405 if (DEBUG_BATCH) {
406 Slog.v(TAG, "Adding " + alarm + " to " + this);
407 }
408 if (alarm.whenElapsed > start) {
409 start = alarm.whenElapsed;
410 newStart = true;
411 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700412 if (alarm.maxWhenElapsed < end) {
413 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700414 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700415 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700416
417 if (DEBUG_BATCH) {
418 Slog.v(TAG, " => now " + this);
419 }
420 return newStart;
421 }
422
Christopher Tate14a7bb02015-10-01 10:24:31 -0700423 boolean remove(final PendingIntent operation, final IAlarmListener listener) {
424 if (operation == null && listener == null) {
425 if (localLOGV) {
426 Slog.w(TAG, "requested remove() of null operation",
427 new RuntimeException("here"));
428 }
429 return false;
430 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700431 boolean didRemove = false;
432 long newStart = 0; // recalculate endpoints as we go
433 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700434 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700435 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700436 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700437 if (alarm.matches(operation, listener)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700438 alarms.remove(i);
439 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200440 if (alarm.alarmClock != null) {
441 mNextAlarmClockMayChange = true;
442 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700443 } else {
444 if (alarm.whenElapsed > newStart) {
445 newStart = alarm.whenElapsed;
446 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700447 if (alarm.maxWhenElapsed < newEnd) {
448 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700449 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700450 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700451 i++;
452 }
453 }
454 if (didRemove) {
455 // commit the new batch bounds
456 start = newStart;
457 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700458 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700459 }
460 return didRemove;
461 }
462
463 boolean remove(final String packageName) {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700464 if (packageName == null) {
465 if (localLOGV) {
466 Slog.w(TAG, "requested remove() of null packageName",
467 new RuntimeException("here"));
468 }
469 return false;
470 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700471 boolean didRemove = false;
472 long newStart = 0; // recalculate endpoints as we go
473 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700474 int newFlags = 0;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700475 for (int i = alarms.size()-1; i >= 0; i--) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700476 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700477 if (alarm.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700478 alarms.remove(i);
479 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200480 if (alarm.alarmClock != null) {
481 mNextAlarmClockMayChange = true;
482 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700483 } else {
484 if (alarm.whenElapsed > newStart) {
485 newStart = alarm.whenElapsed;
486 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700487 if (alarm.maxWhenElapsed < newEnd) {
488 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700489 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700490 newFlags |= alarm.flags;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700491 }
492 }
493 if (didRemove) {
494 // commit the new batch bounds
495 start = newStart;
496 end = newEnd;
497 flags = newFlags;
498 }
499 return didRemove;
500 }
501
502 boolean removeForStopped(final int uid) {
503 boolean didRemove = false;
504 long newStart = 0; // recalculate endpoints as we go
505 long newEnd = Long.MAX_VALUE;
506 int newFlags = 0;
507 for (int i = alarms.size()-1; i >= 0; i--) {
508 Alarm alarm = alarms.get(i);
509 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800510 if (alarm.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
511 uid, alarm.packageName)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700512 alarms.remove(i);
513 didRemove = true;
514 if (alarm.alarmClock != null) {
515 mNextAlarmClockMayChange = true;
516 }
517 } else {
518 if (alarm.whenElapsed > newStart) {
519 newStart = alarm.whenElapsed;
520 }
521 if (alarm.maxWhenElapsed < newEnd) {
522 newEnd = alarm.maxWhenElapsed;
523 }
524 newFlags |= alarm.flags;
525 }
526 } catch (RemoteException e) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700527 }
528 }
529 if (didRemove) {
530 // commit the new batch bounds
531 start = newStart;
532 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700533 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700534 }
535 return didRemove;
536 }
537
538 boolean remove(final int userHandle) {
539 boolean didRemove = false;
540 long newStart = 0; // recalculate endpoints as we go
541 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700542 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700543 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700544 if (UserHandle.getUserId(alarm.creatorUid) == userHandle) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700545 alarms.remove(i);
546 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200547 if (alarm.alarmClock != null) {
548 mNextAlarmClockMayChange = true;
549 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700550 } else {
551 if (alarm.whenElapsed > newStart) {
552 newStart = alarm.whenElapsed;
553 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700554 if (alarm.maxWhenElapsed < newEnd) {
555 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700556 }
557 i++;
558 }
559 }
560 if (didRemove) {
561 // commit the new batch bounds
562 start = newStart;
563 end = newEnd;
564 }
565 return didRemove;
566 }
567
568 boolean hasPackage(final String packageName) {
569 final int N = alarms.size();
570 for (int i = 0; i < N; i++) {
571 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700572 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700573 return true;
574 }
575 }
576 return false;
577 }
578
579 boolean hasWakeups() {
580 final int N = alarms.size();
581 for (int i = 0; i < N; i++) {
582 Alarm a = alarms.get(i);
583 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
584 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
585 return true;
586 }
587 }
588 return false;
589 }
590
591 @Override
592 public String toString() {
593 StringBuilder b = new StringBuilder(40);
594 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
595 b.append(" num="); b.append(size());
596 b.append(" start="); b.append(start);
597 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700598 if (flags != 0) {
599 b.append(" flgs=0x");
600 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700601 }
602 b.append('}');
603 return b.toString();
604 }
605 }
606
607 static class BatchTimeOrder implements Comparator<Batch> {
608 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800609 long when1 = b1.start;
610 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800611 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700612 return 1;
613 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800614 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700615 return -1;
616 }
617 return 0;
618 }
619 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800620
621 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
622 @Override
623 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700624 // priority class trumps everything. TICK < WAKEUP < NORMAL
625 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
626 return -1;
627 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
628 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800629 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700630
631 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800632 if (lhs.whenElapsed < rhs.whenElapsed) {
633 return -1;
634 } else if (lhs.whenElapsed > rhs.whenElapsed) {
635 return 1;
636 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700637
638 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800639 return 0;
640 }
641 };
642
Christopher Tate1590f1e2014-10-02 17:27:57 -0700643 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
644 final int N = alarms.size();
645 for (int i = 0; i < N; i++) {
646 Alarm a = alarms.get(i);
647
648 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700649 if (a.operation != null
650 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700651 alarmPrio = PRIO_TICK;
652 } else if (a.wakeup) {
653 alarmPrio = PRIO_WAKEUP;
654 } else {
655 alarmPrio = PRIO_NORMAL;
656 }
657
658 PriorityClass packagePrio = a.priorityClass;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700659 String alarmPackage = (a.operation != null)
660 ? a.operation.getCreatorPackage()
661 : a.packageName;
662 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700663 if (packagePrio == null) {
664 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700665 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700666 }
667 a.priorityClass = packagePrio;
668
669 if (packagePrio.seq != mCurrentSeq) {
670 // first alarm we've seen in the current delivery generation from this package
671 packagePrio.priority = alarmPrio;
672 packagePrio.seq = mCurrentSeq;
673 } else {
674 // Multiple alarms from this package being delivered in this generation;
675 // bump the package's delivery class if it's warranted.
676 // TICK < WAKEUP < NORMAL
677 if (alarmPrio < packagePrio.priority) {
678 packagePrio.priority = alarmPrio;
679 }
680 }
681 }
682 }
683
Christopher Tatee0a22b32013-07-11 14:43:13 -0700684 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800685 static final long MIN_FUZZABLE_INTERVAL = 10000;
686 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700687 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
688
689 // set to null if in idle mode; while in this mode, any alarms we don't want
690 // to run during this time are placed in mPendingWhileIdleAlarms
691 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700692 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700693 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700694
Jeff Brownb880d882014-02-10 19:47:07 -0800695 public AlarmManagerService(Context context) {
696 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700697 mConstants = new Constants(mHandler);
Jeff Brownb880d882014-02-10 19:47:07 -0800698 }
699
Christopher Tatee0a22b32013-07-11 14:43:13 -0700700 static long convertToElapsed(long when, int type) {
701 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
702 if (isRtc) {
703 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
704 }
705 return when;
706 }
707
708 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
709 // calculate the end of our nominal delivery window for the alarm.
710 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
711 // Current heuristic: batchable window is 75% of either the recurrence interval
712 // [for a periodic alarm] or of the time from now to the desired delivery time,
713 // with a minimum delay/interval of 10 seconds, under which we will simply not
714 // defer the alarm.
715 long futurity = (interval == 0)
716 ? (triggerAtTime - now)
717 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700718 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700719 futurity = 0;
720 }
721 return triggerAtTime + (long)(.75 * futurity);
722 }
723
724 // returns true if the batch was added at the head
725 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
726 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
727 if (index < 0) {
728 index = 0 - index - 1;
729 }
730 list.add(index, newBatch);
731 return (index == 0);
732 }
733
Christopher Tate385e4982013-07-23 18:22:29 -0700734 // Return the index of the matching batch, or -1 if none found.
735 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700736 final int N = mAlarmBatches.size();
737 for (int i = 0; i < N; i++) {
738 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700739 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700740 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700741 }
742 }
Christopher Tate385e4982013-07-23 18:22:29 -0700743 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700744 }
745
746 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
747 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700748 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700749 rebatchAllAlarmsLocked(true);
750 }
751 }
752
753 void rebatchAllAlarmsLocked(boolean doValidate) {
754 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
755 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700756 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700757 final long nowElapsed = SystemClock.elapsedRealtime();
758 final int oldBatches = oldSet.size();
759 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
760 Batch batch = oldSet.get(batchNum);
761 final int N = batch.size();
762 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700763 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700764 }
765 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700766 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
767 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
768 + " to " + mPendingIdleUntil);
769 if (mPendingIdleUntil == null) {
770 // Somehow we lost this... we need to restore all of the pending alarms.
771 restorePendingWhileIdleAlarmsLocked();
772 }
773 }
774 rescheduleKernelAlarmsLocked();
775 updateNextAlarmClockLocked();
776 }
777
778 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
779 a.when = a.origWhen;
780 long whenElapsed = convertToElapsed(a.when, a.type);
781 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700782 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700783 // Exact
784 maxElapsed = whenElapsed;
785 } else {
786 // Not exact. Preserve any explicit window, otherwise recalculate
787 // the window based on the alarm's new futurity. Note that this
788 // reflects a policy of preferring timely to deferred delivery.
789 maxElapsed = (a.windowLength > 0)
790 ? (whenElapsed + a.windowLength)
791 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
792 }
793 a.whenElapsed = whenElapsed;
794 a.maxWhenElapsed = maxElapsed;
795 setImplLocked(a, true, doValidate);
796 }
797
798 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700799 if (RECORD_DEVICE_IDLE_ALARMS) {
800 IdleDispatchEntry ent = new IdleDispatchEntry();
801 ent.uid = 0;
802 ent.pkg = "FINISH IDLE";
803 ent.elapsedRealtime = SystemClock.elapsedRealtime();
804 mAllowWhileIdleDispatches.add(ent);
805 }
806
Dianne Hackborn35d54032015-04-23 10:30:43 -0700807 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700808 if (mPendingWhileIdleAlarms.size() > 0) {
809 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
810 mPendingWhileIdleAlarms = new ArrayList<>();
811 final long nowElapsed = SystemClock.elapsedRealtime();
812 for (int i=alarms.size() - 1; i >= 0; i--) {
813 Alarm a = alarms.get(i);
814 reAddAlarmLocked(a, nowElapsed, false);
815 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700816 }
Dianne Hackborn35d54032015-04-23 10:30:43 -0700817
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700818 // Make sure we are using the correct ALLOW_WHILE_IDLE min time.
Dianne Hackborna750a632015-06-16 17:18:23 -0700819 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700820
Dianne Hackborn35d54032015-04-23 10:30:43 -0700821 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700822 rescheduleKernelAlarmsLocked();
823 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -0700824
825 // And send a TIME_TICK right now, since it is important to get the UI updated.
826 try {
827 mTimeTickSender.send();
828 } catch (PendingIntent.CanceledException e) {
829 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700830 }
831
Christopher Tate14a7bb02015-10-01 10:24:31 -0700832 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -0800833 final PendingIntent mPendingIntent;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700834 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -0700835 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700836 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700837 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800838 final BroadcastStats mBroadcastStats;
839 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800840 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800841
Christopher Tate14a7bb02015-10-01 10:24:31 -0700842 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
843 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
844 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800845 mPendingIntent = pendingIntent;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700846 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -0700847 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700848 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700849 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700850 mBroadcastStats = (pendingIntent != null)
851 ? service.getStatsLocked(pendingIntent)
852 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700853 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -0800854 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700855 fs = new FilterStats(mBroadcastStats, mTag);
856 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -0800857 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700858 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -0800859 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800860 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800861 }
Makoto Onuki33955e12017-03-01 18:11:00 -0800862
863 @Override
864 public String toString() {
865 return "InFlight{"
866 + "pendingIntent=" + mPendingIntent
867 + ", workSource=" + mWorkSource
868 + ", uid=" + mUid
869 + ", tag=" + mTag
870 + ", broadcastStats=" + mBroadcastStats
871 + ", filterStats=" + mFilterStats
872 + ", alarmType=" + mAlarmType
873 + "}";
874 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800876
Adam Lesinski182f73f2013-12-05 16:48:06 -0800877 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -0800878 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700879 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800880
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700881 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800883 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884 int numWakeup;
885 long startTime;
886 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -0800887
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700888 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800889 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700890 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800891 }
Makoto Onuki33955e12017-03-01 18:11:00 -0800892
893 @Override
894 public String toString() {
895 return "FilterStats{"
896 + "tag=" + mTag
897 + ", lastTime=" + lastTime
898 + ", aggregateTime=" + aggregateTime
899 + ", count=" + count
900 + ", numWakeup=" + numWakeup
901 + ", startTime=" + startTime
902 + ", nesting=" + nesting
903 + "}";
904 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800905 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700906
Adam Lesinski182f73f2013-12-05 16:48:06 -0800907 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800908 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800909 final String mPackageName;
910
911 long aggregateTime;
912 int count;
913 int numWakeup;
914 long startTime;
915 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700916 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -0800917
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800918 BroadcastStats(int uid, String packageName) {
919 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800920 mPackageName = packageName;
921 }
Makoto Onuki33955e12017-03-01 18:11:00 -0800922
923 @Override
924 public String toString() {
925 return "BroadcastStats{"
926 + "uid=" + mUid
927 + ", packageName=" + mPackageName
928 + ", aggregateTime=" + aggregateTime
929 + ", count=" + count
930 + ", numWakeup=" + numWakeup
931 + ", startTime=" + startTime
932 + ", nesting=" + nesting
933 + "}";
934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700936
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800937 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
938 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700939
940 int mNumDelayedAlarms = 0;
941 long mTotalDelayTime = 0;
942 long mMaxDelayTime = 0;
943
Adam Lesinski182f73f2013-12-05 16:48:06 -0800944 @Override
945 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800946 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800947 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800948
949 // We have to set current TimeZone info to kernel
950 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -0800951 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800952
Christopher Tate247571462017-04-10 11:45:05 -0700953 // Also sure that we're booting with a halfway sensible current time
954 if (mNativeData != 0) {
955 final long systemBuildTime = Environment.getRootDirectory().lastModified();
956 if (System.currentTimeMillis() < systemBuildTime) {
957 Slog.i(TAG, "Current time only " + System.currentTimeMillis()
958 + ", advancing to build time " + systemBuildTime);
959 setKernelTime(mNativeData, systemBuildTime);
960 }
961 }
962
Adam Lesinski182f73f2013-12-05 16:48:06 -0800963 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800964 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800965
Adam Lesinski182f73f2013-12-05 16:48:06 -0800966 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700968 Intent.FLAG_RECEIVER_REGISTERED_ONLY
Chad Brubaker291df4f2017-03-14 10:23:02 -0700969 | Intent.FLAG_RECEIVER_FOREGROUND
970 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700971 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800972 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -0700973 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
974 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800975 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700976 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977
978 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -0800979 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 mClockReceiver.scheduleTimeTickEvent();
981 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700982 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 mUninstallReceiver = new UninstallReceiver();
984
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800985 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800986 AlarmThread waitThread = new AlarmThread();
987 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800989 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800991
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700992 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800993 ActivityManager.getService().registerUidObserver(new UidObserver(),
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800994 ActivityManager.UID_OBSERVER_IDLE, ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700995 } catch (RemoteException e) {
996 // ignored; both services live in system_server
997 }
998
Adam Lesinski182f73f2013-12-05 16:48:06 -0800999 publishBinderService(Context.ALARM_SERVICE, mService);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001000 publishLocalService(LocalService.class, new LocalService());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001002
1003 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001004 public void onBootPhase(int phase) {
1005 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1006 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -07001007 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001008 mLocalDeviceIdleController
1009 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackborna750a632015-06-16 17:18:23 -07001010 }
1011 }
1012
1013 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014 protected void finalize() throws Throwable {
1015 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001016 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 } finally {
1018 super.finalize();
1019 }
1020 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001021
Adam Lesinski182f73f2013-12-05 16:48:06 -08001022 void setTimeZoneImpl(String tz) {
1023 if (TextUtils.isEmpty(tz)) {
1024 return;
David Christieebe51fc2013-07-26 13:23:29 -07001025 }
1026
Adam Lesinski182f73f2013-12-05 16:48:06 -08001027 TimeZone zone = TimeZone.getTimeZone(tz);
1028 // Prevent reentrant calls from stepping on each other when writing
1029 // the time zone property
1030 boolean timeZoneWasChanged = false;
1031 synchronized (this) {
1032 String current = SystemProperties.get(TIMEZONE_PROPERTY);
1033 if (current == null || !current.equals(zone.getID())) {
1034 if (localLOGV) {
1035 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
1036 }
1037 timeZoneWasChanged = true;
1038 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
1039 }
1040
1041 // Update the kernel timezone information
1042 // Kernel tracks time offsets as 'minutes west of GMT'
1043 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001044 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001045 }
1046
1047 TimeZone.setDefault(null);
1048
1049 if (timeZoneWasChanged) {
1050 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001051 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1052 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001053 intent.putExtra("time-zone", zone.getID());
1054 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001057
Adam Lesinski182f73f2013-12-05 16:48:06 -08001058 void removeImpl(PendingIntent operation) {
1059 if (operation == null) {
1060 return;
1061 }
1062 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001063 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001064 }
1065 }
1066
1067 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001068 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1069 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1070 int callingUid, String callingPackage) {
1071 // must be *either* PendingIntent or AlarmReceiver, but not both
1072 if ((operation == null && directReceiver == null)
1073 || (operation != null && directReceiver != null)) {
1074 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1075 // NB: previous releases failed silently here, so we are continuing to do the same
1076 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 return;
1078 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001079
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001080 // Sanity check the window length. This will catch people mistakenly
1081 // trying to pass an end-of-window timestamp rather than a duration.
1082 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1083 Slog.w(TAG, "Window length " + windowLength
1084 + "ms suspiciously long; limiting to 1 hour");
1085 windowLength = AlarmManager.INTERVAL_HOUR;
1086 }
1087
Christopher Tate498c6cb2014-11-17 16:09:27 -08001088 // Sanity check the recurrence interval. This will catch people who supply
1089 // seconds when the API expects milliseconds.
Dianne Hackborna750a632015-06-16 17:18:23 -07001090 final long minInterval = mConstants.MIN_INTERVAL;
1091 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001092 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001093 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001094 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001095 interval = minInterval;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001096 }
1097
Christopher Tatee0a22b32013-07-11 14:43:13 -07001098 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1099 throw new IllegalArgumentException("Invalid alarm type " + type);
1100 }
1101
Christopher Tate5f221e82013-07-30 17:13:15 -07001102 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001103 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001104 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001105 + " pid=" + what);
1106 triggerAtTime = 0;
1107 }
1108
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001109 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001110 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1111 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001112 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001113 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1114
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001115 final long maxElapsed;
1116 if (windowLength == AlarmManager.WINDOW_EXACT) {
1117 maxElapsed = triggerElapsed;
1118 } else if (windowLength < 0) {
1119 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001120 // Fix this window in place, so that as time approaches we don't collapse it.
1121 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001122 } else {
1123 maxElapsed = triggerElapsed + windowLength;
1124 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001127 if (DEBUG_BATCH) {
1128 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001129 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001130 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001131 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001132 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001133 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001134 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1135 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001136 }
1137 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138
Christopher Tate3e04b472013-10-21 17:51:31 -07001139 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001140 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1141 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1142 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001143 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001144 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1145 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001146 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001147 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001148 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1149 + " -- package not allowed to start");
1150 return;
1151 }
1152 } catch (RemoteException e) {
1153 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001154 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001155 setImplLocked(a, false, doValidate);
1156 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001157
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001158 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1159 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001160 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001161 // The caller has given the time they want this to happen at, however we need
1162 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001163 // bring us out of idle at an earlier time.
1164 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001165 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001166 }
1167 // Add fuzz to make the alarm go off some time before the actual desired time.
1168 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001169 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001170 if (fuzz > 0) {
1171 if (mRandom == null) {
1172 mRandom = new Random();
1173 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001174 final int delta = mRandom.nextInt(fuzz);
1175 a.whenElapsed -= delta;
1176 if (false) {
1177 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1178 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1179 Slog.d(TAG, "Applied fuzz: " + fuzz);
1180 Slog.d(TAG, "Final delta: " + delta);
1181 Slog.d(TAG, "Final when: " + a.whenElapsed);
1182 }
1183 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001184 }
1185
1186 } else if (mPendingIdleUntil != null) {
1187 // We currently have an idle until alarm scheduled; if the new alarm has
1188 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001189 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1190 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1191 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001192 == 0) {
1193 mPendingWhileIdleAlarms.add(a);
1194 return;
1195 }
1196 }
1197
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001198 if (RECORD_DEVICE_IDLE_ALARMS) {
1199 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1200 IdleDispatchEntry ent = new IdleDispatchEntry();
1201 ent.uid = a.uid;
1202 ent.pkg = a.operation.getCreatorPackage();
1203 ent.tag = a.operation.getTag("");
1204 ent.op = "SET";
1205 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1206 ent.argRealtime = a.whenElapsed;
1207 mAllowWhileIdleDispatches.add(ent);
1208 }
1209 }
1210
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001211 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
1212 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -07001213 if (whichBatch < 0) {
1214 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001215 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216 } else {
Christopher Tate385e4982013-07-23 18:22:29 -07001217 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001218 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001219 // The start time of this batch advanced, so batch ordering may
1220 // have just been broken. Move it to where it now belongs.
1221 mAlarmBatches.remove(whichBatch);
1222 addBatchLocked(mAlarmBatches, batch);
1223 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001224 }
1225
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001226 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001227 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001228 }
1229
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001230 boolean needRebatch = false;
1231
1232 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001233 if (RECORD_DEVICE_IDLE_ALARMS) {
1234 if (mPendingIdleUntil == null) {
1235 IdleDispatchEntry ent = new IdleDispatchEntry();
1236 ent.uid = 0;
1237 ent.pkg = "START IDLE";
1238 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1239 mAllowWhileIdleDispatches.add(ent);
1240 }
1241 }
Makoto Onuki4274a6d2017-04-21 12:21:25 -07001242 if ((mPendingIdleUntil != a) && (mPendingIdleUntil != null)) {
1243 Slog.wtfStack(TAG, "setImplLocked: idle until changed from " + mPendingIdleUntil
1244 + " to " + a);
1245 }
1246
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001247 mPendingIdleUntil = a;
Dianne Hackborna750a632015-06-16 17:18:23 -07001248 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001249 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001250 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1251 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1252 mNextWakeFromIdle = a;
1253 // If this wake from idle is earlier than whatever was previously scheduled,
1254 // and we are currently idling, then we need to rebatch alarms in case the idle
1255 // until time needs to be updated.
1256 if (mPendingIdleUntil != null) {
1257 needRebatch = true;
1258 }
1259 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001260 }
1261
1262 if (!rebatching) {
1263 if (DEBUG_VALIDATE) {
1264 if (doValidate && !validateConsistencyLocked()) {
1265 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1266 + " when(hex)=" + Long.toHexString(a.when)
1267 + " whenElapsed=" + a.whenElapsed
1268 + " maxWhenElapsed=" + a.maxWhenElapsed
1269 + " interval=" + a.repeatInterval + " op=" + a.operation
1270 + " flags=0x" + Integer.toHexString(a.flags));
1271 rebatchAllAlarmsLocked(false);
1272 needRebatch = false;
1273 }
1274 }
1275
1276 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001277 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001278 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001279
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001280 rescheduleKernelAlarmsLocked();
1281 updateNextAlarmClockLocked();
1282 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001283 }
1284
Adam Lesinski182f73f2013-12-05 16:48:06 -08001285 private final IBinder mService = new IAlarmManager.Stub() {
1286 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001287 public void set(String callingPackage,
1288 int type, long triggerAtTime, long windowLength, long interval, int flags,
1289 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1290 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001291 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001292
1293 // make sure the caller is not lying about which package should be blamed for
1294 // wakelock time spent in alarm delivery
1295 mAppOps.checkPackage(callingUid, callingPackage);
1296
1297 // Repeating alarms must use PendingIntent, not direct listener
1298 if (interval != 0) {
1299 if (directReceiver != null) {
1300 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1301 }
1302 }
1303
Adam Lesinski182f73f2013-12-05 16:48:06 -08001304 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001305 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001306 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001307 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001308 }
1309
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001310 // No incoming callers can request either WAKE_FROM_IDLE or
1311 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1312 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1313 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1314
1315 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1316 // manager when to come out of idle mode, which is only for DeviceIdleController.
1317 if (callingUid != Process.SYSTEM_UID) {
1318 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1319 }
1320
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001321 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001322 if (windowLength == AlarmManager.WINDOW_EXACT) {
1323 flags |= AlarmManager.FLAG_STANDALONE;
1324 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001325
1326 // If this alarm is for an alarm clock, then it must be standalone and we will
1327 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001328 if (alarmClock != null) {
1329 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001330
1331 // If the caller is a core system component or on the user's whitelist, and not calling
1332 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1333 // This means we will allow these alarms to go off as normal even while idle, with no
1334 // timing restrictions.
1335 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
1336 || Arrays.binarySearch(mDeviceIdleUserWhitelist,
1337 UserHandle.getAppId(callingUid)) >= 0)) {
1338 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1339 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001340 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001341
Christopher Tate14a7bb02015-10-01 10:24:31 -07001342 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1343 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001344 }
Christopher Tate89779822012-08-31 14:40:03 -07001345
Adam Lesinski182f73f2013-12-05 16:48:06 -08001346 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001347 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001348 getContext().enforceCallingOrSelfPermission(
1349 "android.permission.SET_TIME",
1350 "setTime");
1351
Greg Hackmann0cab8962014-02-21 16:35:52 -08001352 if (mNativeData == 0) {
1353 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1354 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001355 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001356
1357 synchronized (mLock) {
1358 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001361
1362 @Override
1363 public void setTimeZone(String tz) {
1364 getContext().enforceCallingOrSelfPermission(
1365 "android.permission.SET_TIME_ZONE",
1366 "setTimeZone");
1367
1368 final long oldId = Binder.clearCallingIdentity();
1369 try {
1370 setTimeZoneImpl(tz);
1371 } finally {
1372 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 }
1374 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001375
Adam Lesinski182f73f2013-12-05 16:48:06 -08001376 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001377 public void remove(PendingIntent operation, IAlarmListener listener) {
1378 if (operation == null && listener == null) {
1379 Slog.w(TAG, "remove() with no intent or listener");
1380 return;
1381 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001382
Christopher Tate14a7bb02015-10-01 10:24:31 -07001383 synchronized (mLock) {
1384 removeLocked(operation, listener);
1385 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001387
Adam Lesinski182f73f2013-12-05 16:48:06 -08001388 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001389 public long getNextWakeFromIdleTime() {
1390 return getNextWakeFromIdleTimeImpl();
1391 }
1392
1393 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001394 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001395 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1396 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1397 "getNextAlarmClock", null);
1398
1399 return getNextAlarmClockImpl(userId);
1400 }
1401
1402 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001403 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06001404 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001405 dumpImpl(pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001406 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001407 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001408
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001409 public final class LocalService {
1410 public void setDeviceIdleUserWhitelist(int[] appids) {
1411 setDeviceIdleUserWhitelistImpl(appids);
1412 }
1413 }
1414
Adam Lesinski182f73f2013-12-05 16:48:06 -08001415 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 synchronized (mLock) {
1417 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001418 mConstants.dump(pw);
1419 pw.println();
1420
Christopher Tatee0a22b32013-07-11 14:43:13 -07001421 final long nowRTC = System.currentTimeMillis();
1422 final long nowELAPSED = SystemClock.elapsedRealtime();
1423 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1424
Dianne Hackborna750a632015-06-16 17:18:23 -07001425 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001426 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001427 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001428 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001429 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001430 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001431 pw.print(" mLastTimeChangeRealtime=");
Dianne Hackbornc3527222015-05-13 14:03:20 -07001432 TimeUtils.formatDuration(mLastTimeChangeRealtime, pw);
1433 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001434 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001435 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001436 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1437 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001438 pw.print(" Max wakeup delay: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001439 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1440 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001441 pw.print(" Time since last dispatch: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001442 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1443 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001444 pw.print(" Next non-wakeup delivery time: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001445 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1446 pw.println();
1447 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001448
1449 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1450 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001451 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001452 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001453 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001454 pw.print(" Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001455 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001456 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
1457 pw.print(" set at "); TimeUtils.formatDuration(mLastWakeupSet, nowELAPSED, pw);
1458 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001459 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001460 pw.println(" mDeviceIdleUserWhitelist=" + Arrays.toString(mDeviceIdleUserWhitelist));
Christopher Tatee0a22b32013-07-11 14:43:13 -07001461
John Spurlock604a5ee2015-06-01 12:27:22 -04001462 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001463 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001464 final TreeSet<Integer> users = new TreeSet<>();
1465 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1466 users.add(mNextAlarmClockForUser.keyAt(i));
1467 }
1468 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1469 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1470 }
1471 for (int user : users) {
1472 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1473 final long time = next != null ? next.getTriggerTime() : 0;
1474 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001475 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001476 pw.print(" pendingSend:"); pw.print(pendingSend);
1477 pw.print(" time:"); pw.print(time);
1478 if (time > 0) {
1479 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1480 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1481 }
1482 pw.println();
1483 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001484 if (mAlarmBatches.size() > 0) {
1485 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001486 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001487 pw.println(mAlarmBatches.size());
1488 for (Batch b : mAlarmBatches) {
1489 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001490 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001491 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001493 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001494 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001495 pw.println(" Idle mode state:");
1496 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001497 if (mPendingIdleUntil != null) {
1498 pw.println(mPendingIdleUntil);
Dianne Hackbornf3831292015-10-15 14:51:06 -07001499 mPendingIdleUntil.dump(pw, " ", nowRTC, nowELAPSED, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001500 } else {
1501 pw.println("null");
1502 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001503 pw.println(" Pending alarms:");
1504 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001505 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001506 if (mNextWakeFromIdle != null) {
1507 pw.println();
1508 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
1509 mNextWakeFromIdle.dump(pw, " ", nowRTC, nowELAPSED, sdf);
1510 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001511
1512 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001513 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001514 if (mPendingNonWakeupAlarms.size() > 0) {
1515 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001516 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001517 } else {
1518 pw.println("(none)");
1519 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001520 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001521 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1522 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001523 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001524 pw.print(", max non-interactive time: ");
1525 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1526 pw.println();
1527
1528 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001529 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001530 pw.println();
1531
Christopher Tate7f2a0352015-12-08 10:24:33 -08001532 if (mInFlight.size() > 0) {
1533 pw.println("Outstanding deliveries:");
1534 for (int i = 0; i < mInFlight.size(); i++) {
1535 pw.print(" #"); pw.print(i); pw.print(": ");
1536 pw.println(mInFlight.get(i));
1537 }
1538 pw.println();
1539 }
1540
Dianne Hackborna750a632015-06-16 17:18:23 -07001541 pw.print(" mAllowWhileIdleMinTime=");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001542 TimeUtils.formatDuration(mAllowWhileIdleMinTime, pw);
1543 pw.println();
1544 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001545 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001546 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
1547 pw.print(" UID ");
1548 UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
1549 pw.print(": ");
1550 TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i),
1551 nowELAPSED, pw);
1552 pw.println();
1553 }
1554 }
1555 pw.println();
1556
Dianne Hackborn81038902012-11-26 17:04:09 -08001557 if (mLog.dump(pw, " Recent problems", " ")) {
1558 pw.println();
1559 }
1560
1561 final FilterStats[] topFilters = new FilterStats[10];
1562 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1563 @Override
1564 public int compare(FilterStats lhs, FilterStats rhs) {
1565 if (lhs.aggregateTime < rhs.aggregateTime) {
1566 return 1;
1567 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1568 return -1;
1569 }
1570 return 0;
1571 }
1572 };
1573 int len = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001574 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1575 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1576 for (int ip=0; ip<uidStats.size(); ip++) {
1577 BroadcastStats bs = uidStats.valueAt(ip);
1578 for (int is=0; is<bs.filterStats.size(); is++) {
1579 FilterStats fs = bs.filterStats.valueAt(is);
1580 int pos = len > 0
1581 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1582 if (pos < 0) {
1583 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001584 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001585 if (pos < topFilters.length) {
1586 int copylen = topFilters.length - pos - 1;
1587 if (copylen > 0) {
1588 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1589 }
1590 topFilters[pos] = fs;
1591 if (len < topFilters.length) {
1592 len++;
1593 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001594 }
1595 }
1596 }
1597 }
1598 if (len > 0) {
1599 pw.println(" Top Alarms:");
1600 for (int i=0; i<len; i++) {
1601 FilterStats fs = topFilters[i];
1602 pw.print(" ");
1603 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1604 TimeUtils.formatDuration(fs.aggregateTime, pw);
1605 pw.print(" running, "); pw.print(fs.numWakeup);
1606 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001607 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1608 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001609 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001610 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001611 pw.println();
1612 }
1613 }
1614
1615 pw.println(" ");
1616 pw.println(" Alarm Stats:");
1617 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001618 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1619 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1620 for (int ip=0; ip<uidStats.size(); ip++) {
1621 BroadcastStats bs = uidStats.valueAt(ip);
1622 pw.print(" ");
1623 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1624 UserHandle.formatUid(pw, bs.mUid);
1625 pw.print(":");
1626 pw.print(bs.mPackageName);
1627 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1628 pw.print(" running, "); pw.print(bs.numWakeup);
1629 pw.println(" wakeups:");
1630 tmpFilters.clear();
1631 for (int is=0; is<bs.filterStats.size(); is++) {
1632 tmpFilters.add(bs.filterStats.valueAt(is));
1633 }
1634 Collections.sort(tmpFilters, comparator);
1635 for (int i=0; i<tmpFilters.size(); i++) {
1636 FilterStats fs = tmpFilters.get(i);
1637 pw.print(" ");
1638 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1639 TimeUtils.formatDuration(fs.aggregateTime, pw);
1640 pw.print(" "); pw.print(fs.numWakeup);
1641 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001642 pw.print(" alarms, last ");
1643 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1644 pw.println(":");
1645 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001646 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001647 pw.println();
1648 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 }
1650 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001651
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001652 if (RECORD_DEVICE_IDLE_ALARMS) {
1653 pw.println();
1654 pw.println(" Allow while idle dispatches:");
1655 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
1656 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
1657 pw.print(" ");
1658 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
1659 pw.print(": ");
1660 UserHandle.formatUid(pw, ent.uid);
1661 pw.print(":");
1662 pw.println(ent.pkg);
1663 if (ent.op != null) {
1664 pw.print(" ");
1665 pw.print(ent.op);
1666 pw.print(" / ");
1667 pw.print(ent.tag);
1668 if (ent.argRealtime != 0) {
1669 pw.print(" (");
1670 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
1671 pw.print(")");
1672 }
1673 pw.println();
1674 }
1675 }
1676 }
1677
Christopher Tate18a75f12013-07-01 18:18:59 -07001678 if (WAKEUP_STATS) {
1679 pw.println();
1680 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001681 long last = -1;
1682 for (WakeupEvent event : mRecentWakeups) {
1683 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1684 pw.print('|');
1685 if (last < 0) {
1686 pw.print('0');
1687 } else {
1688 pw.print(event.when - last);
1689 }
1690 last = event.when;
1691 pw.print('|'); pw.print(event.uid);
1692 pw.print('|'); pw.print(event.action);
1693 pw.println();
1694 }
1695 pw.println();
1696 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 }
1698 }
1699
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001700 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001701 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
1702 PrintWriter pw = new PrintWriter(bs);
1703 final long nowRTC = System.currentTimeMillis();
1704 final long nowELAPSED = SystemClock.elapsedRealtime();
1705 final int NZ = mAlarmBatches.size();
1706 for (int iz = 0; iz < NZ; iz++) {
1707 Batch bz = mAlarmBatches.get(iz);
1708 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001709 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001710 pw.flush();
1711 Slog.v(TAG, bs.toString());
1712 bs.reset();
1713 }
1714 }
1715
1716 private boolean validateConsistencyLocked() {
1717 if (DEBUG_VALIDATE) {
1718 long lastTime = Long.MIN_VALUE;
1719 final int N = mAlarmBatches.size();
1720 for (int i = 0; i < N; i++) {
1721 Batch b = mAlarmBatches.get(i);
1722 if (b.start >= lastTime) {
1723 // duplicate start times are okay because of standalone batches
1724 lastTime = b.start;
1725 } else {
1726 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001727 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1728 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001729 return false;
1730 }
1731 }
1732 }
1733 return true;
1734 }
1735
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001736 private Batch findFirstWakeupBatchLocked() {
1737 final int N = mAlarmBatches.size();
1738 for (int i = 0; i < N; i++) {
1739 Batch b = mAlarmBatches.get(i);
1740 if (b.hasWakeups()) {
1741 return b;
1742 }
1743 }
1744 return null;
1745 }
1746
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001747 long getNextWakeFromIdleTimeImpl() {
1748 synchronized (mLock) {
1749 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
1750 }
1751 }
1752
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001753 void setDeviceIdleUserWhitelistImpl(int[] appids) {
1754 synchronized (mLock) {
1755 mDeviceIdleUserWhitelist = appids;
1756 }
1757 }
1758
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001759 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001760 synchronized (mLock) {
1761 return mNextAlarmClockForUser.get(userId);
1762 }
1763 }
1764
1765 /**
1766 * Recomputes the next alarm clock for all users.
1767 */
1768 private void updateNextAlarmClockLocked() {
1769 if (!mNextAlarmClockMayChange) {
1770 return;
1771 }
1772 mNextAlarmClockMayChange = false;
1773
Jose Lima235510e2014-08-13 12:50:01 -07001774 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001775 nextForUser.clear();
1776
1777 final int N = mAlarmBatches.size();
1778 for (int i = 0; i < N; i++) {
1779 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
1780 final int M = alarms.size();
1781
1782 for (int j = 0; j < M; j++) {
1783 Alarm a = alarms.get(j);
1784 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001785 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07001786 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001787
1788 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07001789 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001790 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02001791 " for user " + userId);
1792 }
1793
1794 // Alarms and batches are sorted by time, no need to compare times here.
1795 if (nextForUser.get(userId) == null) {
1796 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07001797 } else if (a.alarmClock.equals(current)
1798 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
1799 // same/earlier time and it's the one we cited before, so stick with it
1800 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001801 }
1802 }
1803 }
1804 }
1805
1806 // Update mNextAlarmForUser with new values.
1807 final int NN = nextForUser.size();
1808 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07001809 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001810 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001811 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001812 if (!newAlarm.equals(currentAlarm)) {
1813 updateNextAlarmInfoForUserLocked(userId, newAlarm);
1814 }
1815 }
1816
1817 // Remove users without any alarm clocks scheduled.
1818 final int NNN = mNextAlarmClockForUser.size();
1819 for (int i = NNN - 1; i >= 0; i--) {
1820 int userId = mNextAlarmClockForUser.keyAt(i);
1821 if (nextForUser.get(userId) == null) {
1822 updateNextAlarmInfoForUserLocked(userId, null);
1823 }
1824 }
1825 }
1826
Jose Lima235510e2014-08-13 12:50:01 -07001827 private void updateNextAlarmInfoForUserLocked(int userId,
1828 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001829 if (alarmClock != null) {
1830 if (DEBUG_ALARM_CLOCK) {
1831 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001832 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02001833 }
1834 mNextAlarmClockForUser.put(userId, alarmClock);
1835 } else {
1836 if (DEBUG_ALARM_CLOCK) {
1837 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
1838 }
1839 mNextAlarmClockForUser.remove(userId);
1840 }
1841
1842 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
1843 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1844 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1845 }
1846
1847 /**
1848 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
1849 * for which alarm clocks have changed since the last call to this.
1850 *
1851 * Do not call with a lock held. Only call from mHandler's thread.
1852 *
1853 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
1854 */
1855 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07001856 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001857 pendingUsers.clear();
1858
1859 synchronized (mLock) {
1860 final int N = mPendingSendNextAlarmClockChangedForUser.size();
1861 for (int i = 0; i < N; i++) {
1862 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
1863 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
1864 }
1865 mPendingSendNextAlarmClockChangedForUser.clear();
1866 }
1867
1868 final int N = pendingUsers.size();
1869 for (int i = 0; i < N; i++) {
1870 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001871 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001872 Settings.System.putStringForUser(getContext().getContentResolver(),
1873 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01001874 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02001875 userId);
1876
1877 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
1878 new UserHandle(userId));
1879 }
1880 }
1881
1882 /**
1883 * Formats an alarm like platform/packages/apps/DeskClock used to.
1884 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01001885 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
1886 int userId) {
1887 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02001888 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
1889 return (info == null) ? "" :
1890 DateFormat.format(pattern, info.getTriggerTime()).toString();
1891 }
1892
Adam Lesinski182f73f2013-12-05 16:48:06 -08001893 void rescheduleKernelAlarmsLocked() {
1894 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
1895 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001896 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001897 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001898 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001899 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07001900 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001901 mNextWakeup = firstWakeup.start;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001902 mLastWakeupSet = SystemClock.elapsedRealtime();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001903 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001904 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001905 if (firstBatch != firstWakeup) {
1906 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001907 }
1908 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001909 if (mPendingNonWakeupAlarms.size() > 0) {
1910 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
1911 nextNonWakeup = mNextNonWakeupDeliveryTime;
1912 }
1913 }
Prashant Malani753e9e02015-06-10 17:43:49 -07001914 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001915 mNextNonWakeup = nextNonWakeup;
1916 setLocked(ELAPSED_REALTIME, nextNonWakeup);
1917 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001918 }
1919
Christopher Tate14a7bb02015-10-01 10:24:31 -07001920 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001921 boolean didRemove = false;
1922 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1923 Batch b = mAlarmBatches.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -07001924 didRemove |= b.remove(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001925 if (b.size() == 0) {
1926 mAlarmBatches.remove(i);
1927 }
1928 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001929 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001930 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001931 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1932 mPendingWhileIdleAlarms.remove(i);
1933 }
1934 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001935
1936 if (didRemove) {
1937 if (DEBUG_BATCH) {
1938 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
1939 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001940 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001941 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001942 mPendingIdleUntil = null;
1943 restorePending = true;
1944 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001945 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001946 mNextWakeFromIdle = null;
1947 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001948 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001949 if (restorePending) {
1950 restorePendingWhileIdleAlarmsLocked();
1951 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001952 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001953 }
1954 }
1955
1956 void removeLocked(String packageName) {
1957 boolean didRemove = false;
1958 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1959 Batch b = mAlarmBatches.get(i);
1960 didRemove |= b.remove(packageName);
1961 if (b.size() == 0) {
1962 mAlarmBatches.remove(i);
1963 }
1964 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001965 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001966 final Alarm a = mPendingWhileIdleAlarms.get(i);
1967 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001968 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1969 mPendingWhileIdleAlarms.remove(i);
1970 }
1971 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001972
1973 if (didRemove) {
1974 if (DEBUG_BATCH) {
1975 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1976 }
1977 rebatchAllAlarmsLocked(true);
1978 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001979 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001980 }
1981 }
1982
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001983 void removeForStoppedLocked(int uid) {
1984 boolean didRemove = false;
1985 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1986 Batch b = mAlarmBatches.get(i);
1987 didRemove |= b.removeForStopped(uid);
1988 if (b.size() == 0) {
1989 mAlarmBatches.remove(i);
1990 }
1991 }
1992 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1993 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08001994 if (a.uid == uid) {
1995 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1996 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001997 }
1998 }
1999
2000 if (didRemove) {
2001 if (DEBUG_BATCH) {
2002 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2003 }
2004 rebatchAllAlarmsLocked(true);
2005 rescheduleKernelAlarmsLocked();
2006 updateNextAlarmClockLocked();
2007 }
2008 }
2009
Adam Lesinski182f73f2013-12-05 16:48:06 -08002010 void removeUserLocked(int userHandle) {
2011 boolean didRemove = false;
2012 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2013 Batch b = mAlarmBatches.get(i);
2014 didRemove |= b.remove(userHandle);
2015 if (b.size() == 0) {
2016 mAlarmBatches.remove(i);
2017 }
2018 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002019 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002020 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002021 == userHandle) {
2022 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2023 mPendingWhileIdleAlarms.remove(i);
2024 }
2025 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002026 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
2027 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
2028 mLastAllowWhileIdleDispatch.removeAt(i);
2029 }
2030 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002031
2032 if (didRemove) {
2033 if (DEBUG_BATCH) {
2034 Slog.v(TAG, "remove(user) changed bounds; rebatching");
2035 }
2036 rebatchAllAlarmsLocked(true);
2037 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002038 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002039 }
2040 }
2041
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002042 void interactiveStateChangedLocked(boolean interactive) {
2043 if (mInteractive != interactive) {
2044 mInteractive = interactive;
2045 final long nowELAPSED = SystemClock.elapsedRealtime();
2046 if (interactive) {
2047 if (mPendingNonWakeupAlarms.size() > 0) {
2048 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2049 mTotalDelayTime += thisDelayTime;
2050 if (mMaxDelayTime < thisDelayTime) {
2051 mMaxDelayTime = thisDelayTime;
2052 }
2053 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2054 mPendingNonWakeupAlarms.clear();
2055 }
2056 if (mNonInteractiveStartTime > 0) {
2057 long dur = nowELAPSED - mNonInteractiveStartTime;
2058 if (dur > mNonInteractiveTime) {
2059 mNonInteractiveTime = dur;
2060 }
2061 }
2062 } else {
2063 mNonInteractiveStartTime = nowELAPSED;
2064 }
2065 }
2066 }
2067
Adam Lesinski182f73f2013-12-05 16:48:06 -08002068 boolean lookForPackageLocked(String packageName) {
2069 for (int i = 0; i < mAlarmBatches.size(); i++) {
2070 Batch b = mAlarmBatches.get(i);
2071 if (b.hasPackage(packageName)) {
2072 return true;
2073 }
2074 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002075 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002076 final Alarm a = mPendingWhileIdleAlarms.get(i);
2077 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002078 return true;
2079 }
2080 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002081 return false;
2082 }
2083
2084 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002085 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002086 // The kernel never triggers alarms with negative wakeup times
2087 // so we ensure they are positive.
2088 long alarmSeconds, alarmNanoseconds;
2089 if (when < 0) {
2090 alarmSeconds = 0;
2091 alarmNanoseconds = 0;
2092 } else {
2093 alarmSeconds = when / 1000;
2094 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2095 }
2096
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002097 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002098 } else {
2099 Message msg = Message.obtain();
2100 msg.what = ALARM_EVENT;
2101
2102 mHandler.removeMessages(ALARM_EVENT);
2103 mHandler.sendMessageAtTime(msg, when);
2104 }
2105 }
2106
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002107 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002108 String prefix, String label, long nowRTC, long nowELAPSED, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002109 for (int i=list.size()-1; i>=0; i--) {
2110 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002111 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2112 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002113 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002114 }
2115 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002116
2117 private static final String labelForType(int type) {
2118 switch (type) {
2119 case RTC: return "RTC";
2120 case RTC_WAKEUP : return "RTC_WAKEUP";
2121 case ELAPSED_REALTIME : return "ELAPSED";
2122 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
2123 default:
2124 break;
2125 }
2126 return "--unknown--";
2127 }
2128
2129 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002130 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002131 for (int i=list.size()-1; i>=0; i--) {
2132 Alarm a = list.get(i);
2133 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002134 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2135 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002136 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002137 }
2138 }
2139
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002140 private native long init();
2141 private native void close(long nativeData);
2142 private native void set(long nativeData, int type, long seconds, long nanoseconds);
2143 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08002144 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002145 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002146
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002147 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002148 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002149 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002150 // batches are temporally sorted, so we need only pull from the
2151 // start of the list until we either empty it or hit a batch
2152 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07002153 while (mAlarmBatches.size() > 0) {
2154 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002155 if (batch.start > nowELAPSED) {
2156 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002157 break;
2158 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002159
Christopher Tatee0a22b32013-07-11 14:43:13 -07002160 // We will (re)schedule some alarms now; don't let that interfere
2161 // with delivery of this current batch
2162 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002163
Christopher Tatee0a22b32013-07-11 14:43:13 -07002164 final int N = batch.size();
2165 for (int i = 0; i < N; i++) {
2166 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002167
2168 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
2169 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
2170 // schedule such alarms.
2171 long lastTime = mLastAllowWhileIdleDispatch.get(alarm.uid, 0);
2172 long minTime = lastTime + mAllowWhileIdleMinTime;
2173 if (nowELAPSED < minTime) {
2174 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
2175 // alarm went off for this app. Reschedule the alarm to be in the
2176 // correct time period.
2177 alarm.whenElapsed = minTime;
2178 if (alarm.maxWhenElapsed < minTime) {
2179 alarm.maxWhenElapsed = minTime;
2180 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002181 if (RECORD_DEVICE_IDLE_ALARMS) {
2182 IdleDispatchEntry ent = new IdleDispatchEntry();
2183 ent.uid = alarm.uid;
2184 ent.pkg = alarm.operation.getCreatorPackage();
2185 ent.tag = alarm.operation.getTag("");
2186 ent.op = "RESCHEDULE";
2187 ent.elapsedRealtime = nowELAPSED;
2188 ent.argRealtime = lastTime;
2189 mAllowWhileIdleDispatches.add(ent);
2190 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002191 setImplLocked(alarm, true, false);
2192 continue;
2193 }
2194 }
2195
Christopher Tatee0a22b32013-07-11 14:43:13 -07002196 alarm.count = 1;
2197 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002198 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
2199 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002200 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002201 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002202 if (mPendingIdleUntil == alarm) {
2203 mPendingIdleUntil = null;
2204 rebatchAllAlarmsLocked(false);
2205 restorePendingWhileIdleAlarmsLocked();
2206 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002207 if (mNextWakeFromIdle == alarm) {
2208 mNextWakeFromIdle = null;
2209 rebatchAllAlarmsLocked(false);
2210 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002211
2212 // Recurring alarms may have passed several alarm intervals while the
2213 // phone was asleep or off, so pass a trigger count when sending them.
2214 if (alarm.repeatInterval > 0) {
2215 // this adjustment will be zero if we're late by
2216 // less than one full repeat interval
2217 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
2218
2219 // Also schedule its next recurrence
2220 final long delta = alarm.count * alarm.repeatInterval;
2221 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07002222 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07002223 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07002224 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
2225 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08002226 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002227
Christopher Tate864d42e2014-12-02 11:48:53 -08002228 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002229 hasWakeup = true;
2230 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002231
2232 // We removed an alarm clock. Let the caller recompute the next alarm clock.
2233 if (alarm.alarmClock != null) {
2234 mNextAlarmClockMayChange = true;
2235 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07002236 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002237 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002238
Christopher Tate1590f1e2014-10-02 17:27:57 -07002239 // This is a new alarm delivery set; bump the sequence number to indicate that
2240 // all apps' alarm delivery classes should be recalculated.
2241 mCurrentSeq++;
2242 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002243 Collections.sort(triggerList, mAlarmDispatchComparator);
2244
2245 if (localLOGV) {
2246 for (int i=0; i<triggerList.size(); i++) {
2247 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
2248 }
2249 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002250
2251 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002252 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002254 /**
2255 * This Comparator sorts Alarms into increasing time order.
2256 */
2257 public static class IncreasingTimeOrder implements Comparator<Alarm> {
2258 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09002259 long when1 = a1.whenElapsed;
2260 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002261 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002262 return 1;
2263 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002264 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002265 return -1;
2266 }
2267 return 0;
2268 }
2269 }
2270
2271 private static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002272 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002273 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002274 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002275 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002276 public final IAlarmListener listener;
2277 public final String listenerTag;
2278 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002279 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002280 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002281 public final AlarmManager.AlarmClockInfo alarmClock;
2282 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002283 public final int creatorUid;
2284 public final String packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002285 public int count;
2286 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07002287 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002288 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002289 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002290 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07002291 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002292
Christopher Tate3e04b472013-10-21 17:51:31 -07002293 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002294 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
2295 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
2296 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002297 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002298 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002299 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
2300 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002301 when = _when;
2302 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07002303 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002304 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002305 repeatInterval = _interval;
2306 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002307 listener = _rec;
2308 listenerTag = _listenerTag;
2309 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07002310 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002311 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002312 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002313 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002314 packageName = _pkgName;
2315
2316 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002317 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002318
Christopher Tate14a7bb02015-10-01 10:24:31 -07002319 public static String makeTag(PendingIntent pi, String tag, int type) {
2320 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
2321 ? "*walarm*:" : "*alarm*:";
2322 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
2323 }
2324
2325 public WakeupEvent makeWakeupEvent(long nowRTC) {
2326 return new WakeupEvent(nowRTC, creatorUid,
2327 (operation != null)
2328 ? operation.getIntent().getAction()
2329 : ("<listener>:" + listenerTag));
2330 }
2331
2332 // Returns true if either matches
2333 public boolean matches(PendingIntent pi, IAlarmListener rec) {
2334 return (operation != null)
2335 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09002336 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07002337 }
2338
2339 public boolean matches(String packageName) {
2340 return (operation != null)
2341 ? packageName.equals(operation.getTargetPackage())
2342 : packageName.equals(this.packageName);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002343 }
2344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002345 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002346 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002347 StringBuilder sb = new StringBuilder(128);
2348 sb.append("Alarm{");
2349 sb.append(Integer.toHexString(System.identityHashCode(this)));
2350 sb.append(" type ");
2351 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002352 sb.append(" when ");
2353 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002354 sb.append(" ");
Christopher Tate14a7bb02015-10-01 10:24:31 -07002355 if (operation != null) {
2356 sb.append(operation.getTargetPackage());
2357 } else {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002358 sb.append(packageName);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002359 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002360 sb.append('}');
2361 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002362 }
2363
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002364 public void dump(PrintWriter pw, String prefix, long nowRTC, long nowELAPSED,
2365 SimpleDateFormat sdf) {
2366 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002367 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002368 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002369 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
2370 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002371 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002372 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002373 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002374 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002375 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002376 }
2377 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002378 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002379 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002380 pw.print(" count="); pw.print(count);
2381 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002382 if (alarmClock != null) {
2383 pw.print(prefix); pw.println("Alarm clock:");
2384 pw.print(prefix); pw.print(" triggerTime=");
2385 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
2386 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
2387 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002388 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002389 if (listener != null) {
2390 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
2391 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002392 }
2393 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002394
Christopher Tatee0a22b32013-07-11 14:43:13 -07002395 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
2396 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002397 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
2398 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002399 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07002400 break;
2401 }
2402
Christopher Tatee0a22b32013-07-11 14:43:13 -07002403 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002404 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
2405 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002406 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07002407 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002408 }
2409 }
2410
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002411 long currentNonWakeupFuzzLocked(long nowELAPSED) {
2412 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
2413 if (timeSinceOn < 5*60*1000) {
2414 // If the screen has been off for 5 minutes, only delay by at most two minutes.
2415 return 2*60*1000;
2416 } else if (timeSinceOn < 30*60*1000) {
2417 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
2418 return 15*60*1000;
2419 } else {
2420 // Otherwise, we will delay by at most an hour.
2421 return 60*60*1000;
2422 }
2423 }
2424
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002425 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002426 if (duration < 15*60*1000) {
2427 // If the duration until the time is less than 15 minutes, the maximum fuzz
2428 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002429 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002430 } else if (duration < 90*60*1000) {
2431 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
2432 return 15*60*1000;
2433 } else {
2434 // Otherwise, we will fuzz by at most half an hour.
2435 return 30*60*1000;
2436 }
2437 }
2438
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002439 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
2440 if (mInteractive) {
2441 return false;
2442 }
2443 if (mLastAlarmDeliveryTime <= 0) {
2444 return false;
2445 }
minho.choo649acab2014-12-12 16:13:55 +09002446 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002447 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
2448 // and the next delivery time is in the past, then just deliver them all. This
2449 // avoids bugs where we get stuck in a loop trying to poll for alarms.
2450 return false;
2451 }
2452 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
2453 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
2454 }
2455
2456 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
2457 mLastAlarmDeliveryTime = nowELAPSED;
2458 for (int i=0; i<triggerList.size(); i++) {
2459 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07002460 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002461 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07002462 if (localLOGV) {
2463 Slog.v(TAG, "sending alarm " + alarm);
2464 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07002465 if (RECORD_ALARMS_IN_HISTORY) {
2466 if (alarm.workSource != null && alarm.workSource.size() > 0) {
2467 for (int wi=0; wi<alarm.workSource.size(); wi++) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002468 ActivityManager.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002469 alarm.operation, alarm.workSource.get(wi), alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002470 }
2471 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002472 ActivityManager.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002473 alarm.operation, alarm.uid, alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002474 }
2475 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002476 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002477 } catch (RuntimeException e) {
2478 Slog.w(TAG, "Failure sending alarm.", e);
2479 }
2480 }
2481 }
2482
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002483 private class AlarmThread extends Thread
2484 {
2485 public AlarmThread()
2486 {
2487 super("AlarmManager");
2488 }
2489
2490 public void run()
2491 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002492 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002494 while (true)
2495 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002496 int result = waitForAlarm(mNativeData);
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002497 mLastWakeup = SystemClock.elapsedRealtime();
Dianne Hackborn390517b2013-05-30 15:03:32 -07002498
2499 triggerList.clear();
2500
Dianne Hackbornc3527222015-05-13 14:03:20 -07002501 final long nowRTC = System.currentTimeMillis();
2502 final long nowELAPSED = SystemClock.elapsedRealtime();
2503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002504 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002505 // The kernel can give us spurious time change notifications due to
2506 // small adjustments it makes internally; we want to filter those out.
2507 final long lastTimeChangeClockTime;
2508 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07002509 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002510 lastTimeChangeClockTime = mLastTimeChangeClockTime;
2511 expectedClockTime = lastTimeChangeClockTime
2512 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07002513 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08002514 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
2515 || nowRTC > (expectedClockTime+1000)) {
2516 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07002517 // let's do it!
2518 if (DEBUG_BATCH) {
2519 Slog.v(TAG, "Time changed notification from kernel; rebatching");
2520 }
2521 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07002522 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07002523 rebatchAllAlarms();
2524 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07002525 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07002526 synchronized (mLock) {
2527 mNumTimeChanged++;
2528 mLastTimeChangeClockTime = nowRTC;
2529 mLastTimeChangeRealtime = nowELAPSED;
2530 }
2531 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
2532 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08002533 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07002534 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
2535 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07002536 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
2537
2538 // The world has changed on us, so we need to re-evaluate alarms
2539 // regardless of whether the kernel has told us one went off.
2540 result |= IS_WAKEUP_MASK;
2541 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002543
Dianne Hackbornc3527222015-05-13 14:03:20 -07002544 if (result != TIME_CHANGED_MASK) {
2545 // If this was anything besides just a time change, then figure what if
2546 // anything to do about alarms.
2547 synchronized (mLock) {
2548 if (localLOGV) Slog.v(
2549 TAG, "Checking for alarms... rtc=" + nowRTC
2550 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07002551
Dianne Hackbornc3527222015-05-13 14:03:20 -07002552 if (WAKEUP_STATS) {
2553 if ((result & IS_WAKEUP_MASK) != 0) {
2554 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
2555 int n = 0;
2556 for (WakeupEvent event : mRecentWakeups) {
2557 if (event.when > newEarliest) break;
2558 n++; // number of now-stale entries at the list head
2559 }
2560 for (int i = 0; i < n; i++) {
2561 mRecentWakeups.remove();
2562 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002563
Dianne Hackbornc3527222015-05-13 14:03:20 -07002564 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002565 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002566 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002567
2568 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2569 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
2570 // if there are no wakeup alarms and the screen is off, we can
2571 // delay what we have so far until the future.
2572 if (mPendingNonWakeupAlarms.size() == 0) {
2573 mStartCurrentDelayTime = nowELAPSED;
2574 mNextNonWakeupDeliveryTime = nowELAPSED
2575 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
2576 }
2577 mPendingNonWakeupAlarms.addAll(triggerList);
2578 mNumDelayedAlarms += triggerList.size();
2579 rescheduleKernelAlarmsLocked();
2580 updateNextAlarmClockLocked();
2581 } else {
2582 // now deliver the alarm intents; if there are pending non-wakeup
2583 // alarms, we need to merge them in to the list. note we don't
2584 // just deliver them first because we generally want non-wakeup
2585 // alarms delivered after wakeup alarms.
2586 rescheduleKernelAlarmsLocked();
2587 updateNextAlarmClockLocked();
2588 if (mPendingNonWakeupAlarms.size() > 0) {
2589 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
2590 triggerList.addAll(mPendingNonWakeupAlarms);
2591 Collections.sort(triggerList, mAlarmDispatchComparator);
2592 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2593 mTotalDelayTime += thisDelayTime;
2594 if (mMaxDelayTime < thisDelayTime) {
2595 mMaxDelayTime = thisDelayTime;
2596 }
2597 mPendingNonWakeupAlarms.clear();
2598 }
2599 deliverAlarmsLocked(triggerList, nowELAPSED);
2600 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002601 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002602
2603 } else {
2604 // Just in case -- even though no wakeup flag was set, make sure
2605 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07002606 synchronized (mLock) {
2607 rescheduleKernelAlarmsLocked();
2608 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002609 }
2610 }
2611 }
2612 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002613
David Christieebe51fc2013-07-26 13:23:29 -07002614 /**
2615 * Attribute blame for a WakeLock.
2616 * @param pi PendingIntent to attribute blame to if ws is null.
2617 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002618 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07002619 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002620 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002621 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07002622 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002623 final boolean unimportant = pi == mTimeTickSender;
2624 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002625 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002626 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002627 } else {
2628 mWakeLock.setHistoryTag(null);
2629 }
2630 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07002631 if (ws != null) {
2632 mWakeLock.setWorkSource(ws);
2633 return;
2634 }
2635
Christopher Tate14a7bb02015-10-01 10:24:31 -07002636 final int uid = (knownUid >= 0)
2637 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002638 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07002639 if (uid >= 0) {
2640 mWakeLock.setWorkSource(new WorkSource(uid));
2641 return;
2642 }
2643 } catch (Exception e) {
2644 }
2645
2646 // Something went wrong; fall back to attributing the lock to the OS
2647 mWakeLock.setWorkSource(null);
2648 }
2649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002650 private class AlarmHandler extends Handler {
2651 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002652 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
2653 public static final int LISTENER_TIMEOUT = 3;
2654 public static final int REPORT_ALARMS_ACTIVE = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002655
2656 public AlarmHandler() {
2657 }
2658
2659 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002660 switch (msg.what) {
2661 case ALARM_EVENT: {
2662 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2663 synchronized (mLock) {
2664 final long nowRTC = System.currentTimeMillis();
2665 final long nowELAPSED = SystemClock.elapsedRealtime();
2666 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2667 updateNextAlarmClockLocked();
2668 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002669
Christopher Tate14a7bb02015-10-01 10:24:31 -07002670 // now trigger the alarms without the lock held
2671 for (int i=0; i<triggerList.size(); i++) {
2672 Alarm alarm = triggerList.get(i);
2673 try {
2674 alarm.operation.send();
2675 } catch (PendingIntent.CanceledException e) {
2676 if (alarm.repeatInterval > 0) {
2677 // This IntentSender is no longer valid, but this
2678 // is a repeating alarm, so toss the hoser.
2679 removeImpl(alarm.operation);
2680 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002681 }
2682 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002683 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002684 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002685
2686 case SEND_NEXT_ALARM_CLOCK_CHANGED:
2687 sendNextAlarmClockChanged();
2688 break;
2689
2690 case LISTENER_TIMEOUT:
2691 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
2692 break;
2693
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002694 case REPORT_ALARMS_ACTIVE:
2695 if (mLocalDeviceIdleController != null) {
2696 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
2697 }
2698 break;
2699
Christopher Tate14a7bb02015-10-01 10:24:31 -07002700 default:
2701 // nope, just ignore it
2702 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002703 }
2704 }
2705 }
2706
2707 class ClockReceiver extends BroadcastReceiver {
2708 public ClockReceiver() {
2709 IntentFilter filter = new IntentFilter();
2710 filter.addAction(Intent.ACTION_TIME_TICK);
2711 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002712 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002713 }
2714
2715 @Override
2716 public void onReceive(Context context, Intent intent) {
2717 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07002718 if (DEBUG_BATCH) {
2719 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
2720 }
2721 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002722 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
2723 // Since the kernel does not keep track of DST, we need to
2724 // reset the TZ information at the beginning of each day
2725 // based off of the current Zone gmt offset + userspace tracked
2726 // daylight savings information.
2727 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02002728 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002729 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07002730 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002731 }
2732 }
2733
2734 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07002735 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09002736 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07002737
2738 // Schedule this event for the amount of time that it would take to get to
2739 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09002740 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07002741
David Christieebe51fc2013-07-26 13:23:29 -07002742 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002743 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002744 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
2745 null, Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002746 }
Christopher Tate385e4982013-07-23 18:22:29 -07002747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002748 public void scheduleDateChangedEvent() {
2749 Calendar calendar = Calendar.getInstance();
2750 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07002751 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002752 calendar.set(Calendar.MINUTE, 0);
2753 calendar.set(Calendar.SECOND, 0);
2754 calendar.set(Calendar.MILLISECOND, 0);
2755 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07002756
2757 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002758 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
2759 AlarmManager.FLAG_STANDALONE, workSource, null,
2760 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002761 }
2762 }
2763
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002764 class InteractiveStateReceiver extends BroadcastReceiver {
2765 public InteractiveStateReceiver() {
2766 IntentFilter filter = new IntentFilter();
2767 filter.addAction(Intent.ACTION_SCREEN_OFF);
2768 filter.addAction(Intent.ACTION_SCREEN_ON);
2769 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
2770 getContext().registerReceiver(this, filter);
2771 }
2772
2773 @Override
2774 public void onReceive(Context context, Intent intent) {
2775 synchronized (mLock) {
2776 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
2777 }
2778 }
2779 }
2780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002781 class UninstallReceiver extends BroadcastReceiver {
2782 public UninstallReceiver() {
2783 IntentFilter filter = new IntentFilter();
2784 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2785 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002786 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002787 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08002788 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002789 // Register for events related to sdcard installation.
2790 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08002791 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002792 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002793 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002794 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002795 }
2796
2797 @Override
2798 public void onReceive(Context context, Intent intent) {
2799 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002800 String action = intent.getAction();
2801 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002802 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
2803 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
2804 for (String packageName : pkgList) {
2805 if (lookForPackageLocked(packageName)) {
2806 setResultCode(Activity.RESULT_OK);
2807 return;
2808 }
2809 }
2810 return;
2811 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002812 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002813 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
2814 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
2815 if (userHandle >= 0) {
2816 removeUserLocked(userHandle);
2817 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002818 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
2819 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
2820 if (uid >= 0) {
2821 mLastAllowWhileIdleDispatch.delete(uid);
2822 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002823 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08002824 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
2825 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
2826 // This package is being updated; don't kill its alarms.
2827 return;
2828 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002829 Uri data = intent.getData();
2830 if (data != null) {
2831 String pkg = data.getSchemeSpecificPart();
2832 if (pkg != null) {
2833 pkgList = new String[]{pkg};
2834 }
2835 }
2836 }
2837 if (pkgList != null && (pkgList.length > 0)) {
2838 for (String pkg : pkgList) {
2839 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07002840 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002841 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
2842 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
2843 if (uidStats.remove(pkg) != null) {
2844 if (uidStats.size() <= 0) {
2845 mBroadcastStats.removeAt(i);
2846 }
2847 }
2848 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002849 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002850 }
2851 }
2852 }
2853 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002854
2855 final class UidObserver extends IUidObserver.Stub {
Sudheer Shanka80255802017-03-04 14:48:53 -08002856 @Override public void onUidStateChanged(int uid, int procState,
2857 long procStateSeq) throws RemoteException {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002858 }
2859
Dianne Hackborne07641d2016-11-09 15:07:23 -08002860 @Override public void onUidGone(int uid, boolean disabled) throws RemoteException {
2861 if (disabled) {
2862 synchronized (mLock) {
2863 removeForStoppedLocked(uid);
2864 }
2865 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002866 }
2867
2868 @Override public void onUidActive(int uid) throws RemoteException {
2869 }
2870
Dianne Hackborne07641d2016-11-09 15:07:23 -08002871 @Override public void onUidIdle(int uid, boolean disabled) throws RemoteException {
2872 if (disabled) {
2873 synchronized (mLock) {
2874 removeForStoppedLocked(uid);
2875 }
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08002876 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002877 }
2878 };
2879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002880 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002881 String pkg = pi.getCreatorPackage();
2882 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002883 return getStatsLocked(uid, pkg);
2884 }
2885
2886 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002887 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
2888 if (uidStats == null) {
2889 uidStats = new ArrayMap<String, BroadcastStats>();
2890 mBroadcastStats.put(uid, uidStats);
2891 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002892 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002894 bs = new BroadcastStats(uid, pkgName);
2895 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002896 }
2897 return bs;
2898 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002899
Christopher Tate14a7bb02015-10-01 10:24:31 -07002900 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
2901 private InFlight removeLocked(PendingIntent pi, Intent intent) {
2902 for (int i = 0; i < mInFlight.size(); i++) {
2903 if (mInFlight.get(i).mPendingIntent == pi) {
2904 return mInFlight.remove(i);
2905 }
2906 }
2907 mLog.w("No in-flight alarm for " + pi + " " + intent);
2908 return null;
2909 }
2910
2911 private InFlight removeLocked(IBinder listener) {
2912 for (int i = 0; i < mInFlight.size(); i++) {
2913 if (mInFlight.get(i).mListener == listener) {
2914 return mInFlight.remove(i);
2915 }
2916 }
2917 mLog.w("No in-flight alarm for listener " + listener);
2918 return null;
2919 }
2920
2921 private void updateStatsLocked(InFlight inflight) {
2922 final long nowELAPSED = SystemClock.elapsedRealtime();
2923 BroadcastStats bs = inflight.mBroadcastStats;
2924 bs.nesting--;
2925 if (bs.nesting <= 0) {
2926 bs.nesting = 0;
2927 bs.aggregateTime += nowELAPSED - bs.startTime;
2928 }
2929 FilterStats fs = inflight.mFilterStats;
2930 fs.nesting--;
2931 if (fs.nesting <= 0) {
2932 fs.nesting = 0;
2933 fs.aggregateTime += nowELAPSED - fs.startTime;
2934 }
2935 if (RECORD_ALARMS_IN_HISTORY) {
2936 if (inflight.mWorkSource != null && inflight.mWorkSource.size() > 0) {
2937 for (int wi=0; wi<inflight.mWorkSource.size(); wi++) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002938 ActivityManager.noteAlarmFinish(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002939 inflight.mPendingIntent, inflight.mWorkSource.get(wi), inflight.mTag);
2940 }
2941 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002942 ActivityManager.noteAlarmFinish(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002943 inflight.mPendingIntent, inflight.mUid, inflight.mTag);
2944 }
2945 }
2946 }
2947
2948 private void updateTrackingLocked(InFlight inflight) {
2949 if (inflight != null) {
2950 updateStatsLocked(inflight);
2951 }
2952 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08002953 if (DEBUG_WAKELOCK) {
2954 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
2955 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002956 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002957 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002958 mWakeLock.release();
2959 if (mInFlight.size() > 0) {
2960 mLog.w("Finished all dispatches with " + mInFlight.size()
2961 + " remaining inflights");
2962 for (int i=0; i<mInFlight.size(); i++) {
2963 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
2964 }
2965 mInFlight.clear();
2966 }
2967 } else {
2968 // the next of our alarms is now in flight. reattribute the wakelock.
2969 if (mInFlight.size() > 0) {
2970 InFlight inFlight = mInFlight.get(0);
2971 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
2972 inFlight.mAlarmType, inFlight.mTag, -1, false);
2973 } else {
2974 // should never happen
2975 mLog.w("Alarm wakelock still held but sent queue empty");
2976 mWakeLock.setWorkSource(null);
2977 }
2978 }
2979 }
2980
2981 /**
2982 * Callback that arrives when a direct-call alarm reports that delivery has finished
2983 */
2984 @Override
2985 public void alarmComplete(IBinder who) {
2986 if (who == null) {
2987 Slog.w(TAG, "Invalid alarmComplete: uid=" + Binder.getCallingUid()
2988 + " pid=" + Binder.getCallingPid());
2989 return;
2990 }
2991
2992 final long ident = Binder.clearCallingIdentity();
2993 try {
2994 synchronized (mLock) {
2995 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
2996 InFlight inflight = removeLocked(who);
2997 if (inflight != null) {
2998 if (DEBUG_LISTENER_CALLBACK) {
2999 Slog.i(TAG, "alarmComplete() from " + who);
3000 }
3001 updateTrackingLocked(inflight);
3002 } else {
3003 // Delivery timed out, and the timeout handling already took care of
3004 // updating our tracking here, so we needn't do anything further.
3005 if (DEBUG_LISTENER_CALLBACK) {
3006 Slog.i(TAG, "Late alarmComplete() from " + who);
3007 }
3008 }
3009 }
3010 } finally {
3011 Binder.restoreCallingIdentity(ident);
3012 }
3013 }
3014
3015 /**
3016 * Callback that arrives when a PendingIntent alarm has finished delivery
3017 */
3018 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003019 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
3020 String resultData, Bundle resultExtras) {
3021 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003022 updateTrackingLocked(removeLocked(pi, intent));
3023 }
3024 }
3025
3026 /**
3027 * Timeout of a direct-call alarm delivery
3028 */
3029 public void alarmTimedOut(IBinder who) {
3030 synchronized (mLock) {
3031 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08003032 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003033 // TODO: implement ANR policy for the target
3034 if (DEBUG_LISTENER_CALLBACK) {
3035 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003036 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003037 updateTrackingLocked(inflight);
Dianne Hackborn81038902012-11-26 17:04:09 -08003038 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003039 if (DEBUG_LISTENER_CALLBACK) {
3040 Slog.i(TAG, "Spurious timeout of listener " + who);
3041 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003042 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003043 }
3044 }
3045
3046 /**
3047 * Deliver an alarm and set up the post-delivery handling appropriately
3048 */
3049 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
3050 if (alarm.operation != null) {
3051 // PendingIntent alarm
3052 try {
3053 alarm.operation.send(getContext(), 0,
3054 mBackgroundIntent.putExtra(
3055 Intent.EXTRA_ALARM_COUNT, alarm.count),
3056 mDeliveryTracker, mHandler, null,
3057 allowWhileIdle ? mIdleOptions : null);
3058 } catch (PendingIntent.CanceledException e) {
3059 if (alarm.repeatInterval > 0) {
3060 // This IntentSender is no longer valid, but this
3061 // is a repeating alarm, so toss it
3062 removeImpl(alarm.operation);
3063 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003064 // No actual delivery was possible, so the delivery tracker's
3065 // 'finished' callback won't be invoked. We also don't need
3066 // to do any wakelock or stats tracking, so we have nothing
3067 // left to do here but go on to the next thing.
3068 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003069 }
3070 } else {
3071 // Direct listener callback alarm
3072 try {
3073 if (DEBUG_LISTENER_CALLBACK) {
3074 Slog.v(TAG, "Alarm to uid=" + alarm.uid
3075 + " listener=" + alarm.listener.asBinder());
3076 }
3077 alarm.listener.doAlarm(this);
3078 mHandler.sendMessageDelayed(
3079 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
3080 alarm.listener.asBinder()),
3081 mConstants.LISTENER_TIMEOUT);
3082 } catch (Exception e) {
3083 if (DEBUG_LISTENER_CALLBACK) {
3084 Slog.i(TAG, "Alarm undeliverable to listener "
3085 + alarm.listener.asBinder(), e);
3086 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003087 // As in the PendingIntent.CanceledException case, delivery of the
3088 // alarm was not possible, so we have no wakelock or timeout or
3089 // stats management to do. It threw before we posted the delayed
3090 // timeout message, so we're done here.
3091 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003092 }
3093 }
3094
3095 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08003096 if (DEBUG_WAKELOCK) {
3097 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
3098 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003099 if (mBroadcastRefCount == 0) {
3100 setWakelockWorkSource(alarm.operation, alarm.workSource,
3101 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
3102 true);
3103 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003104 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003105 }
3106 final InFlight inflight = new InFlight(AlarmManagerService.this,
3107 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
3108 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
3109 mInFlight.add(inflight);
3110 mBroadcastRefCount++;
3111
3112 if (allowWhileIdle) {
3113 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
3114 mLastAllowWhileIdleDispatch.put(alarm.uid, nowELAPSED);
3115 if (RECORD_DEVICE_IDLE_ALARMS) {
3116 IdleDispatchEntry ent = new IdleDispatchEntry();
3117 ent.uid = alarm.uid;
3118 ent.pkg = alarm.packageName;
3119 ent.tag = alarm.statsTag;
3120 ent.op = "DELIVER";
3121 ent.elapsedRealtime = nowELAPSED;
3122 mAllowWhileIdleDispatches.add(ent);
3123 }
3124 }
3125
3126 final BroadcastStats bs = inflight.mBroadcastStats;
3127 bs.count++;
3128 if (bs.nesting == 0) {
3129 bs.nesting = 1;
3130 bs.startTime = nowELAPSED;
3131 } else {
3132 bs.nesting++;
3133 }
3134 final FilterStats fs = inflight.mFilterStats;
3135 fs.count++;
3136 if (fs.nesting == 0) {
3137 fs.nesting = 1;
3138 fs.startTime = nowELAPSED;
3139 } else {
3140 fs.nesting++;
3141 }
3142 if (alarm.type == ELAPSED_REALTIME_WAKEUP
3143 || alarm.type == RTC_WAKEUP) {
3144 bs.numWakeup++;
3145 fs.numWakeup++;
3146 if (alarm.workSource != null && alarm.workSource.size() > 0) {
3147 for (int wi=0; wi<alarm.workSource.size(); wi++) {
Christopher Tate0029f572016-06-14 10:16:28 -07003148 final String wsName = alarm.workSource.getName(wi);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003149 ActivityManager.noteWakeupAlarm(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003150 alarm.operation, alarm.workSource.get(wi),
Christopher Tate0029f572016-06-14 10:16:28 -07003151 (wsName != null) ? wsName : alarm.packageName,
3152 alarm.statsTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08003153 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003154 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003155 ActivityManager.noteWakeupAlarm(
Joe Onorato78bcdf92016-05-09 10:10:29 -07003156 alarm.operation, alarm.uid, alarm.packageName, alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003157 }
3158 }
3159 }
3160 }
3161}