blob: 0e3867d6ff5cca83ddd2ce6e1387c6ab4607e93b [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import android.app.ActivityManagerNative;
Christopher Tate57ceaaa2013-07-19 16:30:43 -070022import android.app.AlarmManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import android.app.IAlarmManager;
24import android.app.PendingIntent;
25import android.content.BroadcastReceiver;
26import android.content.Context;
27import android.content.Intent;
28import android.content.IntentFilter;
29import android.content.pm.PackageManager;
30import android.net.Uri;
31import android.os.Binder;
32import android.os.Bundle;
33import android.os.Handler;
Adam Lesinski182f73f2013-12-05 16:48:06 -080034import android.os.IBinder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.os.Message;
36import android.os.PowerManager;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070037import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.os.SystemClock;
39import android.os.SystemProperties;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070040import android.os.UserHandle;
Christopher Tatec4a07d12012-04-06 14:19:13 -070041import android.os.WorkSource;
Adrian Roosc42a1e12014-07-07 23:35:53 +020042import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.text.TextUtils;
Adrian Roosc42a1e12014-07-07 23:35:53 +020044import android.text.format.DateFormat;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080045import android.util.ArrayMap;
Adrian Roosc42a1e12014-07-07 23:35:53 +020046import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080047import android.util.Slog;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080048import android.util.SparseArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +020049import android.util.SparseBooleanArray;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070050import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051
Christopher Tate4cb338d2013-07-26 13:11:31 -070052import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import java.io.FileDescriptor;
54import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070055import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -080057import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import java.util.Calendar;
59import java.util.Collections;
60import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -050061import java.util.Date;
Christopher Tate1590f1e2014-10-02 17:27:57 -070062import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -070063import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +020064import java.util.Locale;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070065import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import java.util.TimeZone;
67
Christopher Tatee0a22b32013-07-11 14:43:13 -070068import static android.app.AlarmManager.RTC_WAKEUP;
69import static android.app.AlarmManager.RTC;
70import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
71import static android.app.AlarmManager.ELAPSED_REALTIME;
72
Dianne Hackborn81038902012-11-26 17:04:09 -080073import com.android.internal.util.LocalLog;
74
Adam Lesinski182f73f2013-12-05 16:48:06 -080075class AlarmManagerService extends SystemService {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076 // The threshold for how long an alarm can be late before we print a
77 // warning message. The time duration is in milliseconds.
78 private static final long LATE_ALARM_THRESHOLD = 10 * 1000;
Christopher Tatee0a22b32013-07-11 14:43:13 -070079
Christopher Tate498c6cb2014-11-17 16:09:27 -080080 // Minimum futurity of a new alarm
81 private static final long MIN_FUTURITY = 5 * 1000; // 5 seconds, in millis
82
83 // Minimum alarm recurrence interval
84 private static final long MIN_INTERVAL = 60 * 1000; // one minute, in millis
85
Christopher Tatee0a22b32013-07-11 14:43:13 -070086 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
87 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -080088 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -070089 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -080090 static final int TIME_CHANGED_MASK = 1 << 16;
91 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -080092
Christopher Tatee0a22b32013-07-11 14:43:13 -070093 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -080094 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -080095
Adam Lesinski182f73f2013-12-05 16:48:06 -080096 static final String TAG = "AlarmManager";
97 static final String ClockReceiver_TAG = "ClockReceiver";
98 static final boolean localLOGV = false;
99 static final boolean DEBUG_BATCH = localLOGV || false;
100 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200101 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700102 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800103 static final int ALARM_EVENT = 1;
104 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200105
Adam Lesinski182f73f2013-12-05 16:48:06 -0800106 static final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800108 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109
Adam Lesinski182f73f2013-12-05 16:48:06 -0800110 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700111
Adrian Roosc42a1e12014-07-07 23:35:53 +0200112 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT = new Intent(
113 AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED);
114
Adam Lesinski182f73f2013-12-05 16:48:06 -0800115 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800116
Adam Lesinski182f73f2013-12-05 16:48:06 -0800117 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800118
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800119 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800120 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700121 private long mNextNonWakeup;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800122 int mBroadcastRefCount = 0;
123 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700124 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700125 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<Alarm>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800126 ArrayList<InFlight> mInFlight = new ArrayList<InFlight>();
127 final AlarmHandler mHandler = new AlarmHandler();
128 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700129 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130 private UninstallReceiver mUninstallReceiver;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800131 final ResultReceiver mResultReceiver = new ResultReceiver();
132 PendingIntent mTimeTickSender;
133 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700134 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700135 boolean mInteractive = true;
136 long mNonInteractiveStartTime;
137 long mNonInteractiveTime;
138 long mLastAlarmDeliveryTime;
139 long mStartCurrentDelayTime;
140 long mNextNonWakeupDeliveryTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700141 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800142
Jose Lima235510e2014-08-13 12:50:01 -0700143 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
144 new SparseArray<>();
145 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
146 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200147 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
148 new SparseBooleanArray();
149 private boolean mNextAlarmClockMayChange;
150
151 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700152 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
153 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200154
Christopher Tate1590f1e2014-10-02 17:27:57 -0700155 // Alarm delivery ordering bookkeeping
156 static final int PRIO_TICK = 0;
157 static final int PRIO_WAKEUP = 1;
158 static final int PRIO_NORMAL = 2;
159
160 class PriorityClass {
161 int seq;
162 int priority;
163
164 PriorityClass() {
165 seq = mCurrentSeq - 1;
166 priority = PRIO_NORMAL;
167 }
168 }
169
170 final HashMap<String, PriorityClass> mPriorities =
171 new HashMap<String, PriorityClass>();
172 int mCurrentSeq = 0;
173
Christopher Tate18a75f12013-07-01 18:18:59 -0700174 class WakeupEvent {
175 public long when;
176 public int uid;
177 public String action;
178
179 public WakeupEvent(long theTime, int theUid, String theAction) {
180 when = theTime;
181 uid = theUid;
182 action = theAction;
183 }
184 }
185
Adam Lesinski182f73f2013-12-05 16:48:06 -0800186 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
187 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700188
Adrian Roosc42a1e12014-07-07 23:35:53 +0200189 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700190 long start; // These endpoints are always in ELAPSED
191 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700192 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700193
194 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
195
196 Batch() {
197 start = 0;
198 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700199 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700200 }
201
202 Batch(Alarm seed) {
203 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700204 end = seed.maxWhenElapsed;
205 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700206 alarms.add(seed);
207 }
208
209 int size() {
210 return alarms.size();
211 }
212
213 Alarm get(int index) {
214 return alarms.get(index);
215 }
216
217 boolean canHold(long whenElapsed, long maxWhen) {
218 return (end >= whenElapsed) && (start <= maxWhen);
219 }
220
221 boolean add(Alarm alarm) {
222 boolean newStart = false;
223 // narrows the batch if necessary; presumes that canHold(alarm) is true
224 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
225 if (index < 0) {
226 index = 0 - index - 1;
227 }
228 alarms.add(index, alarm);
229 if (DEBUG_BATCH) {
230 Slog.v(TAG, "Adding " + alarm + " to " + this);
231 }
232 if (alarm.whenElapsed > start) {
233 start = alarm.whenElapsed;
234 newStart = true;
235 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700236 if (alarm.maxWhenElapsed < end) {
237 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700238 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700239 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700240
241 if (DEBUG_BATCH) {
242 Slog.v(TAG, " => now " + this);
243 }
244 return newStart;
245 }
246
247 boolean remove(final PendingIntent operation) {
248 boolean didRemove = false;
249 long newStart = 0; // recalculate endpoints as we go
250 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700251 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700252 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700253 Alarm alarm = alarms.get(i);
254 if (alarm.operation.equals(operation)) {
255 alarms.remove(i);
256 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200257 if (alarm.alarmClock != null) {
258 mNextAlarmClockMayChange = true;
259 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700260 } else {
261 if (alarm.whenElapsed > newStart) {
262 newStart = alarm.whenElapsed;
263 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700264 if (alarm.maxWhenElapsed < newEnd) {
265 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700266 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700267 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700268 i++;
269 }
270 }
271 if (didRemove) {
272 // commit the new batch bounds
273 start = newStart;
274 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700275 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700276 }
277 return didRemove;
278 }
279
280 boolean remove(final String packageName) {
281 boolean didRemove = false;
282 long newStart = 0; // recalculate endpoints as we go
283 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700284 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700285 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700286 Alarm alarm = alarms.get(i);
287 if (alarm.operation.getTargetPackage().equals(packageName)) {
288 alarms.remove(i);
289 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200290 if (alarm.alarmClock != null) {
291 mNextAlarmClockMayChange = true;
292 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700293 } else {
294 if (alarm.whenElapsed > newStart) {
295 newStart = alarm.whenElapsed;
296 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700297 if (alarm.maxWhenElapsed < newEnd) {
298 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700299 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700300 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700301 i++;
302 }
303 }
304 if (didRemove) {
305 // commit the new batch bounds
306 start = newStart;
307 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700308 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700309 }
310 return didRemove;
311 }
312
313 boolean remove(final int userHandle) {
314 boolean didRemove = false;
315 long newStart = 0; // recalculate endpoints as we go
316 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700317 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700318 Alarm alarm = alarms.get(i);
319 if (UserHandle.getUserId(alarm.operation.getCreatorUid()) == userHandle) {
320 alarms.remove(i);
321 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200322 if (alarm.alarmClock != null) {
323 mNextAlarmClockMayChange = true;
324 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700325 } else {
326 if (alarm.whenElapsed > newStart) {
327 newStart = alarm.whenElapsed;
328 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700329 if (alarm.maxWhenElapsed < newEnd) {
330 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700331 }
332 i++;
333 }
334 }
335 if (didRemove) {
336 // commit the new batch bounds
337 start = newStart;
338 end = newEnd;
339 }
340 return didRemove;
341 }
342
343 boolean hasPackage(final String packageName) {
344 final int N = alarms.size();
345 for (int i = 0; i < N; i++) {
346 Alarm a = alarms.get(i);
347 if (a.operation.getTargetPackage().equals(packageName)) {
348 return true;
349 }
350 }
351 return false;
352 }
353
354 boolean hasWakeups() {
355 final int N = alarms.size();
356 for (int i = 0; i < N; i++) {
357 Alarm a = alarms.get(i);
358 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
359 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
360 return true;
361 }
362 }
363 return false;
364 }
365
366 @Override
367 public String toString() {
368 StringBuilder b = new StringBuilder(40);
369 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
370 b.append(" num="); b.append(size());
371 b.append(" start="); b.append(start);
372 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700373 if (flags != 0) {
374 b.append(" flgs=0x");
375 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700376 }
377 b.append('}');
378 return b.toString();
379 }
380 }
381
382 static class BatchTimeOrder implements Comparator<Batch> {
383 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800384 long when1 = b1.start;
385 long when2 = b2.start;
386 if (when1 - when2 > 0) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700387 return 1;
388 }
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800389 if (when1 - when2 < 0) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700390 return -1;
391 }
392 return 0;
393 }
394 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800395
396 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
397 @Override
398 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700399 // priority class trumps everything. TICK < WAKEUP < NORMAL
400 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
401 return -1;
402 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
403 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800404 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700405
406 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800407 if (lhs.whenElapsed < rhs.whenElapsed) {
408 return -1;
409 } else if (lhs.whenElapsed > rhs.whenElapsed) {
410 return 1;
411 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700412
413 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800414 return 0;
415 }
416 };
417
Christopher Tate1590f1e2014-10-02 17:27:57 -0700418 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
419 final int N = alarms.size();
420 for (int i = 0; i < N; i++) {
421 Alarm a = alarms.get(i);
422
423 final int alarmPrio;
424 if (Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
425 alarmPrio = PRIO_TICK;
426 } else if (a.wakeup) {
427 alarmPrio = PRIO_WAKEUP;
428 } else {
429 alarmPrio = PRIO_NORMAL;
430 }
431
432 PriorityClass packagePrio = a.priorityClass;
433 if (packagePrio == null) packagePrio = mPriorities.get(a.operation.getCreatorPackage());
434 if (packagePrio == null) {
435 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
436 mPriorities.put(a.operation.getCreatorPackage(), packagePrio);
437 }
438 a.priorityClass = packagePrio;
439
440 if (packagePrio.seq != mCurrentSeq) {
441 // first alarm we've seen in the current delivery generation from this package
442 packagePrio.priority = alarmPrio;
443 packagePrio.seq = mCurrentSeq;
444 } else {
445 // Multiple alarms from this package being delivered in this generation;
446 // bump the package's delivery class if it's warranted.
447 // TICK < WAKEUP < NORMAL
448 if (alarmPrio < packagePrio.priority) {
449 packagePrio.priority = alarmPrio;
450 }
451 }
452 }
453 }
454
Christopher Tatee0a22b32013-07-11 14:43:13 -0700455 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800456 static final long MIN_FUZZABLE_INTERVAL = 10000;
457 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700458 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
459
460 // set to null if in idle mode; while in this mode, any alarms we don't want
461 // to run during this time are placed in mPendingWhileIdleAlarms
462 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700463 Alarm mNextWakeFromIdle = null;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700464 final ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700465
Jeff Brownb880d882014-02-10 19:47:07 -0800466 public AlarmManagerService(Context context) {
467 super(context);
468 }
469
Christopher Tatee0a22b32013-07-11 14:43:13 -0700470 static long convertToElapsed(long when, int type) {
471 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
472 if (isRtc) {
473 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
474 }
475 return when;
476 }
477
478 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
479 // calculate the end of our nominal delivery window for the alarm.
480 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
481 // Current heuristic: batchable window is 75% of either the recurrence interval
482 // [for a periodic alarm] or of the time from now to the desired delivery time,
483 // with a minimum delay/interval of 10 seconds, under which we will simply not
484 // defer the alarm.
485 long futurity = (interval == 0)
486 ? (triggerAtTime - now)
487 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700488 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700489 futurity = 0;
490 }
491 return triggerAtTime + (long)(.75 * futurity);
492 }
493
494 // returns true if the batch was added at the head
495 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
496 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
497 if (index < 0) {
498 index = 0 - index - 1;
499 }
500 list.add(index, newBatch);
501 return (index == 0);
502 }
503
Christopher Tate385e4982013-07-23 18:22:29 -0700504 // Return the index of the matching batch, or -1 if none found.
505 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700506 final int N = mAlarmBatches.size();
507 for (int i = 0; i < N; i++) {
508 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700509 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700510 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700511 }
512 }
Christopher Tate385e4982013-07-23 18:22:29 -0700513 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700514 }
515
516 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
517 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700518 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700519 rebatchAllAlarmsLocked(true);
520 }
521 }
522
523 void rebatchAllAlarmsLocked(boolean doValidate) {
524 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
525 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700526 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700527 final long nowElapsed = SystemClock.elapsedRealtime();
528 final int oldBatches = oldSet.size();
529 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
530 Batch batch = oldSet.get(batchNum);
531 final int N = batch.size();
532 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700533 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700534 }
535 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700536 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
537 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
538 + " to " + mPendingIdleUntil);
539 if (mPendingIdleUntil == null) {
540 // Somehow we lost this... we need to restore all of the pending alarms.
541 restorePendingWhileIdleAlarmsLocked();
542 }
543 }
544 rescheduleKernelAlarmsLocked();
545 updateNextAlarmClockLocked();
546 }
547
548 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
549 a.when = a.origWhen;
550 long whenElapsed = convertToElapsed(a.when, a.type);
551 final long maxElapsed;
552 if (a.whenElapsed == a.maxWhenElapsed) {
553 // Exact
554 maxElapsed = whenElapsed;
555 } else {
556 // Not exact. Preserve any explicit window, otherwise recalculate
557 // the window based on the alarm's new futurity. Note that this
558 // reflects a policy of preferring timely to deferred delivery.
559 maxElapsed = (a.windowLength > 0)
560 ? (whenElapsed + a.windowLength)
561 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
562 }
563 a.whenElapsed = whenElapsed;
564 a.maxWhenElapsed = maxElapsed;
565 setImplLocked(a, true, doValidate);
566 }
567
568 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackborn35d54032015-04-23 10:30:43 -0700569 // Bring pending alarms back into the main list.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700570 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackborn35d54032015-04-23 10:30:43 -0700571 for (int i=mPendingWhileIdleAlarms.size() - 1; i >= 0 && mPendingIdleUntil == null; i--) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700572 Alarm a = mPendingWhileIdleAlarms.remove(i);
573 reAddAlarmLocked(a, nowElapsed, false);
574 }
Dianne Hackborn35d54032015-04-23 10:30:43 -0700575
576 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700577 rescheduleKernelAlarmsLocked();
578 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -0700579
580 // And send a TIME_TICK right now, since it is important to get the UI updated.
581 try {
582 mTimeTickSender.send();
583 } catch (PendingIntent.CanceledException e) {
584 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700585 }
586
Adam Lesinski182f73f2013-12-05 16:48:06 -0800587 static final class InFlight extends Intent {
Dianne Hackborn81038902012-11-26 17:04:09 -0800588 final PendingIntent mPendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700589 final WorkSource mWorkSource;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700590 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800591 final BroadcastStats mBroadcastStats;
592 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800593 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800594
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800595 InFlight(AlarmManagerService service, PendingIntent pendingIntent, WorkSource workSource,
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700596 int alarmType, String tag, long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800597 mPendingIntent = pendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700598 mWorkSource = workSource;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700599 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800600 mBroadcastStats = service.getStatsLocked(pendingIntent);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700601 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -0800602 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700603 fs = new FilterStats(mBroadcastStats, mTag);
604 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -0800605 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700606 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -0800607 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800608 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800609 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800611
Adam Lesinski182f73f2013-12-05 16:48:06 -0800612 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -0800613 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700614 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800615
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700616 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800617 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800618 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619 int numWakeup;
620 long startTime;
621 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -0800622
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700623 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800624 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700625 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800626 }
627 }
628
Adam Lesinski182f73f2013-12-05 16:48:06 -0800629 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800630 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800631 final String mPackageName;
632
633 long aggregateTime;
634 int count;
635 int numWakeup;
636 long startTime;
637 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700638 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -0800639
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800640 BroadcastStats(int uid, String packageName) {
641 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800642 mPackageName = packageName;
643 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800644 }
645
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800646 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
647 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700648
649 int mNumDelayedAlarms = 0;
650 long mTotalDelayTime = 0;
651 long mMaxDelayTime = 0;
652
Adam Lesinski182f73f2013-12-05 16:48:06 -0800653 @Override
654 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800655 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800656 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800657
658 // We have to set current TimeZone info to kernel
659 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -0800660 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800661
Adam Lesinski182f73f2013-12-05 16:48:06 -0800662 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800663 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800664
Adam Lesinski182f73f2013-12-05 16:48:06 -0800665 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700667 Intent.FLAG_RECEIVER_REGISTERED_ONLY
668 | Intent.FLAG_RECEIVER_FOREGROUND), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700669 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800670 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
671 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800672 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700673 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674
675 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -0800676 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800677 mClockReceiver.scheduleTimeTickEvent();
678 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700679 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680 mUninstallReceiver = new UninstallReceiver();
681
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800682 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800683 AlarmThread waitThread = new AlarmThread();
684 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800686 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800688
689 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800691
692 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693 protected void finalize() throws Throwable {
694 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800695 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 } finally {
697 super.finalize();
698 }
699 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700700
Adam Lesinski182f73f2013-12-05 16:48:06 -0800701 void setTimeZoneImpl(String tz) {
702 if (TextUtils.isEmpty(tz)) {
703 return;
David Christieebe51fc2013-07-26 13:23:29 -0700704 }
705
Adam Lesinski182f73f2013-12-05 16:48:06 -0800706 TimeZone zone = TimeZone.getTimeZone(tz);
707 // Prevent reentrant calls from stepping on each other when writing
708 // the time zone property
709 boolean timeZoneWasChanged = false;
710 synchronized (this) {
711 String current = SystemProperties.get(TIMEZONE_PROPERTY);
712 if (current == null || !current.equals(zone.getID())) {
713 if (localLOGV) {
714 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
715 }
716 timeZoneWasChanged = true;
717 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
718 }
719
720 // Update the kernel timezone information
721 // Kernel tracks time offsets as 'minutes west of GMT'
722 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800723 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -0800724 }
725
726 TimeZone.setDefault(null);
727
728 if (timeZoneWasChanged) {
729 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
730 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
731 intent.putExtra("time-zone", zone.getID());
732 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
733 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700735
Adam Lesinski182f73f2013-12-05 16:48:06 -0800736 void removeImpl(PendingIntent operation) {
737 if (operation == null) {
738 return;
739 }
740 synchronized (mLock) {
741 removeLocked(operation);
742 }
743 }
744
745 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700746 PendingIntent operation, int flags, WorkSource workSource,
Jose Lima235510e2014-08-13 12:50:01 -0700747 AlarmManager.AlarmClockInfo alarmClock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 if (operation == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800749 Slog.w(TAG, "set/setRepeating ignored because there is no intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750 return;
751 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700752
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700753 // Sanity check the window length. This will catch people mistakenly
754 // trying to pass an end-of-window timestamp rather than a duration.
755 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
756 Slog.w(TAG, "Window length " + windowLength
757 + "ms suspiciously long; limiting to 1 hour");
758 windowLength = AlarmManager.INTERVAL_HOUR;
759 }
760
Christopher Tate498c6cb2014-11-17 16:09:27 -0800761 // Sanity check the recurrence interval. This will catch people who supply
762 // seconds when the API expects milliseconds.
763 if (interval > 0 && interval < MIN_INTERVAL) {
764 Slog.w(TAG, "Suspiciously short interval " + interval
765 + " millis; expanding to " + (int)(MIN_INTERVAL/1000)
766 + " seconds");
767 interval = MIN_INTERVAL;
768 }
769
Christopher Tatee0a22b32013-07-11 14:43:13 -0700770 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
771 throw new IllegalArgumentException("Invalid alarm type " + type);
772 }
773
Christopher Tate5f221e82013-07-30 17:13:15 -0700774 if (triggerAtTime < 0) {
775 final long who = Binder.getCallingUid();
776 final long what = Binder.getCallingPid();
777 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + who
778 + " pid=" + what);
779 triggerAtTime = 0;
780 }
781
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700782 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -0800783 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
784 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
785 final long minTrigger = nowElapsed + MIN_FUTURITY;
786 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
787
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700788 final long maxElapsed;
789 if (windowLength == AlarmManager.WINDOW_EXACT) {
790 maxElapsed = triggerElapsed;
791 } else if (windowLength < 0) {
792 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
793 } else {
794 maxElapsed = triggerElapsed + windowLength;
795 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700796
Adrian Roosc42a1e12014-07-07 23:35:53 +0200797 final int userId = UserHandle.getCallingUserId();
798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700800 if (DEBUG_BATCH) {
801 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700802 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -0700803 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700804 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805 }
Christopher Tate3e04b472013-10-21 17:51:31 -0700806 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700807 interval, operation, flags, true, workSource, alarmClock, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 }
809 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810
Christopher Tate3e04b472013-10-21 17:51:31 -0700811 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700812 long maxWhen, long interval, PendingIntent operation, int flags,
Jose Lima235510e2014-08-13 12:50:01 -0700813 boolean doValidate, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
814 int userId) {
Christopher Tate3e04b472013-10-21 17:51:31 -0700815 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700816 operation, workSource, flags, alarmClock, userId);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700817 removeLocked(operation);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700818 setImplLocked(a, false, doValidate);
819 }
Christopher Tateb8849c12011-02-08 13:39:01 -0800820
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700821 private void updateNextWakeFromIdleFuzzLocked() {
822 if (mNextWakeFromIdle != null) {
823
824 }
825 }
826
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700827 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
828 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700829 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700830 // The caller has given the time they want this to happen at, however we need
831 // to pull that earlier if there are existing alarms that have requested to
832 // bring us out of idle.
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700833 if (mNextWakeFromIdle != null) {
834 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700835 }
836 // Add fuzz to make the alarm go off some time before the actual desired time.
837 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700838 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700839 if (fuzz > 0) {
840 if (mRandom == null) {
841 mRandom = new Random();
842 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700843 final int delta = mRandom.nextInt(fuzz);
844 a.whenElapsed -= delta;
845 if (false) {
846 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
847 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
848 Slog.d(TAG, "Applied fuzz: " + fuzz);
849 Slog.d(TAG, "Final delta: " + delta);
850 Slog.d(TAG, "Final when: " + a.whenElapsed);
851 }
852 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700853 }
854
855 } else if (mPendingIdleUntil != null) {
856 // We currently have an idle until alarm scheduled; if the new alarm has
857 // not explicitly stated it wants to run while idle, then put it on hold.
858 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE|AlarmManager.FLAG_WAKE_FROM_IDLE))
859 == 0) {
860 mPendingWhileIdleAlarms.add(a);
861 return;
862 }
863 }
864
865 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
866 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -0700867 if (whichBatch < 0) {
868 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -0700869 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 } else {
Christopher Tate385e4982013-07-23 18:22:29 -0700871 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -0700872 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700873 // The start time of this batch advanced, so batch ordering may
874 // have just been broken. Move it to where it now belongs.
875 mAlarmBatches.remove(whichBatch);
876 addBatchLocked(mAlarmBatches, batch);
877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 }
879
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700880 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +0200881 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200882 }
883
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700884 boolean needRebatch = false;
885
886 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
887 mPendingIdleUntil = a;
888 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700889 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
890 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
891 mNextWakeFromIdle = a;
892 // If this wake from idle is earlier than whatever was previously scheduled,
893 // and we are currently idling, then we need to rebatch alarms in case the idle
894 // until time needs to be updated.
895 if (mPendingIdleUntil != null) {
896 needRebatch = true;
897 }
898 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700899 }
900
901 if (!rebatching) {
902 if (DEBUG_VALIDATE) {
903 if (doValidate && !validateConsistencyLocked()) {
904 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
905 + " when(hex)=" + Long.toHexString(a.when)
906 + " whenElapsed=" + a.whenElapsed
907 + " maxWhenElapsed=" + a.maxWhenElapsed
908 + " interval=" + a.repeatInterval + " op=" + a.operation
909 + " flags=0x" + Integer.toHexString(a.flags));
910 rebatchAllAlarmsLocked(false);
911 needRebatch = false;
912 }
913 }
914
915 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700916 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -0700917 }
Christopher Tate4cb338d2013-07-26 13:11:31 -0700918
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700919 rescheduleKernelAlarmsLocked();
920 updateNextAlarmClockLocked();
921 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700922 }
923
Adam Lesinski182f73f2013-12-05 16:48:06 -0800924 private final IBinder mService = new IAlarmManager.Stub() {
925 @Override
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700926 public void set(int type, long triggerAtTime, long windowLength, long interval, int flags,
Jose Lima235510e2014-08-13 12:50:01 -0700927 PendingIntent operation, WorkSource workSource,
928 AlarmManager.AlarmClockInfo alarmClock) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800929 if (workSource != null) {
930 getContext().enforceCallingPermission(
931 android.Manifest.permission.UPDATE_DEVICE_STATS,
932 "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -0700933 }
934
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700935 if (windowLength == AlarmManager.WINDOW_EXACT) {
936 flags |= AlarmManager.FLAG_STANDALONE;
937 }
938 if (alarmClock != null) {
939 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
940 }
941 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
942 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE;
943 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800944 setImpl(type, triggerAtTime, windowLength, interval, operation,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700945 flags, workSource, alarmClock);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800946 }
Christopher Tate89779822012-08-31 14:40:03 -0700947
Adam Lesinski182f73f2013-12-05 16:48:06 -0800948 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -0800949 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800950 getContext().enforceCallingOrSelfPermission(
951 "android.permission.SET_TIME",
952 "setTime");
953
Greg Hackmann0cab8962014-02-21 16:35:52 -0800954 if (mNativeData == 0) {
955 Slog.w(TAG, "Not setting time since no alarm driver is available.");
956 return false;
Christopher Tate89779822012-08-31 14:40:03 -0700957 }
Greg Hackmann0cab8962014-02-21 16:35:52 -0800958
959 synchronized (mLock) {
960 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800963
964 @Override
965 public void setTimeZone(String tz) {
966 getContext().enforceCallingOrSelfPermission(
967 "android.permission.SET_TIME_ZONE",
968 "setTimeZone");
969
970 final long oldId = Binder.clearCallingIdentity();
971 try {
972 setTimeZoneImpl(tz);
973 } finally {
974 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 }
976 }
Christopher Tate4cb338d2013-07-26 13:11:31 -0700977
Adam Lesinski182f73f2013-12-05 16:48:06 -0800978 @Override
979 public void remove(PendingIntent operation) {
980 removeImpl(operation);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700981
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 }
Christopher Tate4cb338d2013-07-26 13:11:31 -0700983
Adam Lesinski182f73f2013-12-05 16:48:06 -0800984 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700985 public long getNextWakeFromIdleTime() {
986 return getNextWakeFromIdleTimeImpl();
987 }
988
989 @Override
Jose Lima235510e2014-08-13 12:50:01 -0700990 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +0200991 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
992 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
993 "getNextAlarmClock", null);
994
995 return getNextAlarmClockImpl(userId);
996 }
997
998 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -0800999 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1000 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1001 != PackageManager.PERMISSION_GRANTED) {
1002 pw.println("Permission Denial: can't dump AlarmManager from from pid="
1003 + Binder.getCallingPid()
1004 + ", uid=" + Binder.getCallingUid());
1005 return;
Christopher Tate4cb338d2013-07-26 13:11:31 -07001006 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001007
Adam Lesinski182f73f2013-12-05 16:48:06 -08001008 dumpImpl(pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001009 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001010 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001011
Adam Lesinski182f73f2013-12-05 16:48:06 -08001012 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 synchronized (mLock) {
1014 pw.println("Current Alarm Manager state:");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001015 final long nowRTC = System.currentTimeMillis();
1016 final long nowELAPSED = SystemClock.elapsedRealtime();
1017 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1018
1019 pw.print("nowRTC="); pw.print(nowRTC);
1020 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001021 pw.print(" nowELAPSED="); TimeUtils.formatDuration(nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001022 pw.println();
1023 if (!mInteractive) {
1024 pw.print("Time since non-interactive: ");
1025 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1026 pw.println();
1027 pw.print("Max wakeup delay: ");
1028 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1029 pw.println();
1030 pw.print("Time since last dispatch: ");
1031 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1032 pw.println();
1033 pw.print("Next non-wakeup delivery time: ");
1034 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1035 pw.println();
1036 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001037
1038 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1039 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001040 pw.print("Next non-wakeup alarm: ");
1041 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001042 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001043 pw.print("Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001044 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackborn998e6082014-09-11 19:13:23 -07001045 pw.print("Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001046
1047 if (mAlarmBatches.size() > 0) {
1048 pw.println();
1049 pw.print("Pending alarm batches: ");
1050 pw.println(mAlarmBatches.size());
1051 for (Batch b : mAlarmBatches) {
1052 pw.print(b); pw.println(':');
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001053 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001054 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001056 if (mPendingIdleUntil != null) {
1057 pw.println();
1058 pw.println("Idle mode state:");
1059 pw.print(" Idling until: "); pw.println(mPendingIdleUntil);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001060 mPendingIdleUntil.dump(pw, " ", nowRTC, nowELAPSED, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001061 pw.println(" Pending alarms:");
1062 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
1063 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001064 if (mNextWakeFromIdle != null) {
1065 pw.println();
1066 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
1067 mNextWakeFromIdle.dump(pw, " ", nowRTC, nowELAPSED, sdf);
1068 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001069
1070 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001071 pw.print("Past-due non-wakeup alarms: ");
1072 if (mPendingNonWakeupAlarms.size() > 0) {
1073 pw.println(mPendingNonWakeupAlarms.size());
1074 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
1075 } else {
1076 pw.println("(none)");
1077 }
1078 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
1079 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1080 pw.println();
1081 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
1082 pw.print(", max non-interactive time: ");
1083 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1084 pw.println();
1085
1086 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001087 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001088 pw.println();
1089
1090 if (mLog.dump(pw, " Recent problems", " ")) {
1091 pw.println();
1092 }
1093
1094 final FilterStats[] topFilters = new FilterStats[10];
1095 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1096 @Override
1097 public int compare(FilterStats lhs, FilterStats rhs) {
1098 if (lhs.aggregateTime < rhs.aggregateTime) {
1099 return 1;
1100 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1101 return -1;
1102 }
1103 return 0;
1104 }
1105 };
1106 int len = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001107 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1108 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1109 for (int ip=0; ip<uidStats.size(); ip++) {
1110 BroadcastStats bs = uidStats.valueAt(ip);
1111 for (int is=0; is<bs.filterStats.size(); is++) {
1112 FilterStats fs = bs.filterStats.valueAt(is);
1113 int pos = len > 0
1114 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1115 if (pos < 0) {
1116 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001117 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001118 if (pos < topFilters.length) {
1119 int copylen = topFilters.length - pos - 1;
1120 if (copylen > 0) {
1121 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1122 }
1123 topFilters[pos] = fs;
1124 if (len < topFilters.length) {
1125 len++;
1126 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001127 }
1128 }
1129 }
1130 }
1131 if (len > 0) {
1132 pw.println(" Top Alarms:");
1133 for (int i=0; i<len; i++) {
1134 FilterStats fs = topFilters[i];
1135 pw.print(" ");
1136 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1137 TimeUtils.formatDuration(fs.aggregateTime, pw);
1138 pw.print(" running, "); pw.print(fs.numWakeup);
1139 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001140 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1141 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001142 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001143 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001144 pw.println();
1145 }
1146 }
1147
1148 pw.println(" ");
1149 pw.println(" Alarm Stats:");
1150 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001151 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1152 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1153 for (int ip=0; ip<uidStats.size(); ip++) {
1154 BroadcastStats bs = uidStats.valueAt(ip);
1155 pw.print(" ");
1156 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1157 UserHandle.formatUid(pw, bs.mUid);
1158 pw.print(":");
1159 pw.print(bs.mPackageName);
1160 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1161 pw.print(" running, "); pw.print(bs.numWakeup);
1162 pw.println(" wakeups:");
1163 tmpFilters.clear();
1164 for (int is=0; is<bs.filterStats.size(); is++) {
1165 tmpFilters.add(bs.filterStats.valueAt(is));
1166 }
1167 Collections.sort(tmpFilters, comparator);
1168 for (int i=0; i<tmpFilters.size(); i++) {
1169 FilterStats fs = tmpFilters.get(i);
1170 pw.print(" ");
1171 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1172 TimeUtils.formatDuration(fs.aggregateTime, pw);
1173 pw.print(" "); pw.print(fs.numWakeup);
1174 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001175 pw.print(" alarms, last ");
1176 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1177 pw.println(":");
1178 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001179 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001180 pw.println();
1181 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 }
1183 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001184
1185 if (WAKEUP_STATS) {
1186 pw.println();
1187 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001188 long last = -1;
1189 for (WakeupEvent event : mRecentWakeups) {
1190 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1191 pw.print('|');
1192 if (last < 0) {
1193 pw.print('0');
1194 } else {
1195 pw.print(event.when - last);
1196 }
1197 last = event.when;
1198 pw.print('|'); pw.print(event.uid);
1199 pw.print('|'); pw.print(event.action);
1200 pw.println();
1201 }
1202 pw.println();
1203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204 }
1205 }
1206
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001207 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001208 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
1209 PrintWriter pw = new PrintWriter(bs);
1210 final long nowRTC = System.currentTimeMillis();
1211 final long nowELAPSED = SystemClock.elapsedRealtime();
1212 final int NZ = mAlarmBatches.size();
1213 for (int iz = 0; iz < NZ; iz++) {
1214 Batch bz = mAlarmBatches.get(iz);
1215 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001216 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001217 pw.flush();
1218 Slog.v(TAG, bs.toString());
1219 bs.reset();
1220 }
1221 }
1222
1223 private boolean validateConsistencyLocked() {
1224 if (DEBUG_VALIDATE) {
1225 long lastTime = Long.MIN_VALUE;
1226 final int N = mAlarmBatches.size();
1227 for (int i = 0; i < N; i++) {
1228 Batch b = mAlarmBatches.get(i);
1229 if (b.start >= lastTime) {
1230 // duplicate start times are okay because of standalone batches
1231 lastTime = b.start;
1232 } else {
1233 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001234 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1235 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001236 return false;
1237 }
1238 }
1239 }
1240 return true;
1241 }
1242
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001243 private Batch findFirstWakeupBatchLocked() {
1244 final int N = mAlarmBatches.size();
1245 for (int i = 0; i < N; i++) {
1246 Batch b = mAlarmBatches.get(i);
1247 if (b.hasWakeups()) {
1248 return b;
1249 }
1250 }
1251 return null;
1252 }
1253
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001254 long getNextWakeFromIdleTimeImpl() {
1255 synchronized (mLock) {
1256 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
1257 }
1258 }
1259
1260 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001261 synchronized (mLock) {
1262 return mNextAlarmClockForUser.get(userId);
1263 }
1264 }
1265
1266 /**
1267 * Recomputes the next alarm clock for all users.
1268 */
1269 private void updateNextAlarmClockLocked() {
1270 if (!mNextAlarmClockMayChange) {
1271 return;
1272 }
1273 mNextAlarmClockMayChange = false;
1274
Jose Lima235510e2014-08-13 12:50:01 -07001275 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001276 nextForUser.clear();
1277
1278 final int N = mAlarmBatches.size();
1279 for (int i = 0; i < N; i++) {
1280 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
1281 final int M = alarms.size();
1282
1283 for (int j = 0; j < M; j++) {
1284 Alarm a = alarms.get(j);
1285 if (a.alarmClock != null) {
1286 final int userId = a.userId;
1287
1288 if (DEBUG_ALARM_CLOCK) {
1289 Log.v(TAG, "Found AlarmClockInfo at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001290 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02001291 " for user " + userId);
1292 }
1293
1294 // Alarms and batches are sorted by time, no need to compare times here.
1295 if (nextForUser.get(userId) == null) {
1296 nextForUser.put(userId, a.alarmClock);
1297 }
1298 }
1299 }
1300 }
1301
1302 // Update mNextAlarmForUser with new values.
1303 final int NN = nextForUser.size();
1304 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07001305 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001306 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001307 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001308 if (!newAlarm.equals(currentAlarm)) {
1309 updateNextAlarmInfoForUserLocked(userId, newAlarm);
1310 }
1311 }
1312
1313 // Remove users without any alarm clocks scheduled.
1314 final int NNN = mNextAlarmClockForUser.size();
1315 for (int i = NNN - 1; i >= 0; i--) {
1316 int userId = mNextAlarmClockForUser.keyAt(i);
1317 if (nextForUser.get(userId) == null) {
1318 updateNextAlarmInfoForUserLocked(userId, null);
1319 }
1320 }
1321 }
1322
Jose Lima235510e2014-08-13 12:50:01 -07001323 private void updateNextAlarmInfoForUserLocked(int userId,
1324 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001325 if (alarmClock != null) {
1326 if (DEBUG_ALARM_CLOCK) {
1327 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001328 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02001329 }
1330 mNextAlarmClockForUser.put(userId, alarmClock);
1331 } else {
1332 if (DEBUG_ALARM_CLOCK) {
1333 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
1334 }
1335 mNextAlarmClockForUser.remove(userId);
1336 }
1337
1338 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
1339 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1340 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1341 }
1342
1343 /**
1344 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
1345 * for which alarm clocks have changed since the last call to this.
1346 *
1347 * Do not call with a lock held. Only call from mHandler's thread.
1348 *
1349 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
1350 */
1351 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07001352 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001353 pendingUsers.clear();
1354
1355 synchronized (mLock) {
1356 final int N = mPendingSendNextAlarmClockChangedForUser.size();
1357 for (int i = 0; i < N; i++) {
1358 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
1359 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
1360 }
1361 mPendingSendNextAlarmClockChangedForUser.clear();
1362 }
1363
1364 final int N = pendingUsers.size();
1365 for (int i = 0; i < N; i++) {
1366 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001367 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001368 Settings.System.putStringForUser(getContext().getContentResolver(),
1369 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01001370 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02001371 userId);
1372
1373 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
1374 new UserHandle(userId));
1375 }
1376 }
1377
1378 /**
1379 * Formats an alarm like platform/packages/apps/DeskClock used to.
1380 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01001381 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
1382 int userId) {
1383 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02001384 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
1385 return (info == null) ? "" :
1386 DateFormat.format(pattern, info.getTriggerTime()).toString();
1387 }
1388
Adam Lesinski182f73f2013-12-05 16:48:06 -08001389 void rescheduleKernelAlarmsLocked() {
1390 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
1391 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001392 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001393 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001394 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001395 final Batch firstBatch = mAlarmBatches.get(0);
Christopher Tatec83d3e42015-02-04 13:48:29 -08001396 // always update the kernel alarms, as a backstop against missed wakeups
1397 if (firstWakeup != null) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001398 mNextWakeup = firstWakeup.start;
1399 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001400 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001401 if (firstBatch != firstWakeup) {
1402 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001403 }
1404 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001405 if (mPendingNonWakeupAlarms.size() > 0) {
1406 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
1407 nextNonWakeup = mNextNonWakeupDeliveryTime;
1408 }
1409 }
Christopher Tatec83d3e42015-02-04 13:48:29 -08001410 // always update the kernel alarm, as a backstop against missed wakeups
1411 if (nextNonWakeup != 0) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001412 mNextNonWakeup = nextNonWakeup;
1413 setLocked(ELAPSED_REALTIME, nextNonWakeup);
1414 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001415 }
1416
1417 private void removeLocked(PendingIntent operation) {
1418 boolean didRemove = false;
1419 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1420 Batch b = mAlarmBatches.get(i);
1421 didRemove |= b.remove(operation);
1422 if (b.size() == 0) {
1423 mAlarmBatches.remove(i);
1424 }
1425 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001426 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1427 if (mPendingWhileIdleAlarms.get(i).operation.equals(operation)) {
1428 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1429 mPendingWhileIdleAlarms.remove(i);
1430 }
1431 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001432
1433 if (didRemove) {
1434 if (DEBUG_BATCH) {
1435 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
1436 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001437 boolean restorePending = false;
1438 if (mPendingIdleUntil != null && mPendingIdleUntil.operation.equals(operation)) {
1439 mPendingIdleUntil = null;
1440 restorePending = true;
1441 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001442 if (mNextWakeFromIdle != null && mNextWakeFromIdle.operation.equals(operation)) {
1443 mNextWakeFromIdle = null;
1444 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001445 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001446 if (restorePending) {
1447 restorePendingWhileIdleAlarmsLocked();
1448 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001449 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001450 }
1451 }
1452
1453 void removeLocked(String packageName) {
1454 boolean didRemove = false;
1455 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1456 Batch b = mAlarmBatches.get(i);
1457 didRemove |= b.remove(packageName);
1458 if (b.size() == 0) {
1459 mAlarmBatches.remove(i);
1460 }
1461 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001462 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1463 if (mPendingWhileIdleAlarms.get(i).operation.getTargetPackage().equals(packageName)) {
1464 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1465 mPendingWhileIdleAlarms.remove(i);
1466 }
1467 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001468
1469 if (didRemove) {
1470 if (DEBUG_BATCH) {
1471 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1472 }
1473 rebatchAllAlarmsLocked(true);
1474 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001475 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001476 }
1477 }
1478
1479 void removeUserLocked(int userHandle) {
1480 boolean didRemove = false;
1481 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1482 Batch b = mAlarmBatches.get(i);
1483 didRemove |= b.remove(userHandle);
1484 if (b.size() == 0) {
1485 mAlarmBatches.remove(i);
1486 }
1487 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001488 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1489 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).operation.getCreatorUid())
1490 == userHandle) {
1491 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1492 mPendingWhileIdleAlarms.remove(i);
1493 }
1494 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001495
1496 if (didRemove) {
1497 if (DEBUG_BATCH) {
1498 Slog.v(TAG, "remove(user) changed bounds; rebatching");
1499 }
1500 rebatchAllAlarmsLocked(true);
1501 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001502 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001503 }
1504 }
1505
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001506 void interactiveStateChangedLocked(boolean interactive) {
1507 if (mInteractive != interactive) {
1508 mInteractive = interactive;
1509 final long nowELAPSED = SystemClock.elapsedRealtime();
1510 if (interactive) {
1511 if (mPendingNonWakeupAlarms.size() > 0) {
1512 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1513 mTotalDelayTime += thisDelayTime;
1514 if (mMaxDelayTime < thisDelayTime) {
1515 mMaxDelayTime = thisDelayTime;
1516 }
1517 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
1518 mPendingNonWakeupAlarms.clear();
1519 }
1520 if (mNonInteractiveStartTime > 0) {
1521 long dur = nowELAPSED - mNonInteractiveStartTime;
1522 if (dur > mNonInteractiveTime) {
1523 mNonInteractiveTime = dur;
1524 }
1525 }
1526 } else {
1527 mNonInteractiveStartTime = nowELAPSED;
1528 }
1529 }
1530 }
1531
Adam Lesinski182f73f2013-12-05 16:48:06 -08001532 boolean lookForPackageLocked(String packageName) {
1533 for (int i = 0; i < mAlarmBatches.size(); i++) {
1534 Batch b = mAlarmBatches.get(i);
1535 if (b.hasPackage(packageName)) {
1536 return true;
1537 }
1538 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001539 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
1540 if (mPendingWhileIdleAlarms.get(i).operation.getTargetPackage().equals(packageName)) {
1541 return true;
1542 }
1543 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001544 return false;
1545 }
1546
1547 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001548 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001549 // The kernel never triggers alarms with negative wakeup times
1550 // so we ensure they are positive.
1551 long alarmSeconds, alarmNanoseconds;
1552 if (when < 0) {
1553 alarmSeconds = 0;
1554 alarmNanoseconds = 0;
1555 } else {
1556 alarmSeconds = when / 1000;
1557 alarmNanoseconds = (when % 1000) * 1000 * 1000;
1558 }
1559
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001560 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001561 } else {
1562 Message msg = Message.obtain();
1563 msg.what = ALARM_EVENT;
1564
1565 mHandler.removeMessages(ALARM_EVENT);
1566 mHandler.sendMessageAtTime(msg, when);
1567 }
1568 }
1569
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001570 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001571 String prefix, String label, long nowRTC, long nowELAPSED, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 for (int i=list.size()-1; i>=0; i--) {
1573 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001574 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1575 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001576 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 }
1578 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001579
1580 private static final String labelForType(int type) {
1581 switch (type) {
1582 case RTC: return "RTC";
1583 case RTC_WAKEUP : return "RTC_WAKEUP";
1584 case ELAPSED_REALTIME : return "ELAPSED";
1585 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
1586 default:
1587 break;
1588 }
1589 return "--unknown--";
1590 }
1591
1592 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001593 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001594 for (int i=list.size()-1; i>=0; i--) {
1595 Alarm a = list.get(i);
1596 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001597 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1598 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001599 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001600 }
1601 }
1602
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001603 private native long init();
1604 private native void close(long nativeData);
1605 private native void set(long nativeData, int type, long seconds, long nanoseconds);
1606 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08001607 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001608 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001610 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001611 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001612 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001613 // batches are temporally sorted, so we need only pull from the
1614 // start of the list until we either empty it or hit a batch
1615 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07001616 while (mAlarmBatches.size() > 0) {
1617 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001618 if (batch.start > nowELAPSED) {
1619 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 break;
1621 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622
Christopher Tatee0a22b32013-07-11 14:43:13 -07001623 // We will (re)schedule some alarms now; don't let that interfere
1624 // with delivery of this current batch
1625 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001626
Christopher Tatee0a22b32013-07-11 14:43:13 -07001627 final int N = batch.size();
1628 for (int i = 0; i < N; i++) {
1629 Alarm alarm = batch.get(i);
1630 alarm.count = 1;
1631 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001632 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1633 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
1634 alarm.tag);
1635 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001636 if (mPendingIdleUntil == alarm) {
1637 mPendingIdleUntil = null;
1638 rebatchAllAlarmsLocked(false);
1639 restorePendingWhileIdleAlarmsLocked();
1640 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001641 if (mNextWakeFromIdle == alarm) {
1642 mNextWakeFromIdle = null;
1643 rebatchAllAlarmsLocked(false);
1644 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001645
1646 // Recurring alarms may have passed several alarm intervals while the
1647 // phone was asleep or off, so pass a trigger count when sending them.
1648 if (alarm.repeatInterval > 0) {
1649 // this adjustment will be zero if we're late by
1650 // less than one full repeat interval
1651 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
1652
1653 // Also schedule its next recurrence
1654 final long delta = alarm.count * alarm.repeatInterval;
1655 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07001656 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07001657 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001658 alarm.repeatInterval, alarm.operation, alarm.flags, true,
Adrian Roosc42a1e12014-07-07 23:35:53 +02001659 alarm.workSource, alarm.alarmClock, alarm.userId);
Christopher Tate864d42e2014-12-02 11:48:53 -08001660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661
Christopher Tate864d42e2014-12-02 11:48:53 -08001662 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001663 hasWakeup = true;
1664 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001665
1666 // We removed an alarm clock. Let the caller recompute the next alarm clock.
1667 if (alarm.alarmClock != null) {
1668 mNextAlarmClockMayChange = true;
1669 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07001670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001672
Christopher Tate1590f1e2014-10-02 17:27:57 -07001673 // This is a new alarm delivery set; bump the sequence number to indicate that
1674 // all apps' alarm delivery classes should be recalculated.
1675 mCurrentSeq++;
1676 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001677 Collections.sort(triggerList, mAlarmDispatchComparator);
1678
1679 if (localLOGV) {
1680 for (int i=0; i<triggerList.size(); i++) {
1681 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
1682 }
1683 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001684
1685 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 /**
1689 * This Comparator sorts Alarms into increasing time order.
1690 */
1691 public static class IncreasingTimeOrder implements Comparator<Alarm> {
1692 public int compare(Alarm a1, Alarm a2) {
1693 long when1 = a1.when;
1694 long when2 = a2.when;
1695 if (when1 - when2 > 0) {
1696 return 1;
1697 }
1698 if (when1 - when2 < 0) {
1699 return -1;
1700 }
1701 return 0;
1702 }
1703 }
1704
1705 private static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001706 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001707 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001708 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001709 public final PendingIntent operation;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001710 public final String tag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001711 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001712 public final int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001713 public int count;
1714 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07001715 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001716 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001717 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 public long repeatInterval;
Jose Lima235510e2014-08-13 12:50:01 -07001719 public final AlarmManager.AlarmClockInfo alarmClock;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001720 public final int userId;
Christopher Tate1590f1e2014-10-02 17:27:57 -07001721 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001722
Christopher Tate3e04b472013-10-21 17:51:31 -07001723 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001724 long _interval, PendingIntent _op, WorkSource _ws, int _flags,
Jose Lima235510e2014-08-13 12:50:01 -07001725 AlarmManager.AlarmClockInfo _info, int _userId) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001726 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001727 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001728 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
1729 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001730 when = _when;
1731 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07001732 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001733 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001734 repeatInterval = _interval;
1735 operation = _op;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001736 tag = makeTag(_op, _type);
David Christieebe51fc2013-07-26 13:23:29 -07001737 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001738 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001739 alarmClock = _info;
1740 userId = _userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001741 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001742
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001743 public static String makeTag(PendingIntent pi, int type) {
1744 return pi.getTag(type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
1745 ? "*walarm*:" : "*alarm*:");
1746 }
1747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001749 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001750 StringBuilder sb = new StringBuilder(128);
1751 sb.append("Alarm{");
1752 sb.append(Integer.toHexString(System.identityHashCode(this)));
1753 sb.append(" type ");
1754 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001755 sb.append(" when ");
1756 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001757 sb.append(" ");
1758 sb.append(operation.getTargetPackage());
1759 sb.append('}');
1760 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 }
1762
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001763 public void dump(PrintWriter pw, String prefix, long nowRTC, long nowELAPSED,
1764 SimpleDateFormat sdf) {
1765 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
1766 pw.print(prefix); pw.print("tag="); pw.println(tag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001767 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001768 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
1769 nowELAPSED, pw);
1770 if (isRtc) {
1771 pw.print(" when="); pw.print(sdf.format(new Date(when)));
1772 } else {
1773 pw.print(" when="); TimeUtils.formatDuration(when, nowELAPSED, pw);
1774 }
1775 pw.println();
1776 pw.print(prefix); pw.print("window="); pw.print(windowLength);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001777 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001778 pw.print(" count="); pw.print(count);
1779 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001780 if (alarmClock != null) {
1781 pw.print(prefix); pw.println("Alarm clock:");
1782 pw.print(prefix); pw.print(" triggerTime=");
1783 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
1784 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
1785 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001786 pw.print(prefix); pw.print("operation="); pw.println(operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 }
1788 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001789
Christopher Tatee0a22b32013-07-11 14:43:13 -07001790 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
1791 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07001792 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
1793 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001794 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07001795 break;
1796 }
1797
Christopher Tatee0a22b32013-07-11 14:43:13 -07001798 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07001799 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
1800 Alarm a = b.alarms.get(nextAlarm);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001801 WakeupEvent e = new WakeupEvent(nowRTC,
1802 a.operation.getCreatorUid(),
1803 a.operation.getIntent().getAction());
1804 mRecentWakeups.add(e);
1805 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001806 }
1807 }
1808
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001809 long currentNonWakeupFuzzLocked(long nowELAPSED) {
1810 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
1811 if (timeSinceOn < 5*60*1000) {
1812 // If the screen has been off for 5 minutes, only delay by at most two minutes.
1813 return 2*60*1000;
1814 } else if (timeSinceOn < 30*60*1000) {
1815 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
1816 return 15*60*1000;
1817 } else {
1818 // Otherwise, we will delay by at most an hour.
1819 return 60*60*1000;
1820 }
1821 }
1822
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001823 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001824 if (duration < 15*60*1000) {
1825 // If the duration until the time is less than 15 minutes, the maximum fuzz
1826 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001827 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001828 } else if (duration < 90*60*1000) {
1829 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
1830 return 15*60*1000;
1831 } else {
1832 // Otherwise, we will fuzz by at most half an hour.
1833 return 30*60*1000;
1834 }
1835 }
1836
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001837 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
1838 if (mInteractive) {
1839 return false;
1840 }
1841 if (mLastAlarmDeliveryTime <= 0) {
1842 return false;
1843 }
minho.choo649acab2014-12-12 16:13:55 +09001844 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001845 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
1846 // and the next delivery time is in the past, then just deliver them all. This
1847 // avoids bugs where we get stuck in a loop trying to poll for alarms.
1848 return false;
1849 }
1850 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
1851 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
1852 }
1853
1854 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
1855 mLastAlarmDeliveryTime = nowELAPSED;
1856 for (int i=0; i<triggerList.size(); i++) {
1857 Alarm alarm = triggerList.get(i);
1858 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07001859 if (localLOGV) {
1860 Slog.v(TAG, "sending alarm " + alarm);
1861 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07001862 if (RECORD_ALARMS_IN_HISTORY) {
1863 if (alarm.workSource != null && alarm.workSource.size() > 0) {
1864 for (int wi=0; wi<alarm.workSource.size(); wi++) {
1865 ActivityManagerNative.noteAlarmStart(
1866 alarm.operation, alarm.workSource.get(wi), alarm.tag);
1867 }
1868 } else {
1869 ActivityManagerNative.noteAlarmStart(
1870 alarm.operation, -1, alarm.tag);
1871 }
1872 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001873 alarm.operation.send(getContext(), 0,
1874 mBackgroundIntent.putExtra(
1875 Intent.EXTRA_ALARM_COUNT, alarm.count),
1876 mResultReceiver, mHandler);
1877
1878 // we have an active broadcast so stay awake.
1879 if (mBroadcastRefCount == 0) {
1880 setWakelockWorkSource(alarm.operation, alarm.workSource,
1881 alarm.type, alarm.tag, true);
1882 mWakeLock.acquire();
1883 }
1884 final InFlight inflight = new InFlight(AlarmManagerService.this,
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001885 alarm.operation, alarm.workSource, alarm.type, alarm.tag, nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001886 mInFlight.add(inflight);
1887 mBroadcastRefCount++;
1888
1889 final BroadcastStats bs = inflight.mBroadcastStats;
1890 bs.count++;
1891 if (bs.nesting == 0) {
1892 bs.nesting = 1;
1893 bs.startTime = nowELAPSED;
1894 } else {
1895 bs.nesting++;
1896 }
1897 final FilterStats fs = inflight.mFilterStats;
1898 fs.count++;
1899 if (fs.nesting == 0) {
1900 fs.nesting = 1;
1901 fs.startTime = nowELAPSED;
1902 } else {
1903 fs.nesting++;
1904 }
1905 if (alarm.type == ELAPSED_REALTIME_WAKEUP
1906 || alarm.type == RTC_WAKEUP) {
1907 bs.numWakeup++;
1908 fs.numWakeup++;
1909 if (alarm.workSource != null && alarm.workSource.size() > 0) {
1910 for (int wi=0; wi<alarm.workSource.size(); wi++) {
1911 ActivityManagerNative.noteWakeupAlarm(
1912 alarm.operation, alarm.workSource.get(wi),
Dianne Hackborn1e383822015-04-10 14:02:33 -07001913 alarm.workSource.getName(wi), alarm.tag);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001914 }
1915 } else {
1916 ActivityManagerNative.noteWakeupAlarm(
Dianne Hackborn1e383822015-04-10 14:02:33 -07001917 alarm.operation, -1, null, alarm.tag);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001918 }
1919 }
1920 } catch (PendingIntent.CanceledException e) {
1921 if (alarm.repeatInterval > 0) {
1922 // This IntentSender is no longer valid, but this
1923 // is a repeating alarm, so toss the hoser.
1924 removeImpl(alarm.operation);
1925 }
1926 } catch (RuntimeException e) {
1927 Slog.w(TAG, "Failure sending alarm.", e);
1928 }
1929 }
1930 }
1931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001932 private class AlarmThread extends Thread
1933 {
1934 public AlarmThread()
1935 {
1936 super("AlarmManager");
1937 }
1938
1939 public void run()
1940 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07001941 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
1942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 while (true)
1944 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001945 int result = waitForAlarm(mNativeData);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001946
1947 triggerList.clear();
1948
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001949 if ((result & TIME_CHANGED_MASK) != 0) {
Christopher Tate385e4982013-07-23 18:22:29 -07001950 if (DEBUG_BATCH) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001951 Slog.v(TAG, "Time changed notification from kernel; rebatching");
Christopher Tate385e4982013-07-23 18:22:29 -07001952 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001953 removeImpl(mTimeTickSender);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001954 rebatchAllAlarms();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001955 mClockReceiver.scheduleTimeTickEvent();
Dianne Hackborn998e6082014-09-11 19:13:23 -07001956 synchronized (mLock) {
1957 mNumTimeChanged++;
1958 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001959 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
Dianne Hackborn89ba6752011-01-23 16:51:16 -08001960 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1961 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001962 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001963 }
1964
1965 synchronized (mLock) {
1966 final long nowRTC = System.currentTimeMillis();
1967 final long nowELAPSED = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001968 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 TAG, "Checking for alarms... rtc=" + nowRTC
1970 + ", elapsed=" + nowELAPSED);
1971
Christopher Tate18a75f12013-07-01 18:18:59 -07001972 if (WAKEUP_STATS) {
1973 if ((result & IS_WAKEUP_MASK) != 0) {
1974 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
1975 int n = 0;
1976 for (WakeupEvent event : mRecentWakeups) {
1977 if (event.when > newEarliest) break;
1978 n++; // number of now-stale entries at the list head
1979 }
1980 for (int i = 0; i < n; i++) {
1981 mRecentWakeups.remove();
1982 }
1983
Christopher Tatee0a22b32013-07-11 14:43:13 -07001984 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Christopher Tate18a75f12013-07-01 18:18:59 -07001985 }
1986 }
1987
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001988 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
1989 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
1990 // if there are no wakeup alarms and the screen is off, we can
1991 // delay what we have so far until the future.
1992 if (mPendingNonWakeupAlarms.size() == 0) {
1993 mStartCurrentDelayTime = nowELAPSED;
1994 mNextNonWakeupDeliveryTime = nowELAPSED
1995 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001997 mPendingNonWakeupAlarms.addAll(triggerList);
1998 mNumDelayedAlarms += triggerList.size();
1999 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002000 updateNextAlarmClockLocked();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002001 } else {
2002 // now deliver the alarm intents; if there are pending non-wakeup
2003 // alarms, we need to merge them in to the list. note we don't
2004 // just deliver them first because we generally want non-wakeup
2005 // alarms delivered after wakeup alarms.
2006 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002007 updateNextAlarmClockLocked();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002008 if (mPendingNonWakeupAlarms.size() > 0) {
Christopher Tate1590f1e2014-10-02 17:27:57 -07002009 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002010 triggerList.addAll(mPendingNonWakeupAlarms);
2011 Collections.sort(triggerList, mAlarmDispatchComparator);
2012 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2013 mTotalDelayTime += thisDelayTime;
2014 if (mMaxDelayTime < thisDelayTime) {
2015 mMaxDelayTime = thisDelayTime;
2016 }
2017 mPendingNonWakeupAlarms.clear();
2018 }
2019 deliverAlarmsLocked(triggerList, nowELAPSED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002020 }
2021 }
2022 }
2023 }
2024 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002025
David Christieebe51fc2013-07-26 13:23:29 -07002026 /**
2027 * Attribute blame for a WakeLock.
2028 * @param pi PendingIntent to attribute blame to if ws is null.
2029 * @param ws WorkSource to attribute blame.
2030 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002031 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
2032 boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07002033 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002034 final boolean unimportant = pi == mTimeTickSender;
2035 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002036 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002037 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002038 } else {
2039 mWakeLock.setHistoryTag(null);
2040 }
2041 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07002042 if (ws != null) {
2043 mWakeLock.setWorkSource(ws);
2044 return;
2045 }
2046
Christopher Tatec4a07d12012-04-06 14:19:13 -07002047 final int uid = ActivityManagerNative.getDefault()
2048 .getUidForIntentSender(pi.getTarget());
2049 if (uid >= 0) {
2050 mWakeLock.setWorkSource(new WorkSource(uid));
2051 return;
2052 }
2053 } catch (Exception e) {
2054 }
2055
2056 // Something went wrong; fall back to attributing the lock to the OS
2057 mWakeLock.setWorkSource(null);
2058 }
2059
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 private class AlarmHandler extends Handler {
2061 public static final int ALARM_EVENT = 1;
2062 public static final int MINUTE_CHANGE_EVENT = 2;
2063 public static final int DATE_CHANGE_EVENT = 3;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002064 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002065
2066 public AlarmHandler() {
2067 }
2068
2069 public void handleMessage(Message msg) {
2070 if (msg.what == ALARM_EVENT) {
2071 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2072 synchronized (mLock) {
2073 final long nowRTC = System.currentTimeMillis();
Christopher Tatee0a22b32013-07-11 14:43:13 -07002074 final long nowELAPSED = SystemClock.elapsedRealtime();
2075 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002076 updateNextAlarmClockLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002077 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079 // now trigger the alarms without the lock held
Dianne Hackborn390517b2013-05-30 15:03:32 -07002080 for (int i=0; i<triggerList.size(); i++) {
2081 Alarm alarm = triggerList.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002082 try {
2083 alarm.operation.send();
2084 } catch (PendingIntent.CanceledException e) {
2085 if (alarm.repeatInterval > 0) {
2086 // This IntentSender is no longer valid, but this
2087 // is a repeating alarm, so toss the hoser.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002088 removeImpl(alarm.operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 }
2090 }
2091 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002092 } else if (msg.what == SEND_NEXT_ALARM_CLOCK_CHANGED) {
2093 sendNextAlarmClockChanged();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002094 }
2095 }
2096 }
2097
2098 class ClockReceiver extends BroadcastReceiver {
2099 public ClockReceiver() {
2100 IntentFilter filter = new IntentFilter();
2101 filter.addAction(Intent.ACTION_TIME_TICK);
2102 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002103 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002104 }
2105
2106 @Override
2107 public void onReceive(Context context, Intent intent) {
2108 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07002109 if (DEBUG_BATCH) {
2110 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
2111 }
2112 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002113 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
2114 // Since the kernel does not keep track of DST, we need to
2115 // reset the TZ information at the beginning of each day
2116 // based off of the current Zone gmt offset + userspace tracked
2117 // daylight savings information.
2118 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02002119 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002120 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07002121 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002122 }
2123 }
2124
2125 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07002126 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09002127 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07002128
2129 // Schedule this event for the amount of time that it would take to get to
2130 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09002131 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07002132
David Christieebe51fc2013-07-26 13:23:29 -07002133 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002134 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002135 0, mTimeTickSender, AlarmManager.FLAG_STANDALONE, workSource, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002136 }
Christopher Tate385e4982013-07-23 18:22:29 -07002137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002138 public void scheduleDateChangedEvent() {
2139 Calendar calendar = Calendar.getInstance();
2140 calendar.setTimeInMillis(System.currentTimeMillis());
2141 calendar.set(Calendar.HOUR, 0);
2142 calendar.set(Calendar.MINUTE, 0);
2143 calendar.set(Calendar.SECOND, 0);
2144 calendar.set(Calendar.MILLISECOND, 0);
2145 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07002146
2147 final WorkSource workSource = null; // Let system take blame for date change events.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002148 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender,
2149 AlarmManager.FLAG_STANDALONE, workSource, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002150 }
2151 }
2152
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002153 class InteractiveStateReceiver extends BroadcastReceiver {
2154 public InteractiveStateReceiver() {
2155 IntentFilter filter = new IntentFilter();
2156 filter.addAction(Intent.ACTION_SCREEN_OFF);
2157 filter.addAction(Intent.ACTION_SCREEN_ON);
2158 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
2159 getContext().registerReceiver(this, filter);
2160 }
2161
2162 @Override
2163 public void onReceive(Context context, Intent intent) {
2164 synchronized (mLock) {
2165 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
2166 }
2167 }
2168 }
2169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002170 class UninstallReceiver extends BroadcastReceiver {
2171 public UninstallReceiver() {
2172 IntentFilter filter = new IntentFilter();
2173 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2174 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002175 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08002177 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002178 // Register for events related to sdcard installation.
2179 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08002180 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002181 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002182 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002183 }
2184
2185 @Override
2186 public void onReceive(Context context, Intent intent) {
2187 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002188 String action = intent.getAction();
2189 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002190 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
2191 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
2192 for (String packageName : pkgList) {
2193 if (lookForPackageLocked(packageName)) {
2194 setResultCode(Activity.RESULT_OK);
2195 return;
2196 }
2197 }
2198 return;
2199 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002200 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002201 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
2202 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
2203 if (userHandle >= 0) {
2204 removeUserLocked(userHandle);
2205 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002206 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08002207 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
2208 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
2209 // This package is being updated; don't kill its alarms.
2210 return;
2211 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002212 Uri data = intent.getData();
2213 if (data != null) {
2214 String pkg = data.getSchemeSpecificPart();
2215 if (pkg != null) {
2216 pkgList = new String[]{pkg};
2217 }
2218 }
2219 }
2220 if (pkgList != null && (pkgList.length > 0)) {
2221 for (String pkg : pkgList) {
2222 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07002223 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002224 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
2225 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
2226 if (uidStats.remove(pkg) != null) {
2227 if (uidStats.size() <= 0) {
2228 mBroadcastStats.removeAt(i);
2229 }
2230 }
2231 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002232 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002233 }
2234 }
2235 }
2236 }
2237
2238 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002239 String pkg = pi.getCreatorPackage();
2240 int uid = pi.getCreatorUid();
2241 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
2242 if (uidStats == null) {
2243 uidStats = new ArrayMap<String, BroadcastStats>();
2244 mBroadcastStats.put(uid, uidStats);
2245 }
2246 BroadcastStats bs = uidStats.get(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002247 if (bs == null) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002248 bs = new BroadcastStats(uid, pkg);
2249 uidStats.put(pkg, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002250 }
2251 return bs;
2252 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002254 class ResultReceiver implements PendingIntent.OnFinished {
2255 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
2256 String resultData, Bundle resultExtras) {
2257 synchronized (mLock) {
Dianne Hackborn81038902012-11-26 17:04:09 -08002258 InFlight inflight = null;
2259 for (int i=0; i<mInFlight.size(); i++) {
2260 if (mInFlight.get(i).mPendingIntent == pi) {
2261 inflight = mInFlight.remove(i);
2262 break;
2263 }
2264 }
2265 if (inflight != null) {
2266 final long nowELAPSED = SystemClock.elapsedRealtime();
2267 BroadcastStats bs = inflight.mBroadcastStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002268 bs.nesting--;
2269 if (bs.nesting <= 0) {
2270 bs.nesting = 0;
Dianne Hackborn81038902012-11-26 17:04:09 -08002271 bs.aggregateTime += nowELAPSED - bs.startTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002272 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002273 FilterStats fs = inflight.mFilterStats;
2274 fs.nesting--;
2275 if (fs.nesting <= 0) {
2276 fs.nesting = 0;
2277 fs.aggregateTime += nowELAPSED - fs.startTime;
2278 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07002279 if (RECORD_ALARMS_IN_HISTORY) {
2280 if (inflight.mWorkSource != null && inflight.mWorkSource.size() > 0) {
2281 for (int wi=0; wi<inflight.mWorkSource.size(); wi++) {
2282 ActivityManagerNative.noteAlarmFinish(
2283 pi, inflight.mWorkSource.get(wi), inflight.mTag);
2284 }
2285 } else {
2286 ActivityManagerNative.noteAlarmFinish(
2287 pi, -1, inflight.mTag);
2288 }
2289 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002290 } else {
2291 mLog.w("No in-flight alarm for " + pi + " " + intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002292 }
2293 mBroadcastRefCount--;
2294 if (mBroadcastRefCount == 0) {
2295 mWakeLock.release();
Dianne Hackborn81038902012-11-26 17:04:09 -08002296 if (mInFlight.size() > 0) {
2297 mLog.w("Finished all broadcasts with " + mInFlight.size()
2298 + " remaining inflights");
2299 for (int i=0; i<mInFlight.size(); i++) {
2300 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
2301 }
2302 mInFlight.clear();
2303 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002304 } else {
2305 // the next of our alarms is now in flight. reattribute the wakelock.
Dianne Hackborn81038902012-11-26 17:04:09 -08002306 if (mInFlight.size() > 0) {
David Christieebe51fc2013-07-26 13:23:29 -07002307 InFlight inFlight = mInFlight.get(0);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08002308 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002309 inFlight.mAlarmType, inFlight.mTag, false);
Christopher Tatec4a07d12012-04-06 14:19:13 -07002310 } else {
2311 // should never happen
Dianne Hackborn81038902012-11-26 17:04:09 -08002312 mLog.w("Alarm wakelock still held but sent queue empty");
Christopher Tatec4a07d12012-04-06 14:19:13 -07002313 mWakeLock.setWorkSource(null);
2314 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002315 }
2316 }
2317 }
2318 }
2319}