blob: 0c555c5f146eddd2581ec42a06870acda4c1d515 [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;
37import android.os.SystemClock;
38import android.os.SystemProperties;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070039import android.os.UserHandle;
Christopher Tatec4a07d12012-04-06 14:19:13 -070040import android.os.WorkSource;
Adrian Roosc42a1e12014-07-07 23:35:53 +020041import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.text.TextUtils;
Adrian Roosc42a1e12014-07-07 23:35:53 +020043import android.text.format.DateFormat;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080044import android.util.ArrayMap;
Adrian Roosc42a1e12014-07-07 23:35:53 +020045import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080046import android.util.Slog;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080047import android.util.SparseArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +020048import android.util.SparseBooleanArray;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070049import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050
Christopher Tate4cb338d2013-07-26 13:11:31 -070051import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import java.io.FileDescriptor;
53import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070054import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -080056import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import java.util.Calendar;
58import java.util.Collections;
59import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -050060import java.util.Date;
Christopher Tate1590f1e2014-10-02 17:27:57 -070061import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -070062import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +020063import java.util.Locale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import java.util.TimeZone;
65
Christopher Tatee0a22b32013-07-11 14:43:13 -070066import static android.app.AlarmManager.RTC_WAKEUP;
67import static android.app.AlarmManager.RTC;
68import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
69import static android.app.AlarmManager.ELAPSED_REALTIME;
70
Dianne Hackborn81038902012-11-26 17:04:09 -080071import com.android.internal.util.LocalLog;
72
Adam Lesinski182f73f2013-12-05 16:48:06 -080073class AlarmManagerService extends SystemService {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074 // The threshold for how long an alarm can be late before we print a
75 // warning message. The time duration is in milliseconds.
76 private static final long LATE_ALARM_THRESHOLD = 10 * 1000;
Christopher Tatee0a22b32013-07-11 14:43:13 -070077
78 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
79 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -080080 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -070081 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -080082 static final int TIME_CHANGED_MASK = 1 << 16;
83 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -080084
Christopher Tatee0a22b32013-07-11 14:43:13 -070085 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -080086 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -080087
Adam Lesinski182f73f2013-12-05 16:48:06 -080088 static final String TAG = "AlarmManager";
89 static final String ClockReceiver_TAG = "ClockReceiver";
90 static final boolean localLOGV = false;
91 static final boolean DEBUG_BATCH = localLOGV || false;
92 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +020093 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Adam Lesinski182f73f2013-12-05 16:48:06 -080094 static final int ALARM_EVENT = 1;
95 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +020096
Adam Lesinski182f73f2013-12-05 16:48:06 -080097 static final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -080099 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100
Adam Lesinski182f73f2013-12-05 16:48:06 -0800101 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700102
Adrian Roosc42a1e12014-07-07 23:35:53 +0200103 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT = new Intent(
104 AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED);
105
Adam Lesinski182f73f2013-12-05 16:48:06 -0800106 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800107
Adam Lesinski182f73f2013-12-05 16:48:06 -0800108 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800109
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800110 long mNativeData;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700111 private long mNextWakeup;
112 private long mNextNonWakeup;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800113 int mBroadcastRefCount = 0;
114 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700115 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700116 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<Alarm>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800117 ArrayList<InFlight> mInFlight = new ArrayList<InFlight>();
118 final AlarmHandler mHandler = new AlarmHandler();
119 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700120 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 private UninstallReceiver mUninstallReceiver;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800122 final ResultReceiver mResultReceiver = new ResultReceiver();
123 PendingIntent mTimeTickSender;
124 PendingIntent mDateChangeSender;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700125 boolean mInteractive = true;
126 long mNonInteractiveStartTime;
127 long mNonInteractiveTime;
128 long mLastAlarmDeliveryTime;
129 long mStartCurrentDelayTime;
130 long mNextNonWakeupDeliveryTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700131 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800132
Jose Lima235510e2014-08-13 12:50:01 -0700133 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
134 new SparseArray<>();
135 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
136 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200137 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
138 new SparseBooleanArray();
139 private boolean mNextAlarmClockMayChange;
140
141 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700142 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
143 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200144
Christopher Tate1590f1e2014-10-02 17:27:57 -0700145 // Alarm delivery ordering bookkeeping
146 static final int PRIO_TICK = 0;
147 static final int PRIO_WAKEUP = 1;
148 static final int PRIO_NORMAL = 2;
149
150 class PriorityClass {
151 int seq;
152 int priority;
153
154 PriorityClass() {
155 seq = mCurrentSeq - 1;
156 priority = PRIO_NORMAL;
157 }
158 }
159
160 final HashMap<String, PriorityClass> mPriorities =
161 new HashMap<String, PriorityClass>();
162 int mCurrentSeq = 0;
163
Christopher Tate18a75f12013-07-01 18:18:59 -0700164 class WakeupEvent {
165 public long when;
166 public int uid;
167 public String action;
168
169 public WakeupEvent(long theTime, int theUid, String theAction) {
170 when = theTime;
171 uid = theUid;
172 action = theAction;
173 }
174 }
175
Adam Lesinski182f73f2013-12-05 16:48:06 -0800176 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
177 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700178
Adrian Roosc42a1e12014-07-07 23:35:53 +0200179 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700180 long start; // These endpoints are always in ELAPSED
181 long end;
182 boolean standalone; // certain "batches" don't participate in coalescing
183
184 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
185
186 Batch() {
187 start = 0;
188 end = Long.MAX_VALUE;
189 }
190
191 Batch(Alarm seed) {
192 start = seed.whenElapsed;
193 end = seed.maxWhen;
194 alarms.add(seed);
195 }
196
197 int size() {
198 return alarms.size();
199 }
200
201 Alarm get(int index) {
202 return alarms.get(index);
203 }
204
205 boolean canHold(long whenElapsed, long maxWhen) {
206 return (end >= whenElapsed) && (start <= maxWhen);
207 }
208
209 boolean add(Alarm alarm) {
210 boolean newStart = false;
211 // narrows the batch if necessary; presumes that canHold(alarm) is true
212 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
213 if (index < 0) {
214 index = 0 - index - 1;
215 }
216 alarms.add(index, alarm);
217 if (DEBUG_BATCH) {
218 Slog.v(TAG, "Adding " + alarm + " to " + this);
219 }
220 if (alarm.whenElapsed > start) {
221 start = alarm.whenElapsed;
222 newStart = true;
223 }
224 if (alarm.maxWhen < end) {
225 end = alarm.maxWhen;
226 }
227
228 if (DEBUG_BATCH) {
229 Slog.v(TAG, " => now " + this);
230 }
231 return newStart;
232 }
233
234 boolean remove(final PendingIntent operation) {
235 boolean didRemove = false;
236 long newStart = 0; // recalculate endpoints as we go
237 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700238 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700239 Alarm alarm = alarms.get(i);
240 if (alarm.operation.equals(operation)) {
241 alarms.remove(i);
242 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200243 if (alarm.alarmClock != null) {
244 mNextAlarmClockMayChange = true;
245 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700246 } else {
247 if (alarm.whenElapsed > newStart) {
248 newStart = alarm.whenElapsed;
249 }
250 if (alarm.maxWhen < newEnd) {
251 newEnd = alarm.maxWhen;
252 }
253 i++;
254 }
255 }
256 if (didRemove) {
257 // commit the new batch bounds
258 start = newStart;
259 end = newEnd;
260 }
261 return didRemove;
262 }
263
264 boolean remove(final String packageName) {
265 boolean didRemove = false;
266 long newStart = 0; // recalculate endpoints as we go
267 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700268 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700269 Alarm alarm = alarms.get(i);
270 if (alarm.operation.getTargetPackage().equals(packageName)) {
271 alarms.remove(i);
272 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200273 if (alarm.alarmClock != null) {
274 mNextAlarmClockMayChange = true;
275 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700276 } else {
277 if (alarm.whenElapsed > newStart) {
278 newStart = alarm.whenElapsed;
279 }
280 if (alarm.maxWhen < newEnd) {
281 newEnd = alarm.maxWhen;
282 }
283 i++;
284 }
285 }
286 if (didRemove) {
287 // commit the new batch bounds
288 start = newStart;
289 end = newEnd;
290 }
291 return didRemove;
292 }
293
294 boolean remove(final int userHandle) {
295 boolean didRemove = false;
296 long newStart = 0; // recalculate endpoints as we go
297 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700298 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700299 Alarm alarm = alarms.get(i);
300 if (UserHandle.getUserId(alarm.operation.getCreatorUid()) == userHandle) {
301 alarms.remove(i);
302 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200303 if (alarm.alarmClock != null) {
304 mNextAlarmClockMayChange = true;
305 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700306 } else {
307 if (alarm.whenElapsed > newStart) {
308 newStart = alarm.whenElapsed;
309 }
310 if (alarm.maxWhen < newEnd) {
311 newEnd = alarm.maxWhen;
312 }
313 i++;
314 }
315 }
316 if (didRemove) {
317 // commit the new batch bounds
318 start = newStart;
319 end = newEnd;
320 }
321 return didRemove;
322 }
323
324 boolean hasPackage(final String packageName) {
325 final int N = alarms.size();
326 for (int i = 0; i < N; i++) {
327 Alarm a = alarms.get(i);
328 if (a.operation.getTargetPackage().equals(packageName)) {
329 return true;
330 }
331 }
332 return false;
333 }
334
335 boolean hasWakeups() {
336 final int N = alarms.size();
337 for (int i = 0; i < N; i++) {
338 Alarm a = alarms.get(i);
339 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
340 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
341 return true;
342 }
343 }
344 return false;
345 }
346
347 @Override
348 public String toString() {
349 StringBuilder b = new StringBuilder(40);
350 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
351 b.append(" num="); b.append(size());
352 b.append(" start="); b.append(start);
353 b.append(" end="); b.append(end);
354 if (standalone) {
355 b.append(" STANDALONE");
356 }
357 b.append('}');
358 return b.toString();
359 }
360 }
361
362 static class BatchTimeOrder implements Comparator<Batch> {
363 public int compare(Batch b1, Batch b2) {
364 long when1 = b1.start;
365 long when2 = b2.start;
366 if (when1 - when2 > 0) {
367 return 1;
368 }
369 if (when1 - when2 < 0) {
370 return -1;
371 }
372 return 0;
373 }
374 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800375
376 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
377 @Override
378 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700379 // priority class trumps everything. TICK < WAKEUP < NORMAL
380 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
381 return -1;
382 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
383 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800384 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700385
386 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800387 if (lhs.whenElapsed < rhs.whenElapsed) {
388 return -1;
389 } else if (lhs.whenElapsed > rhs.whenElapsed) {
390 return 1;
391 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700392
393 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800394 return 0;
395 }
396 };
397
Christopher Tate1590f1e2014-10-02 17:27:57 -0700398 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
399 final int N = alarms.size();
400 for (int i = 0; i < N; i++) {
401 Alarm a = alarms.get(i);
402
403 final int alarmPrio;
404 if (Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
405 alarmPrio = PRIO_TICK;
406 } else if (a.wakeup) {
407 alarmPrio = PRIO_WAKEUP;
408 } else {
409 alarmPrio = PRIO_NORMAL;
410 }
411
412 PriorityClass packagePrio = a.priorityClass;
413 if (packagePrio == null) packagePrio = mPriorities.get(a.operation.getCreatorPackage());
414 if (packagePrio == null) {
415 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
416 mPriorities.put(a.operation.getCreatorPackage(), packagePrio);
417 }
418 a.priorityClass = packagePrio;
419
420 if (packagePrio.seq != mCurrentSeq) {
421 // first alarm we've seen in the current delivery generation from this package
422 packagePrio.priority = alarmPrio;
423 packagePrio.seq = mCurrentSeq;
424 } else {
425 // Multiple alarms from this package being delivered in this generation;
426 // bump the package's delivery class if it's warranted.
427 // TICK < WAKEUP < NORMAL
428 if (alarmPrio < packagePrio.priority) {
429 packagePrio.priority = alarmPrio;
430 }
431 }
432 }
433 }
434
Christopher Tatee0a22b32013-07-11 14:43:13 -0700435 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800436 static final long MIN_FUZZABLE_INTERVAL = 10000;
437 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
438 final ArrayList<Batch> mAlarmBatches = new ArrayList<Batch>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700439
Jeff Brownb880d882014-02-10 19:47:07 -0800440 public AlarmManagerService(Context context) {
441 super(context);
442 }
443
Christopher Tatee0a22b32013-07-11 14:43:13 -0700444 static long convertToElapsed(long when, int type) {
445 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
446 if (isRtc) {
447 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
448 }
449 return when;
450 }
451
452 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
453 // calculate the end of our nominal delivery window for the alarm.
454 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
455 // Current heuristic: batchable window is 75% of either the recurrence interval
456 // [for a periodic alarm] or of the time from now to the desired delivery time,
457 // with a minimum delay/interval of 10 seconds, under which we will simply not
458 // defer the alarm.
459 long futurity = (interval == 0)
460 ? (triggerAtTime - now)
461 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700462 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700463 futurity = 0;
464 }
465 return triggerAtTime + (long)(.75 * futurity);
466 }
467
468 // returns true if the batch was added at the head
469 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
470 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
471 if (index < 0) {
472 index = 0 - index - 1;
473 }
474 list.add(index, newBatch);
475 return (index == 0);
476 }
477
Christopher Tate385e4982013-07-23 18:22:29 -0700478 // Return the index of the matching batch, or -1 if none found.
479 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700480 final int N = mAlarmBatches.size();
481 for (int i = 0; i < N; i++) {
482 Batch b = mAlarmBatches.get(i);
483 if (!b.standalone && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700484 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700485 }
486 }
Christopher Tate385e4982013-07-23 18:22:29 -0700487 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700488 }
489
490 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
491 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700492 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700493 rebatchAllAlarmsLocked(true);
494 }
495 }
496
497 void rebatchAllAlarmsLocked(boolean doValidate) {
498 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
499 mAlarmBatches.clear();
500 final long nowElapsed = SystemClock.elapsedRealtime();
501 final int oldBatches = oldSet.size();
502 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
503 Batch batch = oldSet.get(batchNum);
504 final int N = batch.size();
505 for (int i = 0; i < N; i++) {
506 Alarm a = batch.get(i);
507 long whenElapsed = convertToElapsed(a.when, a.type);
Christopher Tate3e04b472013-10-21 17:51:31 -0700508 final long maxElapsed;
509 if (a.whenElapsed == a.maxWhen) {
510 // Exact
511 maxElapsed = whenElapsed;
512 } else {
513 // Not exact. Preserve any explicit window, otherwise recalculate
514 // the window based on the alarm's new futurity. Note that this
515 // reflects a policy of preferring timely to deferred delivery.
516 maxElapsed = (a.windowLength > 0)
517 ? (whenElapsed + a.windowLength)
518 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
519 }
520 setImplLocked(a.type, a.when, whenElapsed, a.windowLength, maxElapsed,
Adrian Roosc42a1e12014-07-07 23:35:53 +0200521 a.repeatInterval, a.operation, batch.standalone, doValidate, a.workSource,
522 a.alarmClock, a.userId);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700523 }
524 }
525 }
526
Adam Lesinski182f73f2013-12-05 16:48:06 -0800527 static final class InFlight extends Intent {
Dianne Hackborn81038902012-11-26 17:04:09 -0800528 final PendingIntent mPendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700529 final WorkSource mWorkSource;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700530 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800531 final BroadcastStats mBroadcastStats;
532 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800533 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800534
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800535 InFlight(AlarmManagerService service, PendingIntent pendingIntent, WorkSource workSource,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700536 int alarmType, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800537 mPendingIntent = pendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700538 mWorkSource = workSource;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700539 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800540 mBroadcastStats = service.getStatsLocked(pendingIntent);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700541 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -0800542 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700543 fs = new FilterStats(mBroadcastStats, mTag);
544 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -0800545 }
546 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800547 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800548 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800550
Adam Lesinski182f73f2013-12-05 16:48:06 -0800551 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -0800552 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700553 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800556 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800557 int numWakeup;
558 long startTime;
559 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -0800560
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700561 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800562 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700563 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800564 }
565 }
566
Adam Lesinski182f73f2013-12-05 16:48:06 -0800567 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800568 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800569 final String mPackageName;
570
571 long aggregateTime;
572 int count;
573 int numWakeup;
574 long startTime;
575 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700576 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -0800577
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800578 BroadcastStats(int uid, String packageName) {
579 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800580 mPackageName = packageName;
581 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800582 }
583
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800584 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
585 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700586
587 int mNumDelayedAlarms = 0;
588 long mTotalDelayTime = 0;
589 long mMaxDelayTime = 0;
590
Adam Lesinski182f73f2013-12-05 16:48:06 -0800591 @Override
592 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800593 mNativeData = init();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700594 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800595
596 // We have to set current TimeZone info to kernel
597 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -0800598 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800599
Adam Lesinski182f73f2013-12-05 16:48:06 -0800600 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800601 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800602
Adam Lesinski182f73f2013-12-05 16:48:06 -0800603 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700605 Intent.FLAG_RECEIVER_REGISTERED_ONLY
606 | Intent.FLAG_RECEIVER_FOREGROUND), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700607 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800608 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
609 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800610 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700611 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800612
613 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -0800614 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800615 mClockReceiver.scheduleTimeTickEvent();
616 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700617 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 mUninstallReceiver = new UninstallReceiver();
619
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800620 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800621 AlarmThread waitThread = new AlarmThread();
622 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800623 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800624 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800626
627 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800628 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800629
630 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800631 protected void finalize() throws Throwable {
632 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800633 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800634 } finally {
635 super.finalize();
636 }
637 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700638
Adam Lesinski182f73f2013-12-05 16:48:06 -0800639 void setTimeZoneImpl(String tz) {
640 if (TextUtils.isEmpty(tz)) {
641 return;
David Christieebe51fc2013-07-26 13:23:29 -0700642 }
643
Adam Lesinski182f73f2013-12-05 16:48:06 -0800644 TimeZone zone = TimeZone.getTimeZone(tz);
645 // Prevent reentrant calls from stepping on each other when writing
646 // the time zone property
647 boolean timeZoneWasChanged = false;
648 synchronized (this) {
649 String current = SystemProperties.get(TIMEZONE_PROPERTY);
650 if (current == null || !current.equals(zone.getID())) {
651 if (localLOGV) {
652 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
653 }
654 timeZoneWasChanged = true;
655 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
656 }
657
658 // Update the kernel timezone information
659 // Kernel tracks time offsets as 'minutes west of GMT'
660 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800661 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -0800662 }
663
664 TimeZone.setDefault(null);
665
666 if (timeZoneWasChanged) {
667 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
668 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
669 intent.putExtra("time-zone", zone.getID());
670 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
671 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700673
Adam Lesinski182f73f2013-12-05 16:48:06 -0800674 void removeImpl(PendingIntent operation) {
675 if (operation == null) {
676 return;
677 }
678 synchronized (mLock) {
679 removeLocked(operation);
680 }
681 }
682
683 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Adrian Roosc42a1e12014-07-07 23:35:53 +0200684 PendingIntent operation, boolean isStandalone, WorkSource workSource,
Jose Lima235510e2014-08-13 12:50:01 -0700685 AlarmManager.AlarmClockInfo alarmClock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800686 if (operation == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800687 Slog.w(TAG, "set/setRepeating ignored because there is no intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688 return;
689 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700690
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700691 // Sanity check the window length. This will catch people mistakenly
692 // trying to pass an end-of-window timestamp rather than a duration.
693 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
694 Slog.w(TAG, "Window length " + windowLength
695 + "ms suspiciously long; limiting to 1 hour");
696 windowLength = AlarmManager.INTERVAL_HOUR;
697 }
698
Christopher Tatee0a22b32013-07-11 14:43:13 -0700699 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
700 throw new IllegalArgumentException("Invalid alarm type " + type);
701 }
702
Christopher Tate5f221e82013-07-30 17:13:15 -0700703 if (triggerAtTime < 0) {
704 final long who = Binder.getCallingUid();
705 final long what = Binder.getCallingPid();
706 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + who
707 + " pid=" + what);
708 triggerAtTime = 0;
709 }
710
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700711 final long nowElapsed = SystemClock.elapsedRealtime();
712 final long triggerElapsed = convertToElapsed(triggerAtTime, type);
713 final long maxElapsed;
714 if (windowLength == AlarmManager.WINDOW_EXACT) {
715 maxElapsed = triggerElapsed;
716 } else if (windowLength < 0) {
717 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
718 } else {
719 maxElapsed = triggerElapsed + windowLength;
720 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700721
Adrian Roosc42a1e12014-07-07 23:35:53 +0200722 final int userId = UserHandle.getCallingUserId();
723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700725 if (DEBUG_BATCH) {
726 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700727 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -0700728 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
729 + " interval=" + interval + " standalone=" + isStandalone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730 }
Christopher Tate3e04b472013-10-21 17:51:31 -0700731 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Adrian Roosc42a1e12014-07-07 23:35:53 +0200732 interval, operation, isStandalone, true, workSource, alarmClock, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733 }
734 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735
Christopher Tate3e04b472013-10-21 17:51:31 -0700736 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
737 long maxWhen, long interval, PendingIntent operation, boolean isStandalone,
Jose Lima235510e2014-08-13 12:50:01 -0700738 boolean doValidate, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
739 int userId) {
Christopher Tate3e04b472013-10-21 17:51:31 -0700740 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Adrian Roosc42a1e12014-07-07 23:35:53 +0200741 operation, workSource, alarmClock, userId);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700742 removeLocked(operation);
Christopher Tateb8849c12011-02-08 13:39:01 -0800743
Christopher Tate385e4982013-07-23 18:22:29 -0700744 int whichBatch = (isStandalone) ? -1 : attemptCoalesceLocked(whenElapsed, maxWhen);
745 if (whichBatch < 0) {
746 Batch batch = new Batch(a);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700747 batch.standalone = isStandalone;
Christopher Tate7d57ed82013-10-25 20:18:03 -0700748 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800749 } else {
Christopher Tate385e4982013-07-23 18:22:29 -0700750 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -0700751 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700752 // The start time of this batch advanced, so batch ordering may
753 // have just been broken. Move it to where it now belongs.
754 mAlarmBatches.remove(whichBatch);
755 addBatchLocked(mAlarmBatches, batch);
756 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800757 }
758
Adrian Roosc42a1e12014-07-07 23:35:53 +0200759 if (alarmClock != null) {
760 mNextAlarmClockMayChange = true;
761 updateNextAlarmClockLocked();
762 }
763
Christopher Tate4cb338d2013-07-26 13:11:31 -0700764 if (DEBUG_VALIDATE) {
Christopher Tate5f221e82013-07-30 17:13:15 -0700765 if (doValidate && !validateConsistencyLocked()) {
766 Slog.v(TAG, "Tipping-point operation: type=" + type + " when=" + when
767 + " when(hex)=" + Long.toHexString(when)
768 + " whenElapsed=" + whenElapsed + " maxWhen=" + maxWhen
769 + " interval=" + interval + " op=" + operation
770 + " standalone=" + isStandalone);
Christopher Tate4cb338d2013-07-26 13:11:31 -0700771 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -0700772 }
773 }
774
Christopher Tate7d57ed82013-10-25 20:18:03 -0700775 rescheduleKernelAlarmsLocked();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700776 }
777
Adam Lesinski182f73f2013-12-05 16:48:06 -0800778 private final IBinder mService = new IAlarmManager.Stub() {
779 @Override
780 public void set(int type, long triggerAtTime, long windowLength, long interval,
Jose Lima235510e2014-08-13 12:50:01 -0700781 PendingIntent operation, WorkSource workSource,
782 AlarmManager.AlarmClockInfo alarmClock) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800783 if (workSource != null) {
784 getContext().enforceCallingPermission(
785 android.Manifest.permission.UPDATE_DEVICE_STATS,
786 "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -0700787 }
788
Adam Lesinski182f73f2013-12-05 16:48:06 -0800789 setImpl(type, triggerAtTime, windowLength, interval, operation,
Adrian Roosc42a1e12014-07-07 23:35:53 +0200790 false, workSource, alarmClock);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800791 }
Christopher Tate89779822012-08-31 14:40:03 -0700792
Adam Lesinski182f73f2013-12-05 16:48:06 -0800793 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -0800794 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800795 getContext().enforceCallingOrSelfPermission(
796 "android.permission.SET_TIME",
797 "setTime");
798
Greg Hackmann0cab8962014-02-21 16:35:52 -0800799 if (mNativeData == 0) {
800 Slog.w(TAG, "Not setting time since no alarm driver is available.");
801 return false;
Christopher Tate89779822012-08-31 14:40:03 -0700802 }
Greg Hackmann0cab8962014-02-21 16:35:52 -0800803
804 synchronized (mLock) {
805 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800808
809 @Override
810 public void setTimeZone(String tz) {
811 getContext().enforceCallingOrSelfPermission(
812 "android.permission.SET_TIME_ZONE",
813 "setTimeZone");
814
815 final long oldId = Binder.clearCallingIdentity();
816 try {
817 setTimeZoneImpl(tz);
818 } finally {
819 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 }
821 }
Christopher Tate4cb338d2013-07-26 13:11:31 -0700822
Adam Lesinski182f73f2013-12-05 16:48:06 -0800823 @Override
824 public void remove(PendingIntent operation) {
825 removeImpl(operation);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 }
Christopher Tate4cb338d2013-07-26 13:11:31 -0700828
Adam Lesinski182f73f2013-12-05 16:48:06 -0800829 @Override
Jose Lima235510e2014-08-13 12:50:01 -0700830 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +0200831 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
832 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
833 "getNextAlarmClock", null);
834
835 return getNextAlarmClockImpl(userId);
836 }
837
838 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -0800839 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
840 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
841 != PackageManager.PERMISSION_GRANTED) {
842 pw.println("Permission Denial: can't dump AlarmManager from from pid="
843 + Binder.getCallingPid()
844 + ", uid=" + Binder.getCallingUid());
845 return;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700846 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700847
Adam Lesinski182f73f2013-12-05 16:48:06 -0800848 dumpImpl(pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700849 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800850 };
Christopher Tate4cb338d2013-07-26 13:11:31 -0700851
Adam Lesinski182f73f2013-12-05 16:48:06 -0800852 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 synchronized (mLock) {
854 pw.println("Current Alarm Manager state:");
Christopher Tatee0a22b32013-07-11 14:43:13 -0700855 final long nowRTC = System.currentTimeMillis();
856 final long nowELAPSED = SystemClock.elapsedRealtime();
857 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
858
859 pw.print("nowRTC="); pw.print(nowRTC);
860 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700861 pw.print(" nowELAPSED="); TimeUtils.formatDuration(nowELAPSED, pw);
862 pw.println();
863 if (!mInteractive) {
864 pw.print("Time since non-interactive: ");
865 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
866 pw.println();
867 pw.print("Max wakeup delay: ");
868 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
869 pw.println();
870 pw.print("Time since last dispatch: ");
871 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
872 pw.println();
873 pw.print("Next non-wakeup delivery time: ");
874 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
875 pw.println();
876 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700877
878 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
879 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700880 pw.print("Next non-wakeup alarm: ");
881 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700882 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700883 pw.print("Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700884 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackborn998e6082014-09-11 19:13:23 -0700885 pw.print("Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700886
887 if (mAlarmBatches.size() > 0) {
888 pw.println();
889 pw.print("Pending alarm batches: ");
890 pw.println(mAlarmBatches.size());
891 for (Batch b : mAlarmBatches) {
892 pw.print(b); pw.println(':');
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700893 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700894 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800896
897 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700898 pw.print("Past-due non-wakeup alarms: ");
899 if (mPendingNonWakeupAlarms.size() > 0) {
900 pw.println(mPendingNonWakeupAlarms.size());
901 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
902 } else {
903 pw.println("(none)");
904 }
905 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
906 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
907 pw.println();
908 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
909 pw.print(", max non-interactive time: ");
910 TimeUtils.formatDuration(mNonInteractiveTime, pw);
911 pw.println();
912
913 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700914 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -0800915 pw.println();
916
917 if (mLog.dump(pw, " Recent problems", " ")) {
918 pw.println();
919 }
920
921 final FilterStats[] topFilters = new FilterStats[10];
922 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
923 @Override
924 public int compare(FilterStats lhs, FilterStats rhs) {
925 if (lhs.aggregateTime < rhs.aggregateTime) {
926 return 1;
927 } else if (lhs.aggregateTime > rhs.aggregateTime) {
928 return -1;
929 }
930 return 0;
931 }
932 };
933 int len = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800934 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
935 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
936 for (int ip=0; ip<uidStats.size(); ip++) {
937 BroadcastStats bs = uidStats.valueAt(ip);
938 for (int is=0; is<bs.filterStats.size(); is++) {
939 FilterStats fs = bs.filterStats.valueAt(is);
940 int pos = len > 0
941 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
942 if (pos < 0) {
943 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -0800944 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800945 if (pos < topFilters.length) {
946 int copylen = topFilters.length - pos - 1;
947 if (copylen > 0) {
948 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
949 }
950 topFilters[pos] = fs;
951 if (len < topFilters.length) {
952 len++;
953 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800954 }
955 }
956 }
957 }
958 if (len > 0) {
959 pw.println(" Top Alarms:");
960 for (int i=0; i<len; i++) {
961 FilterStats fs = topFilters[i];
962 pw.print(" ");
963 if (fs.nesting > 0) pw.print("*ACTIVE* ");
964 TimeUtils.formatDuration(fs.aggregateTime, pw);
965 pw.print(" running, "); pw.print(fs.numWakeup);
966 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800967 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
968 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -0800969 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700970 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -0800971 pw.println();
972 }
973 }
974
975 pw.println(" ");
976 pw.println(" Alarm Stats:");
977 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800978 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
979 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
980 for (int ip=0; ip<uidStats.size(); ip++) {
981 BroadcastStats bs = uidStats.valueAt(ip);
982 pw.print(" ");
983 if (bs.nesting > 0) pw.print("*ACTIVE* ");
984 UserHandle.formatUid(pw, bs.mUid);
985 pw.print(":");
986 pw.print(bs.mPackageName);
987 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
988 pw.print(" running, "); pw.print(bs.numWakeup);
989 pw.println(" wakeups:");
990 tmpFilters.clear();
991 for (int is=0; is<bs.filterStats.size(); is++) {
992 tmpFilters.add(bs.filterStats.valueAt(is));
993 }
994 Collections.sort(tmpFilters, comparator);
995 for (int i=0; i<tmpFilters.size(); i++) {
996 FilterStats fs = tmpFilters.get(i);
997 pw.print(" ");
998 if (fs.nesting > 0) pw.print("*ACTIVE* ");
999 TimeUtils.formatDuration(fs.aggregateTime, pw);
1000 pw.print(" "); pw.print(fs.numWakeup);
1001 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001002 pw.print(" alarms: ");
1003 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001004 pw.println();
1005 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 }
1007 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001008
1009 if (WAKEUP_STATS) {
1010 pw.println();
1011 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001012 long last = -1;
1013 for (WakeupEvent event : mRecentWakeups) {
1014 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1015 pw.print('|');
1016 if (last < 0) {
1017 pw.print('0');
1018 } else {
1019 pw.print(event.when - last);
1020 }
1021 last = event.when;
1022 pw.print('|'); pw.print(event.uid);
1023 pw.print('|'); pw.print(event.action);
1024 pw.println();
1025 }
1026 pw.println();
1027 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 }
1029 }
1030
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001031 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001032 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
1033 PrintWriter pw = new PrintWriter(bs);
1034 final long nowRTC = System.currentTimeMillis();
1035 final long nowELAPSED = SystemClock.elapsedRealtime();
1036 final int NZ = mAlarmBatches.size();
1037 for (int iz = 0; iz < NZ; iz++) {
1038 Batch bz = mAlarmBatches.get(iz);
1039 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001040 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001041 pw.flush();
1042 Slog.v(TAG, bs.toString());
1043 bs.reset();
1044 }
1045 }
1046
1047 private boolean validateConsistencyLocked() {
1048 if (DEBUG_VALIDATE) {
1049 long lastTime = Long.MIN_VALUE;
1050 final int N = mAlarmBatches.size();
1051 for (int i = 0; i < N; i++) {
1052 Batch b = mAlarmBatches.get(i);
1053 if (b.start >= lastTime) {
1054 // duplicate start times are okay because of standalone batches
1055 lastTime = b.start;
1056 } else {
1057 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001058 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1059 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001060 return false;
1061 }
1062 }
1063 }
1064 return true;
1065 }
1066
1067 private Batch findFirstWakeupBatchLocked() {
1068 final int N = mAlarmBatches.size();
1069 for (int i = 0; i < N; i++) {
1070 Batch b = mAlarmBatches.get(i);
1071 if (b.hasWakeups()) {
1072 return b;
1073 }
1074 }
1075 return null;
1076 }
1077
Jose Lima235510e2014-08-13 12:50:01 -07001078 private AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001079 synchronized (mLock) {
1080 return mNextAlarmClockForUser.get(userId);
1081 }
1082 }
1083
1084 /**
1085 * Recomputes the next alarm clock for all users.
1086 */
1087 private void updateNextAlarmClockLocked() {
1088 if (!mNextAlarmClockMayChange) {
1089 return;
1090 }
1091 mNextAlarmClockMayChange = false;
1092
Jose Lima235510e2014-08-13 12:50:01 -07001093 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001094 nextForUser.clear();
1095
1096 final int N = mAlarmBatches.size();
1097 for (int i = 0; i < N; i++) {
1098 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
1099 final int M = alarms.size();
1100
1101 for (int j = 0; j < M; j++) {
1102 Alarm a = alarms.get(j);
1103 if (a.alarmClock != null) {
1104 final int userId = a.userId;
1105
1106 if (DEBUG_ALARM_CLOCK) {
1107 Log.v(TAG, "Found AlarmClockInfo at " +
1108 formatNextAlarm(getContext(), a.alarmClock) +
1109 " for user " + userId);
1110 }
1111
1112 // Alarms and batches are sorted by time, no need to compare times here.
1113 if (nextForUser.get(userId) == null) {
1114 nextForUser.put(userId, a.alarmClock);
1115 }
1116 }
1117 }
1118 }
1119
1120 // Update mNextAlarmForUser with new values.
1121 final int NN = nextForUser.size();
1122 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07001123 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001124 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001125 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001126 if (!newAlarm.equals(currentAlarm)) {
1127 updateNextAlarmInfoForUserLocked(userId, newAlarm);
1128 }
1129 }
1130
1131 // Remove users without any alarm clocks scheduled.
1132 final int NNN = mNextAlarmClockForUser.size();
1133 for (int i = NNN - 1; i >= 0; i--) {
1134 int userId = mNextAlarmClockForUser.keyAt(i);
1135 if (nextForUser.get(userId) == null) {
1136 updateNextAlarmInfoForUserLocked(userId, null);
1137 }
1138 }
1139 }
1140
Jose Lima235510e2014-08-13 12:50:01 -07001141 private void updateNextAlarmInfoForUserLocked(int userId,
1142 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001143 if (alarmClock != null) {
1144 if (DEBUG_ALARM_CLOCK) {
1145 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
1146 formatNextAlarm(getContext(), alarmClock));
1147 }
1148 mNextAlarmClockForUser.put(userId, alarmClock);
1149 } else {
1150 if (DEBUG_ALARM_CLOCK) {
1151 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
1152 }
1153 mNextAlarmClockForUser.remove(userId);
1154 }
1155
1156 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
1157 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1158 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1159 }
1160
1161 /**
1162 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
1163 * for which alarm clocks have changed since the last call to this.
1164 *
1165 * Do not call with a lock held. Only call from mHandler's thread.
1166 *
1167 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
1168 */
1169 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07001170 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001171 pendingUsers.clear();
1172
1173 synchronized (mLock) {
1174 final int N = mPendingSendNextAlarmClockChangedForUser.size();
1175 for (int i = 0; i < N; i++) {
1176 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
1177 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
1178 }
1179 mPendingSendNextAlarmClockChangedForUser.clear();
1180 }
1181
1182 final int N = pendingUsers.size();
1183 for (int i = 0; i < N; i++) {
1184 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001185 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001186 Settings.System.putStringForUser(getContext().getContentResolver(),
1187 Settings.System.NEXT_ALARM_FORMATTED,
1188 formatNextAlarm(getContext(), alarmClock),
1189 userId);
1190
1191 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
1192 new UserHandle(userId));
1193 }
1194 }
1195
1196 /**
1197 * Formats an alarm like platform/packages/apps/DeskClock used to.
1198 */
Jose Lima235510e2014-08-13 12:50:01 -07001199 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001200 String skeleton = DateFormat.is24HourFormat(context) ? "EHm" : "Ehma";
1201 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
1202 return (info == null) ? "" :
1203 DateFormat.format(pattern, info.getTriggerTime()).toString();
1204 }
1205
Adam Lesinski182f73f2013-12-05 16:48:06 -08001206 void rescheduleKernelAlarmsLocked() {
1207 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
1208 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001209 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001210 if (mAlarmBatches.size() > 0) {
1211 final Batch firstWakeup = findFirstWakeupBatchLocked();
1212 final Batch firstBatch = mAlarmBatches.get(0);
1213 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
1214 mNextWakeup = firstWakeup.start;
1215 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
1216 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001217 if (firstBatch != firstWakeup) {
1218 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001219 }
1220 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001221 if (mPendingNonWakeupAlarms.size() > 0) {
1222 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
1223 nextNonWakeup = mNextNonWakeupDeliveryTime;
1224 }
1225 }
1226 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
1227 mNextNonWakeup = nextNonWakeup;
1228 setLocked(ELAPSED_REALTIME, nextNonWakeup);
1229 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001230 }
1231
1232 private void removeLocked(PendingIntent operation) {
1233 boolean didRemove = false;
1234 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1235 Batch b = mAlarmBatches.get(i);
1236 didRemove |= b.remove(operation);
1237 if (b.size() == 0) {
1238 mAlarmBatches.remove(i);
1239 }
1240 }
1241
1242 if (didRemove) {
1243 if (DEBUG_BATCH) {
1244 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
1245 }
1246 rebatchAllAlarmsLocked(true);
1247 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001248 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001249 }
1250 }
1251
1252 void removeLocked(String packageName) {
1253 boolean didRemove = false;
1254 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1255 Batch b = mAlarmBatches.get(i);
1256 didRemove |= b.remove(packageName);
1257 if (b.size() == 0) {
1258 mAlarmBatches.remove(i);
1259 }
1260 }
1261
1262 if (didRemove) {
1263 if (DEBUG_BATCH) {
1264 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1265 }
1266 rebatchAllAlarmsLocked(true);
1267 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001268 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001269 }
1270 }
1271
1272 void removeUserLocked(int userHandle) {
1273 boolean didRemove = false;
1274 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1275 Batch b = mAlarmBatches.get(i);
1276 didRemove |= b.remove(userHandle);
1277 if (b.size() == 0) {
1278 mAlarmBatches.remove(i);
1279 }
1280 }
1281
1282 if (didRemove) {
1283 if (DEBUG_BATCH) {
1284 Slog.v(TAG, "remove(user) changed bounds; rebatching");
1285 }
1286 rebatchAllAlarmsLocked(true);
1287 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001288 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001289 }
1290 }
1291
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001292 void interactiveStateChangedLocked(boolean interactive) {
1293 if (mInteractive != interactive) {
1294 mInteractive = interactive;
1295 final long nowELAPSED = SystemClock.elapsedRealtime();
1296 if (interactive) {
1297 if (mPendingNonWakeupAlarms.size() > 0) {
1298 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1299 mTotalDelayTime += thisDelayTime;
1300 if (mMaxDelayTime < thisDelayTime) {
1301 mMaxDelayTime = thisDelayTime;
1302 }
1303 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
1304 mPendingNonWakeupAlarms.clear();
1305 }
1306 if (mNonInteractiveStartTime > 0) {
1307 long dur = nowELAPSED - mNonInteractiveStartTime;
1308 if (dur > mNonInteractiveTime) {
1309 mNonInteractiveTime = dur;
1310 }
1311 }
1312 } else {
1313 mNonInteractiveStartTime = nowELAPSED;
1314 }
1315 }
1316 }
1317
Adam Lesinski182f73f2013-12-05 16:48:06 -08001318 boolean lookForPackageLocked(String packageName) {
1319 for (int i = 0; i < mAlarmBatches.size(); i++) {
1320 Batch b = mAlarmBatches.get(i);
1321 if (b.hasPackage(packageName)) {
1322 return true;
1323 }
1324 }
1325 return false;
1326 }
1327
1328 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001329 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001330 // The kernel never triggers alarms with negative wakeup times
1331 // so we ensure they are positive.
1332 long alarmSeconds, alarmNanoseconds;
1333 if (when < 0) {
1334 alarmSeconds = 0;
1335 alarmNanoseconds = 0;
1336 } else {
1337 alarmSeconds = when / 1000;
1338 alarmNanoseconds = (when % 1000) * 1000 * 1000;
1339 }
1340
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001341 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001342 } else {
1343 Message msg = Message.obtain();
1344 msg.what = ALARM_EVENT;
1345
1346 mHandler.removeMessages(ALARM_EVENT);
1347 mHandler.sendMessageAtTime(msg, when);
1348 }
1349 }
1350
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001351 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001352 String prefix, String label, long nowRTC, long nowELAPSED, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001353 for (int i=list.size()-1; i>=0; i--) {
1354 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001355 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1356 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001357 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358 }
1359 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001360
1361 private static final String labelForType(int type) {
1362 switch (type) {
1363 case RTC: return "RTC";
1364 case RTC_WAKEUP : return "RTC_WAKEUP";
1365 case ELAPSED_REALTIME : return "ELAPSED";
1366 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
1367 default:
1368 break;
1369 }
1370 return "--unknown--";
1371 }
1372
1373 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001374 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001375 for (int i=list.size()-1; i>=0; i--) {
1376 Alarm a = list.get(i);
1377 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001378 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1379 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001380 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001381 }
1382 }
1383
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001384 private native long init();
1385 private native void close(long nativeData);
1386 private native void set(long nativeData, int type, long seconds, long nanoseconds);
1387 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08001388 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001389 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001391 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001392 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001393 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001394 // batches are temporally sorted, so we need only pull from the
1395 // start of the list until we either empty it or hit a batch
1396 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07001397 while (mAlarmBatches.size() > 0) {
1398 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001399 if (batch.start > nowELAPSED) {
1400 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 break;
1402 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403
Christopher Tatee0a22b32013-07-11 14:43:13 -07001404 // We will (re)schedule some alarms now; don't let that interfere
1405 // with delivery of this current batch
1406 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001407
Christopher Tatee0a22b32013-07-11 14:43:13 -07001408 final int N = batch.size();
1409 for (int i = 0; i < N; i++) {
1410 Alarm alarm = batch.get(i);
1411 alarm.count = 1;
1412 triggerList.add(alarm);
1413
1414 // Recurring alarms may have passed several alarm intervals while the
1415 // phone was asleep or off, so pass a trigger count when sending them.
1416 if (alarm.repeatInterval > 0) {
1417 // this adjustment will be zero if we're late by
1418 // less than one full repeat interval
1419 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
1420
1421 // Also schedule its next recurrence
1422 final long delta = alarm.count * alarm.repeatInterval;
1423 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07001424 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07001425 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
David Christieebe51fc2013-07-26 13:23:29 -07001426 alarm.repeatInterval, alarm.operation, batch.standalone, true,
Adrian Roosc42a1e12014-07-07 23:35:53 +02001427 alarm.workSource, alarm.alarmClock, alarm.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001429 // For now we count this as a wakeup alarm, meaning it needs to be
1430 // delivered immediately. In the future we should change this, but
1431 // that required delaying when we reschedule the repeat...!
1432 hasWakeup = false;
1433 } else if (alarm.wakeup) {
1434 hasWakeup = true;
1435 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001436
1437 // We removed an alarm clock. Let the caller recompute the next alarm clock.
1438 if (alarm.alarmClock != null) {
1439 mNextAlarmClockMayChange = true;
1440 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07001441 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001443
Christopher Tate1590f1e2014-10-02 17:27:57 -07001444 // This is a new alarm delivery set; bump the sequence number to indicate that
1445 // all apps' alarm delivery classes should be recalculated.
1446 mCurrentSeq++;
1447 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001448 Collections.sort(triggerList, mAlarmDispatchComparator);
1449
1450 if (localLOGV) {
1451 for (int i=0; i<triggerList.size(); i++) {
1452 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
1453 }
1454 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001455
1456 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001457 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001458
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 /**
1460 * This Comparator sorts Alarms into increasing time order.
1461 */
1462 public static class IncreasingTimeOrder implements Comparator<Alarm> {
1463 public int compare(Alarm a1, Alarm a2) {
1464 long when1 = a1.when;
1465 long when2 = a2.when;
1466 if (when1 - when2 > 0) {
1467 return 1;
1468 }
1469 if (when1 - when2 < 0) {
1470 return -1;
1471 }
1472 return 0;
1473 }
1474 }
1475
1476 private static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001477 public final int type;
1478 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001479 public final PendingIntent operation;
1480 public final String tag;
1481 public final WorkSource workSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 public int count;
1483 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07001484 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001485 public long whenElapsed; // 'when' in the elapsed time base
1486 public long maxWhen; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 public long repeatInterval;
Jose Lima235510e2014-08-13 12:50:01 -07001488 public final AlarmManager.AlarmClockInfo alarmClock;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001489 public final int userId;
Christopher Tate1590f1e2014-10-02 17:27:57 -07001490 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001491
Christopher Tate3e04b472013-10-21 17:51:31 -07001492 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Jose Lima235510e2014-08-13 12:50:01 -07001493 long _interval, PendingIntent _op, WorkSource _ws,
1494 AlarmManager.AlarmClockInfo _info, int _userId) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001495 type = _type;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001496 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
1497 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001498 when = _when;
1499 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07001500 windowLength = _windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001501 maxWhen = _maxWhen;
1502 repeatInterval = _interval;
1503 operation = _op;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001504 tag = makeTag(_op, _type);
David Christieebe51fc2013-07-26 13:23:29 -07001505 workSource = _ws;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001506 alarmClock = _info;
1507 userId = _userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001509
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001510 public static String makeTag(PendingIntent pi, int type) {
1511 return pi.getTag(type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
1512 ? "*walarm*:" : "*alarm*:");
1513 }
1514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001516 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001517 StringBuilder sb = new StringBuilder(128);
1518 sb.append("Alarm{");
1519 sb.append(Integer.toHexString(System.identityHashCode(this)));
1520 sb.append(" type ");
1521 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001522 sb.append(" when ");
1523 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001524 sb.append(" ");
1525 sb.append(operation.getTargetPackage());
1526 sb.append('}');
1527 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001528 }
1529
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001530 public void dump(PrintWriter pw, String prefix, long nowRTC, long nowELAPSED,
1531 SimpleDateFormat sdf) {
1532 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
1533 pw.print(prefix); pw.print("tag="); pw.println(tag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001534 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001535 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
1536 nowELAPSED, pw);
1537 if (isRtc) {
1538 pw.print(" when="); pw.print(sdf.format(new Date(when)));
1539 } else {
1540 pw.print(" when="); TimeUtils.formatDuration(when, nowELAPSED, pw);
1541 }
1542 pw.println();
1543 pw.print(prefix); pw.print("window="); pw.print(windowLength);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001544 pw.print(" repeatInterval="); pw.print(repeatInterval);
1545 pw.print(" count="); pw.println(count);
1546 pw.print(prefix); pw.print("operation="); pw.println(operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 }
1548 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001549
Christopher Tatee0a22b32013-07-11 14:43:13 -07001550 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
1551 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07001552 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
1553 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001554 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07001555 break;
1556 }
1557
Christopher Tatee0a22b32013-07-11 14:43:13 -07001558 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07001559 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
1560 Alarm a = b.alarms.get(nextAlarm);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001561 WakeupEvent e = new WakeupEvent(nowRTC,
1562 a.operation.getCreatorUid(),
1563 a.operation.getIntent().getAction());
1564 mRecentWakeups.add(e);
1565 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001566 }
1567 }
1568
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001569 long currentNonWakeupFuzzLocked(long nowELAPSED) {
1570 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
1571 if (timeSinceOn < 5*60*1000) {
1572 // If the screen has been off for 5 minutes, only delay by at most two minutes.
1573 return 2*60*1000;
1574 } else if (timeSinceOn < 30*60*1000) {
1575 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
1576 return 15*60*1000;
1577 } else {
1578 // Otherwise, we will delay by at most an hour.
1579 return 60*60*1000;
1580 }
1581 }
1582
1583 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
1584 if (mInteractive) {
1585 return false;
1586 }
1587 if (mLastAlarmDeliveryTime <= 0) {
1588 return false;
1589 }
minho.choo649acab2014-12-12 16:13:55 +09001590 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001591 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
1592 // and the next delivery time is in the past, then just deliver them all. This
1593 // avoids bugs where we get stuck in a loop trying to poll for alarms.
1594 return false;
1595 }
1596 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
1597 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
1598 }
1599
1600 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
1601 mLastAlarmDeliveryTime = nowELAPSED;
1602 for (int i=0; i<triggerList.size(); i++) {
1603 Alarm alarm = triggerList.get(i);
1604 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07001605 if (localLOGV) {
1606 Slog.v(TAG, "sending alarm " + alarm);
1607 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001608 alarm.operation.send(getContext(), 0,
1609 mBackgroundIntent.putExtra(
1610 Intent.EXTRA_ALARM_COUNT, alarm.count),
1611 mResultReceiver, mHandler);
1612
1613 // we have an active broadcast so stay awake.
1614 if (mBroadcastRefCount == 0) {
1615 setWakelockWorkSource(alarm.operation, alarm.workSource,
1616 alarm.type, alarm.tag, true);
1617 mWakeLock.acquire();
1618 }
1619 final InFlight inflight = new InFlight(AlarmManagerService.this,
1620 alarm.operation, alarm.workSource, alarm.type, alarm.tag);
1621 mInFlight.add(inflight);
1622 mBroadcastRefCount++;
1623
1624 final BroadcastStats bs = inflight.mBroadcastStats;
1625 bs.count++;
1626 if (bs.nesting == 0) {
1627 bs.nesting = 1;
1628 bs.startTime = nowELAPSED;
1629 } else {
1630 bs.nesting++;
1631 }
1632 final FilterStats fs = inflight.mFilterStats;
1633 fs.count++;
1634 if (fs.nesting == 0) {
1635 fs.nesting = 1;
1636 fs.startTime = nowELAPSED;
1637 } else {
1638 fs.nesting++;
1639 }
1640 if (alarm.type == ELAPSED_REALTIME_WAKEUP
1641 || alarm.type == RTC_WAKEUP) {
1642 bs.numWakeup++;
1643 fs.numWakeup++;
1644 if (alarm.workSource != null && alarm.workSource.size() > 0) {
1645 for (int wi=0; wi<alarm.workSource.size(); wi++) {
1646 ActivityManagerNative.noteWakeupAlarm(
1647 alarm.operation, alarm.workSource.get(wi),
1648 alarm.workSource.getName(wi));
1649 }
1650 } else {
1651 ActivityManagerNative.noteWakeupAlarm(
1652 alarm.operation, -1, null);
1653 }
1654 }
1655 } catch (PendingIntent.CanceledException e) {
1656 if (alarm.repeatInterval > 0) {
1657 // This IntentSender is no longer valid, but this
1658 // is a repeating alarm, so toss the hoser.
1659 removeImpl(alarm.operation);
1660 }
1661 } catch (RuntimeException e) {
1662 Slog.w(TAG, "Failure sending alarm.", e);
1663 }
1664 }
1665 }
1666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 private class AlarmThread extends Thread
1668 {
1669 public AlarmThread()
1670 {
1671 super("AlarmManager");
1672 }
1673
1674 public void run()
1675 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07001676 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
1677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 while (true)
1679 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001680 int result = waitForAlarm(mNativeData);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001681
1682 triggerList.clear();
1683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 if ((result & TIME_CHANGED_MASK) != 0) {
Christopher Tate385e4982013-07-23 18:22:29 -07001685 if (DEBUG_BATCH) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001686 Slog.v(TAG, "Time changed notification from kernel; rebatching");
Christopher Tate385e4982013-07-23 18:22:29 -07001687 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001688 removeImpl(mTimeTickSender);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001689 rebatchAllAlarms();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001690 mClockReceiver.scheduleTimeTickEvent();
Dianne Hackborn998e6082014-09-11 19:13:23 -07001691 synchronized (mLock) {
1692 mNumTimeChanged++;
1693 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001694 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
Dianne Hackborn89ba6752011-01-23 16:51:16 -08001695 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1696 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001697 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 }
1699
1700 synchronized (mLock) {
1701 final long nowRTC = System.currentTimeMillis();
1702 final long nowELAPSED = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001703 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 TAG, "Checking for alarms... rtc=" + nowRTC
1705 + ", elapsed=" + nowELAPSED);
1706
Christopher Tate18a75f12013-07-01 18:18:59 -07001707 if (WAKEUP_STATS) {
1708 if ((result & IS_WAKEUP_MASK) != 0) {
1709 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
1710 int n = 0;
1711 for (WakeupEvent event : mRecentWakeups) {
1712 if (event.when > newEarliest) break;
1713 n++; // number of now-stale entries at the list head
1714 }
1715 for (int i = 0; i < n; i++) {
1716 mRecentWakeups.remove();
1717 }
1718
Christopher Tatee0a22b32013-07-11 14:43:13 -07001719 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Christopher Tate18a75f12013-07-01 18:18:59 -07001720 }
1721 }
1722
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001723 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
1724 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
1725 // if there are no wakeup alarms and the screen is off, we can
1726 // delay what we have so far until the future.
1727 if (mPendingNonWakeupAlarms.size() == 0) {
1728 mStartCurrentDelayTime = nowELAPSED;
1729 mNextNonWakeupDeliveryTime = nowELAPSED
1730 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001731 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001732 mPendingNonWakeupAlarms.addAll(triggerList);
1733 mNumDelayedAlarms += triggerList.size();
1734 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001735 updateNextAlarmClockLocked();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001736 } else {
1737 // now deliver the alarm intents; if there are pending non-wakeup
1738 // alarms, we need to merge them in to the list. note we don't
1739 // just deliver them first because we generally want non-wakeup
1740 // alarms delivered after wakeup alarms.
1741 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001742 updateNextAlarmClockLocked();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001743 if (mPendingNonWakeupAlarms.size() > 0) {
Christopher Tate1590f1e2014-10-02 17:27:57 -07001744 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001745 triggerList.addAll(mPendingNonWakeupAlarms);
1746 Collections.sort(triggerList, mAlarmDispatchComparator);
1747 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1748 mTotalDelayTime += thisDelayTime;
1749 if (mMaxDelayTime < thisDelayTime) {
1750 mMaxDelayTime = thisDelayTime;
1751 }
1752 mPendingNonWakeupAlarms.clear();
1753 }
1754 deliverAlarmsLocked(triggerList, nowELAPSED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 }
1756 }
1757 }
1758 }
1759 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07001760
David Christieebe51fc2013-07-26 13:23:29 -07001761 /**
1762 * Attribute blame for a WakeLock.
1763 * @param pi PendingIntent to attribute blame to if ws is null.
1764 * @param ws WorkSource to attribute blame.
1765 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001766 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
1767 boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07001768 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001769 final boolean unimportant = pi == mTimeTickSender;
1770 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07001771 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001772 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07001773 } else {
1774 mWakeLock.setHistoryTag(null);
1775 }
1776 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07001777 if (ws != null) {
1778 mWakeLock.setWorkSource(ws);
1779 return;
1780 }
1781
Christopher Tatec4a07d12012-04-06 14:19:13 -07001782 final int uid = ActivityManagerNative.getDefault()
1783 .getUidForIntentSender(pi.getTarget());
1784 if (uid >= 0) {
1785 mWakeLock.setWorkSource(new WorkSource(uid));
1786 return;
1787 }
1788 } catch (Exception e) {
1789 }
1790
1791 // Something went wrong; fall back to attributing the lock to the OS
1792 mWakeLock.setWorkSource(null);
1793 }
1794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001795 private class AlarmHandler extends Handler {
1796 public static final int ALARM_EVENT = 1;
1797 public static final int MINUTE_CHANGE_EVENT = 2;
1798 public static final int DATE_CHANGE_EVENT = 3;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001799 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800
1801 public AlarmHandler() {
1802 }
1803
1804 public void handleMessage(Message msg) {
1805 if (msg.what == ALARM_EVENT) {
1806 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
1807 synchronized (mLock) {
1808 final long nowRTC = System.currentTimeMillis();
Christopher Tatee0a22b32013-07-11 14:43:13 -07001809 final long nowELAPSED = SystemClock.elapsedRealtime();
1810 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001811 updateNextAlarmClockLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001812 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814 // now trigger the alarms without the lock held
Dianne Hackborn390517b2013-05-30 15:03:32 -07001815 for (int i=0; i<triggerList.size(); i++) {
1816 Alarm alarm = triggerList.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 try {
1818 alarm.operation.send();
1819 } catch (PendingIntent.CanceledException e) {
1820 if (alarm.repeatInterval > 0) {
1821 // This IntentSender is no longer valid, but this
1822 // is a repeating alarm, so toss the hoser.
Adam Lesinski182f73f2013-12-05 16:48:06 -08001823 removeImpl(alarm.operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 }
1825 }
1826 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001827 } else if (msg.what == SEND_NEXT_ALARM_CLOCK_CHANGED) {
1828 sendNextAlarmClockChanged();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 }
1830 }
1831 }
1832
1833 class ClockReceiver extends BroadcastReceiver {
1834 public ClockReceiver() {
1835 IntentFilter filter = new IntentFilter();
1836 filter.addAction(Intent.ACTION_TIME_TICK);
1837 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001838 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 }
1840
1841 @Override
1842 public void onReceive(Context context, Intent intent) {
1843 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001844 if (DEBUG_BATCH) {
1845 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
1846 }
1847 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001848 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
1849 // Since the kernel does not keep track of DST, we need to
1850 // reset the TZ information at the beginning of each day
1851 // based off of the current Zone gmt offset + userspace tracked
1852 // daylight savings information.
1853 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02001854 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001855 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07001856 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001857 }
1858 }
1859
1860 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07001861 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09001862 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07001863
1864 // Schedule this event for the amount of time that it would take to get to
1865 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09001866 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07001867
David Christieebe51fc2013-07-26 13:23:29 -07001868 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08001869 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Adrian Roosc42a1e12014-07-07 23:35:53 +02001870 0, mTimeTickSender, true, workSource, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001871 }
Christopher Tate385e4982013-07-23 18:22:29 -07001872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873 public void scheduleDateChangedEvent() {
1874 Calendar calendar = Calendar.getInstance();
1875 calendar.setTimeInMillis(System.currentTimeMillis());
1876 calendar.set(Calendar.HOUR, 0);
1877 calendar.set(Calendar.MINUTE, 0);
1878 calendar.set(Calendar.SECOND, 0);
1879 calendar.set(Calendar.MILLISECOND, 0);
1880 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07001881
1882 final WorkSource workSource = null; // Let system take blame for date change events.
Adrian Roosc42a1e12014-07-07 23:35:53 +02001883 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, true, workSource,
1884 null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 }
1886 }
1887
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001888 class InteractiveStateReceiver extends BroadcastReceiver {
1889 public InteractiveStateReceiver() {
1890 IntentFilter filter = new IntentFilter();
1891 filter.addAction(Intent.ACTION_SCREEN_OFF);
1892 filter.addAction(Intent.ACTION_SCREEN_ON);
1893 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
1894 getContext().registerReceiver(this, filter);
1895 }
1896
1897 @Override
1898 public void onReceive(Context context, Intent intent) {
1899 synchronized (mLock) {
1900 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
1901 }
1902 }
1903 }
1904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001905 class UninstallReceiver extends BroadcastReceiver {
1906 public UninstallReceiver() {
1907 IntentFilter filter = new IntentFilter();
1908 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1909 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001910 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08001912 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001913 // Register for events related to sdcard installation.
1914 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001915 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001916 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001917 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001918 }
1919
1920 @Override
1921 public void onReceive(Context context, Intent intent) {
1922 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001923 String action = intent.getAction();
1924 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001925 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
1926 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
1927 for (String packageName : pkgList) {
1928 if (lookForPackageLocked(packageName)) {
1929 setResultCode(Activity.RESULT_OK);
1930 return;
1931 }
1932 }
1933 return;
1934 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001935 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001936 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
1937 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
1938 if (userHandle >= 0) {
1939 removeUserLocked(userHandle);
1940 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001941 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08001942 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
1943 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
1944 // This package is being updated; don't kill its alarms.
1945 return;
1946 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001947 Uri data = intent.getData();
1948 if (data != null) {
1949 String pkg = data.getSchemeSpecificPart();
1950 if (pkg != null) {
1951 pkgList = new String[]{pkg};
1952 }
1953 }
1954 }
1955 if (pkgList != null && (pkgList.length > 0)) {
1956 for (String pkg : pkgList) {
1957 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07001958 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001959 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
1960 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
1961 if (uidStats.remove(pkg) != null) {
1962 if (uidStats.size() <= 0) {
1963 mBroadcastStats.removeAt(i);
1964 }
1965 }
1966 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001967 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001968 }
1969 }
1970 }
1971 }
1972
1973 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001974 String pkg = pi.getCreatorPackage();
1975 int uid = pi.getCreatorUid();
1976 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
1977 if (uidStats == null) {
1978 uidStats = new ArrayMap<String, BroadcastStats>();
1979 mBroadcastStats.put(uid, uidStats);
1980 }
1981 BroadcastStats bs = uidStats.get(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001982 if (bs == null) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001983 bs = new BroadcastStats(uid, pkg);
1984 uidStats.put(pkg, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001985 }
1986 return bs;
1987 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001988
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001989 class ResultReceiver implements PendingIntent.OnFinished {
1990 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
1991 String resultData, Bundle resultExtras) {
1992 synchronized (mLock) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001993 InFlight inflight = null;
1994 for (int i=0; i<mInFlight.size(); i++) {
1995 if (mInFlight.get(i).mPendingIntent == pi) {
1996 inflight = mInFlight.remove(i);
1997 break;
1998 }
1999 }
2000 if (inflight != null) {
2001 final long nowELAPSED = SystemClock.elapsedRealtime();
2002 BroadcastStats bs = inflight.mBroadcastStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 bs.nesting--;
2004 if (bs.nesting <= 0) {
2005 bs.nesting = 0;
Dianne Hackborn81038902012-11-26 17:04:09 -08002006 bs.aggregateTime += nowELAPSED - bs.startTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002008 FilterStats fs = inflight.mFilterStats;
2009 fs.nesting--;
2010 if (fs.nesting <= 0) {
2011 fs.nesting = 0;
2012 fs.aggregateTime += nowELAPSED - fs.startTime;
2013 }
2014 } else {
2015 mLog.w("No in-flight alarm for " + pi + " " + intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002016 }
2017 mBroadcastRefCount--;
2018 if (mBroadcastRefCount == 0) {
2019 mWakeLock.release();
Dianne Hackborn81038902012-11-26 17:04:09 -08002020 if (mInFlight.size() > 0) {
2021 mLog.w("Finished all broadcasts with " + mInFlight.size()
2022 + " remaining inflights");
2023 for (int i=0; i<mInFlight.size(); i++) {
2024 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
2025 }
2026 mInFlight.clear();
2027 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002028 } else {
2029 // the next of our alarms is now in flight. reattribute the wakelock.
Dianne Hackborn81038902012-11-26 17:04:09 -08002030 if (mInFlight.size() > 0) {
David Christieebe51fc2013-07-26 13:23:29 -07002031 InFlight inFlight = mInFlight.get(0);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08002032 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002033 inFlight.mAlarmType, inFlight.mTag, false);
Christopher Tatec4a07d12012-04-06 14:19:13 -07002034 } else {
2035 // should never happen
Dianne Hackborn81038902012-11-26 17:04:09 -08002036 mLog.w("Alarm wakelock still held but sent queue empty");
Christopher Tatec4a07d12012-04-06 14:19:13 -07002037 mWakeLock.setWorkSource(null);
2038 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039 }
2040 }
2041 }
2042 }
2043}