blob: d7cdb9d4f32a0204efd78a20879f79fac524bcfc [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import android.app.ActivityManagerNative;
Christopher Tate57ceaaa2013-07-19 16:30:43 -070021import android.app.AlarmManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.app.IAlarmManager;
23import android.app.PendingIntent;
24import android.content.BroadcastReceiver;
Dianne Hackborn81038902012-11-26 17:04:09 -080025import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import 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;
34import android.os.Message;
35import android.os.PowerManager;
36import android.os.SystemClock;
37import android.os.SystemProperties;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070038import android.os.UserHandle;
Christopher Tatec4a07d12012-04-06 14:19:13 -070039import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.text.TextUtils;
Dianne Hackborn81038902012-11-26 17:04:09 -080041import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -080042import android.util.Slog;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070043import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044
45import java.io.FileDescriptor;
46import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070047import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -080049import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import java.util.Calendar;
51import java.util.Collections;
52import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -050053import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -070055import java.util.LinkedList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import java.util.Map;
57import java.util.TimeZone;
58
Christopher Tatee0a22b32013-07-11 14:43:13 -070059import static android.app.AlarmManager.RTC_WAKEUP;
60import static android.app.AlarmManager.RTC;
61import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
62import static android.app.AlarmManager.ELAPSED_REALTIME;
63
Dianne Hackborn81038902012-11-26 17:04:09 -080064import com.android.internal.util.LocalLog;
65
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066class AlarmManagerService extends IAlarmManager.Stub {
67 // The threshold for how long an alarm can be late before we print a
68 // warning message. The time duration is in milliseconds.
69 private static final long LATE_ALARM_THRESHOLD = 10 * 1000;
Christopher Tatee0a22b32013-07-11 14:43:13 -070070
71 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
72 private static final int RTC_MASK = 1 << RTC;
73 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
74 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075 private static final int TIME_CHANGED_MASK = 1 << 16;
Christopher Tate18a75f12013-07-01 18:18:59 -070076 private static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -080077
Christopher Tatee0a22b32013-07-11 14:43:13 -070078 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
79 private static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -080080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081 private static final String TAG = "AlarmManager";
82 private static final String ClockReceiver_TAG = "ClockReceiver";
83 private static final boolean localLOGV = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -070084 private static final boolean DEBUG_BATCH = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085 private static final int ALARM_EVENT = 1;
86 private static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
87
88 private static final Intent mBackgroundIntent
89 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Christopher Tatee0a22b32013-07-11 14:43:13 -070090 private static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091
Christopher Tate18a75f12013-07-01 18:18:59 -070092 private static final boolean WAKEUP_STATS = true;
93
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094 private final Context mContext;
Dianne Hackborn81038902012-11-26 17:04:09 -080095
96 private final LocalLog mLog = new LocalLog(TAG);
97
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098 private Object mLock = new Object();
Christopher Tatee0a22b32013-07-11 14:43:13 -070099
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100 private int mDescriptor;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700101 private long mNextWakeup;
102 private long mNextNonWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103 private int mBroadcastRefCount = 0;
104 private PowerManager.WakeLock mWakeLock;
Dianne Hackborn81038902012-11-26 17:04:09 -0800105 private ArrayList<InFlight> mInFlight = new ArrayList<InFlight>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 private final AlarmThread mWaitThread = new AlarmThread();
107 private final AlarmHandler mHandler = new AlarmHandler();
108 private ClockReceiver mClockReceiver;
109 private UninstallReceiver mUninstallReceiver;
110 private final ResultReceiver mResultReceiver = new ResultReceiver();
111 private final PendingIntent mTimeTickSender;
112 private final PendingIntent mDateChangeSender;
Dianne Hackborn81038902012-11-26 17:04:09 -0800113
Christopher Tate18a75f12013-07-01 18:18:59 -0700114 class WakeupEvent {
115 public long when;
116 public int uid;
117 public String action;
118
119 public WakeupEvent(long theTime, int theUid, String theAction) {
120 when = theTime;
121 uid = theUid;
122 action = theAction;
123 }
124 }
125
126 private final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
127 private final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
128
Christopher Tatee0a22b32013-07-11 14:43:13 -0700129 static final class Batch {
130 long start; // These endpoints are always in ELAPSED
131 long end;
132 boolean standalone; // certain "batches" don't participate in coalescing
133
134 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
135
136 Batch() {
137 start = 0;
138 end = Long.MAX_VALUE;
139 }
140
141 Batch(Alarm seed) {
142 start = seed.whenElapsed;
143 end = seed.maxWhen;
144 alarms.add(seed);
145 }
146
147 int size() {
148 return alarms.size();
149 }
150
151 Alarm get(int index) {
152 return alarms.get(index);
153 }
154
155 boolean canHold(long whenElapsed, long maxWhen) {
156 return (end >= whenElapsed) && (start <= maxWhen);
157 }
158
159 boolean add(Alarm alarm) {
160 boolean newStart = false;
161 // narrows the batch if necessary; presumes that canHold(alarm) is true
162 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
163 if (index < 0) {
164 index = 0 - index - 1;
165 }
166 alarms.add(index, alarm);
167 if (DEBUG_BATCH) {
168 Slog.v(TAG, "Adding " + alarm + " to " + this);
169 }
170 if (alarm.whenElapsed > start) {
171 start = alarm.whenElapsed;
172 newStart = true;
173 }
174 if (alarm.maxWhen < end) {
175 end = alarm.maxWhen;
176 }
177
178 if (DEBUG_BATCH) {
179 Slog.v(TAG, " => now " + this);
180 }
181 return newStart;
182 }
183
184 boolean remove(final PendingIntent operation) {
185 boolean didRemove = false;
186 long newStart = 0; // recalculate endpoints as we go
187 long newEnd = Long.MAX_VALUE;
188 for (int i = 0; i < alarms.size(); i++) {
189 Alarm alarm = alarms.get(i);
190 if (alarm.operation.equals(operation)) {
191 alarms.remove(i);
192 didRemove = true;
193 } else {
194 if (alarm.whenElapsed > newStart) {
195 newStart = alarm.whenElapsed;
196 }
197 if (alarm.maxWhen < newEnd) {
198 newEnd = alarm.maxWhen;
199 }
200 i++;
201 }
202 }
203 if (didRemove) {
204 // commit the new batch bounds
205 start = newStart;
206 end = newEnd;
207 }
208 return didRemove;
209 }
210
211 boolean remove(final String packageName) {
212 boolean didRemove = false;
213 long newStart = 0; // recalculate endpoints as we go
214 long newEnd = Long.MAX_VALUE;
215 for (int i = 0; i < alarms.size(); i++) {
216 Alarm alarm = alarms.get(i);
217 if (alarm.operation.getTargetPackage().equals(packageName)) {
218 alarms.remove(i);
219 didRemove = true;
220 } else {
221 if (alarm.whenElapsed > newStart) {
222 newStart = alarm.whenElapsed;
223 }
224 if (alarm.maxWhen < newEnd) {
225 newEnd = alarm.maxWhen;
226 }
227 i++;
228 }
229 }
230 if (didRemove) {
231 // commit the new batch bounds
232 start = newStart;
233 end = newEnd;
234 }
235 return didRemove;
236 }
237
238 boolean remove(final int userHandle) {
239 boolean didRemove = false;
240 long newStart = 0; // recalculate endpoints as we go
241 long newEnd = Long.MAX_VALUE;
242 for (int i = 0; i < alarms.size(); i++) {
243 Alarm alarm = alarms.get(i);
244 if (UserHandle.getUserId(alarm.operation.getCreatorUid()) == userHandle) {
245 alarms.remove(i);
246 didRemove = true;
247 } else {
248 if (alarm.whenElapsed > newStart) {
249 newStart = alarm.whenElapsed;
250 }
251 if (alarm.maxWhen < newEnd) {
252 newEnd = alarm.maxWhen;
253 }
254 i++;
255 }
256 }
257 if (didRemove) {
258 // commit the new batch bounds
259 start = newStart;
260 end = newEnd;
261 }
262 return didRemove;
263 }
264
265 boolean hasPackage(final String packageName) {
266 final int N = alarms.size();
267 for (int i = 0; i < N; i++) {
268 Alarm a = alarms.get(i);
269 if (a.operation.getTargetPackage().equals(packageName)) {
270 return true;
271 }
272 }
273 return false;
274 }
275
276 boolean hasWakeups() {
277 final int N = alarms.size();
278 for (int i = 0; i < N; i++) {
279 Alarm a = alarms.get(i);
280 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
281 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
282 return true;
283 }
284 }
285 return false;
286 }
287
288 @Override
289 public String toString() {
290 StringBuilder b = new StringBuilder(40);
291 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
292 b.append(" num="); b.append(size());
293 b.append(" start="); b.append(start);
294 b.append(" end="); b.append(end);
295 if (standalone) {
296 b.append(" STANDALONE");
297 }
298 b.append('}');
299 return b.toString();
300 }
301 }
302
303 static class BatchTimeOrder implements Comparator<Batch> {
304 public int compare(Batch b1, Batch b2) {
305 long when1 = b1.start;
306 long when2 = b2.start;
307 if (when1 - when2 > 0) {
308 return 1;
309 }
310 if (when1 - when2 < 0) {
311 return -1;
312 }
313 return 0;
314 }
315 }
316
317 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700318 private static final long MIN_FUZZABLE_INTERVAL = 10000;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700319 private static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
320 private final ArrayList<Batch> mAlarmBatches = new ArrayList<Batch>();
321
322 static long convertToElapsed(long when, int type) {
323 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
324 if (isRtc) {
325 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
326 }
327 return when;
328 }
329
330 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
331 // calculate the end of our nominal delivery window for the alarm.
332 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
333 // Current heuristic: batchable window is 75% of either the recurrence interval
334 // [for a periodic alarm] or of the time from now to the desired delivery time,
335 // with a minimum delay/interval of 10 seconds, under which we will simply not
336 // defer the alarm.
337 long futurity = (interval == 0)
338 ? (triggerAtTime - now)
339 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700340 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700341 futurity = 0;
342 }
343 return triggerAtTime + (long)(.75 * futurity);
344 }
345
346 // returns true if the batch was added at the head
347 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
348 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
349 if (index < 0) {
350 index = 0 - index - 1;
351 }
352 list.add(index, newBatch);
353 return (index == 0);
354 }
355
356 Batch attemptCoalesceLocked(long whenElapsed, long maxWhen) {
357 final int N = mAlarmBatches.size();
358 for (int i = 0; i < N; i++) {
359 Batch b = mAlarmBatches.get(i);
360 if (!b.standalone && b.canHold(whenElapsed, maxWhen)) {
361 return b;
362 }
363 }
364 return null;
365 }
366
367 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
368 void rebatchAllAlarms() {
369 if (DEBUG_BATCH) {
370 Slog.v(TAG, "RTC changed; rebatching");
371 }
372 synchronized (mLock) {
373 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
374 mAlarmBatches.clear();
375 final long nowElapsed = SystemClock.elapsedRealtime();
376 for (Batch batch : oldSet) {
377 final int N = batch.size();
378 for (int i = 0; i < N; i++) {
379 Alarm a = batch.get(i);
380 long whenElapsed = convertToElapsed(a.when, a.type);
381 long maxElapsed = (a.whenElapsed == a.maxWhen)
382 ? whenElapsed
383 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
384 if (batch.standalone) {
385 // this will also be the only alarm in the batch
386 a = new Alarm(a.type, a.when, whenElapsed, maxElapsed,
387 a.repeatInterval, a.operation);
388 Batch newBatch = new Batch(a);
389 newBatch.standalone = true;
390 addBatchLocked(mAlarmBatches, newBatch);
391 } else {
392 setImplLocked(a.type, a.when, whenElapsed, maxElapsed,
393 a.repeatInterval, a.operation, false);
394 }
395 }
396 }
397 }
398 }
399
Dianne Hackborn81038902012-11-26 17:04:09 -0800400 private static final class InFlight extends Intent {
401 final PendingIntent mPendingIntent;
402 final Pair<String, ComponentName> mTarget;
403 final BroadcastStats mBroadcastStats;
404 final FilterStats mFilterStats;
405
406 InFlight(AlarmManagerService service, PendingIntent pendingIntent) {
407 mPendingIntent = pendingIntent;
408 Intent intent = pendingIntent.getIntent();
409 mTarget = intent != null
410 ? new Pair<String, ComponentName>(intent.getAction(), intent.getComponent())
411 : null;
412 mBroadcastStats = service.getStatsLocked(pendingIntent);
413 FilterStats fs = mBroadcastStats.filterStats.get(mTarget);
414 if (fs == null) {
415 fs = new FilterStats(mBroadcastStats, mTarget);
416 mBroadcastStats.filterStats.put(mTarget, fs);
417 }
418 mFilterStats = fs;
419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800420 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800421
422 private static final class FilterStats {
423 final BroadcastStats mBroadcastStats;
424 final Pair<String, ComponentName> mTarget;
425
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800426 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800427 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428 int numWakeup;
429 long startTime;
430 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -0800431
432 FilterStats(BroadcastStats broadcastStats, Pair<String, ComponentName> target) {
433 mBroadcastStats = broadcastStats;
434 mTarget = target;
435 }
436 }
437
438 private static final class BroadcastStats {
439 final String mPackageName;
440
441 long aggregateTime;
442 int count;
443 int numWakeup;
444 long startTime;
445 int nesting;
446 final HashMap<Pair<String, ComponentName>, FilterStats> filterStats
447 = new HashMap<Pair<String, ComponentName>, FilterStats>();
448
449 BroadcastStats(String packageName) {
450 mPackageName = packageName;
451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800452 }
453
454 private final HashMap<String, BroadcastStats> mBroadcastStats
455 = new HashMap<String, BroadcastStats>();
456
457 public AlarmManagerService(Context context) {
458 mContext = context;
459 mDescriptor = init();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700460 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800461
462 // We have to set current TimeZone info to kernel
463 // because kernel doesn't keep this after reboot
464 String tz = SystemProperties.get(TIMEZONE_PROPERTY);
465 if (tz != null) {
466 setTimeZone(tz);
467 }
468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469 PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
470 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
471
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700472 mTimeTickSender = PendingIntent.getBroadcastAsUser(context, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800473 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700474 Intent.FLAG_RECEIVER_REGISTERED_ONLY), 0,
475 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800476 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
477 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700478 mDateChangeSender = PendingIntent.getBroadcastAsUser(context, 0, intent,
479 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480
481 // now that we have initied the driver schedule the alarm
482 mClockReceiver= new ClockReceiver();
483 mClockReceiver.scheduleTimeTickEvent();
484 mClockReceiver.scheduleDateChangedEvent();
485 mUninstallReceiver = new UninstallReceiver();
486
487 if (mDescriptor != -1) {
488 mWaitThread.start();
489 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800490 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800491 }
492 }
493
494 protected void finalize() throws Throwable {
495 try {
496 close(mDescriptor);
497 } finally {
498 super.finalize();
499 }
500 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700501
502 @Override
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700503 public void set(int type, long triggerAtTime, long windowLength, long interval,
504 PendingIntent operation) {
505 set(type, triggerAtTime, windowLength, interval, operation, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700507
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700508 public void set(int type, long triggerAtTime, long windowLength, long interval,
509 PendingIntent operation, boolean isStandalone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800510 if (operation == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800511 Slog.w(TAG, "set/setRepeating ignored because there is no intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800512 return;
513 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700514
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700515 // Sanity check the window length. This will catch people mistakenly
516 // trying to pass an end-of-window timestamp rather than a duration.
517 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
518 Slog.w(TAG, "Window length " + windowLength
519 + "ms suspiciously long; limiting to 1 hour");
520 windowLength = AlarmManager.INTERVAL_HOUR;
521 }
522
Christopher Tatee0a22b32013-07-11 14:43:13 -0700523 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
524 throw new IllegalArgumentException("Invalid alarm type " + type);
525 }
526
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700527 final long nowElapsed = SystemClock.elapsedRealtime();
528 final long triggerElapsed = convertToElapsed(triggerAtTime, type);
529 final long maxElapsed;
530 if (windowLength == AlarmManager.WINDOW_EXACT) {
531 maxElapsed = triggerElapsed;
532 } else if (windowLength < 0) {
533 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
534 } else {
535 maxElapsed = triggerElapsed + windowLength;
536 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800538 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700539 if (DEBUG_BATCH) {
540 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700541 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -0700542 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
543 + " interval=" + interval + " standalone=" + isStandalone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800544 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700545 setImplLocked(type, triggerAtTime, triggerElapsed, maxElapsed,
546 interval, operation, isStandalone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800547 }
548 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549
Christopher Tatee0a22b32013-07-11 14:43:13 -0700550 private void setImplLocked(int type, long when, long whenElapsed, long maxWhen, long interval,
551 PendingIntent operation, boolean isStandalone) {
552 Alarm a = new Alarm(type, when, whenElapsed, maxWhen, interval, operation);
553 removeLocked(operation);
Christopher Tateb8849c12011-02-08 13:39:01 -0800554
Christopher Tatee0a22b32013-07-11 14:43:13 -0700555 final boolean reschedule;
556 Batch batch = (isStandalone) ? null : attemptCoalesceLocked(whenElapsed, maxWhen);
557 if (batch == null) {
558 batch = new Batch(a);
559 batch.standalone = isStandalone;
560 if (DEBUG_BATCH) {
561 Slog.v(TAG, "Starting new alarm batch " + batch);
562 }
563 reschedule = addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800564 } else {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700565 reschedule = batch.add(a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800566 }
567
Christopher Tatee0a22b32013-07-11 14:43:13 -0700568 if (reschedule) {
569 rescheduleKernelAlarmsLocked();
570 }
571 }
572
573 private Batch findFirstWakeupBatchLocked() {
574 final int N = mAlarmBatches.size();
575 for (int i = 0; i < N; i++) {
576 Batch b = mAlarmBatches.get(i);
577 if (b.hasWakeups()) {
578 return b;
579 }
580 }
581 return null;
582 }
583
584 private void rescheduleKernelAlarmsLocked() {
585 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
586 // prior to that which contains no wakeups, we schedule that as well.
587 final Batch firstWakeup = findFirstWakeupBatchLocked();
588 final Batch firstBatch = mAlarmBatches.get(0);
589 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
590 mNextWakeup = firstWakeup.start;
591 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
592 }
593 if (firstBatch != firstWakeup && mNextNonWakeup != firstBatch.start) {
594 mNextNonWakeup = firstBatch.start;
595 setLocked(ELAPSED_REALTIME, firstBatch.start);
596 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800597 }
598
Dan Egnor97e44942010-02-04 20:27:47 -0800599 public void setTime(long millis) {
600 mContext.enforceCallingOrSelfPermission(
601 "android.permission.SET_TIME",
602 "setTime");
603
604 SystemClock.setCurrentTimeMillis(millis);
605 }
606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607 public void setTimeZone(String tz) {
608 mContext.enforceCallingOrSelfPermission(
609 "android.permission.SET_TIME_ZONE",
610 "setTimeZone");
611
Christopher Tate89779822012-08-31 14:40:03 -0700612 long oldId = Binder.clearCallingIdentity();
613 try {
614 if (TextUtils.isEmpty(tz)) return;
615 TimeZone zone = TimeZone.getTimeZone(tz);
616 // Prevent reentrant calls from stepping on each other when writing
617 // the time zone property
618 boolean timeZoneWasChanged = false;
619 synchronized (this) {
620 String current = SystemProperties.get(TIMEZONE_PROPERTY);
621 if (current == null || !current.equals(zone.getID())) {
622 if (localLOGV) {
623 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
624 }
625 timeZoneWasChanged = true;
626 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
627 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800628
Christopher Tate89779822012-08-31 14:40:03 -0700629 // Update the kernel timezone information
630 // Kernel tracks time offsets as 'minutes west of GMT'
631 int gmtOffset = zone.getOffset(System.currentTimeMillis());
632 setKernelTimezone(mDescriptor, -(gmtOffset / 60000));
633 }
634
635 TimeZone.setDefault(null);
636
637 if (timeZoneWasChanged) {
638 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
639 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
640 intent.putExtra("time-zone", zone.getID());
641 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
642 }
643 } finally {
644 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 }
646 }
647
648 public void remove(PendingIntent operation) {
649 if (operation == null) {
650 return;
651 }
652 synchronized (mLock) {
653 removeLocked(operation);
654 }
655 }
656
657 public void removeLocked(PendingIntent operation) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700658 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
659 Batch b = mAlarmBatches.get(i);
660 b.remove(operation);
661 if (b.size() == 0) {
662 mAlarmBatches.remove(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800663 }
664 }
665 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 public void removeLocked(String packageName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700668 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
669 Batch b = mAlarmBatches.get(i);
670 b.remove(packageName);
671 if (b.size() == 0) {
672 mAlarmBatches.remove(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673 }
674 }
675 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700676
677 public void removeUserLocked(int userHandle) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700678 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
679 Batch b = mAlarmBatches.get(i);
680 b.remove(userHandle);
681 if (b.size() == 0) {
682 mAlarmBatches.remove(i);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700683 }
684 }
685 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -0800686
Christopher Tatee0a22b32013-07-11 14:43:13 -0700687 public boolean lookForPackageLocked(String packageName) {
688 for (int i = 0; i < mAlarmBatches.size(); i++) {
689 Batch b = mAlarmBatches.get(i);
690 if (b.hasPackage(packageName)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -0800691 return true;
692 }
693 }
694 return false;
695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696
Christopher Tatee0a22b32013-07-11 14:43:13 -0700697 private void setLocked(int type, long when)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698 {
699 if (mDescriptor != -1)
700 {
Jeff Brown11c5f1a2010-03-31 15:29:40 -0700701 // The kernel never triggers alarms with negative wakeup times
702 // so we ensure they are positive.
703 long alarmSeconds, alarmNanoseconds;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700704 if (when < 0) {
Jeff Brown11c5f1a2010-03-31 15:29:40 -0700705 alarmSeconds = 0;
706 alarmNanoseconds = 0;
707 } else {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700708 alarmSeconds = when / 1000;
709 alarmNanoseconds = (when % 1000) * 1000 * 1000;
Jeff Brown11c5f1a2010-03-31 15:29:40 -0700710 }
711
Christopher Tatee0a22b32013-07-11 14:43:13 -0700712 set(mDescriptor, type, alarmSeconds, alarmNanoseconds);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 }
714 else
715 {
716 Message msg = Message.obtain();
717 msg.what = ALARM_EVENT;
718
719 mHandler.removeMessages(ALARM_EVENT);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700720 mHandler.sendMessageAtTime(msg, when);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 }
722 }
723
724 @Override
725 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
726 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
727 != PackageManager.PERMISSION_GRANTED) {
728 pw.println("Permission Denial: can't dump AlarmManager from from pid="
729 + Binder.getCallingPid()
730 + ", uid=" + Binder.getCallingUid());
731 return;
732 }
733
734 synchronized (mLock) {
735 pw.println("Current Alarm Manager state:");
Christopher Tatee0a22b32013-07-11 14:43:13 -0700736 final long nowRTC = System.currentTimeMillis();
737 final long nowELAPSED = SystemClock.elapsedRealtime();
738 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
739
740 pw.print("nowRTC="); pw.print(nowRTC);
741 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
742 pw.print(" nowELAPSED="); pw.println(nowELAPSED);
743
744 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
745 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
746 pw.print("Next alarm: "); pw.print(mNextNonWakeup);
747 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
748 pw.print("Next wakeup: "); pw.print(mNextWakeup);
749 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
750
751 if (mAlarmBatches.size() > 0) {
752 pw.println();
753 pw.print("Pending alarm batches: ");
754 pw.println(mAlarmBatches.size());
755 for (Batch b : mAlarmBatches) {
756 pw.print(b); pw.println(':');
757 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC);
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700758 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800760
761 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700762 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -0800763 pw.println();
764
765 if (mLog.dump(pw, " Recent problems", " ")) {
766 pw.println();
767 }
768
769 final FilterStats[] topFilters = new FilterStats[10];
770 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
771 @Override
772 public int compare(FilterStats lhs, FilterStats rhs) {
773 if (lhs.aggregateTime < rhs.aggregateTime) {
774 return 1;
775 } else if (lhs.aggregateTime > rhs.aggregateTime) {
776 return -1;
777 }
778 return 0;
779 }
780 };
781 int len = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 for (Map.Entry<String, BroadcastStats> be : mBroadcastStats.entrySet()) {
783 BroadcastStats bs = be.getValue();
Dianne Hackborn81038902012-11-26 17:04:09 -0800784 for (Map.Entry<Pair<String, ComponentName>, FilterStats> fe
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 : bs.filterStats.entrySet()) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800786 FilterStats fs = fe.getValue();
787 int pos = len > 0
788 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
789 if (pos < 0) {
790 pos = -pos - 1;
791 }
792 if (pos < topFilters.length) {
793 int copylen = topFilters.length - pos - 1;
794 if (copylen > 0) {
795 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
796 }
797 topFilters[pos] = fs;
798 if (len < topFilters.length) {
799 len++;
800 }
801 }
802 }
803 }
804 if (len > 0) {
805 pw.println(" Top Alarms:");
806 for (int i=0; i<len; i++) {
807 FilterStats fs = topFilters[i];
808 pw.print(" ");
809 if (fs.nesting > 0) pw.print("*ACTIVE* ");
810 TimeUtils.formatDuration(fs.aggregateTime, pw);
811 pw.print(" running, "); pw.print(fs.numWakeup);
812 pw.print(" wakeups, "); pw.print(fs.count);
813 pw.print(" alarms: "); pw.print(fs.mBroadcastStats.mPackageName);
814 pw.println();
815 pw.print(" ");
816 if (fs.mTarget.first != null) {
817 pw.print(" act="); pw.print(fs.mTarget.first);
818 }
819 if (fs.mTarget.second != null) {
820 pw.print(" cmp="); pw.print(fs.mTarget.second.toShortString());
821 }
822 pw.println();
823 }
824 }
825
826 pw.println(" ");
827 pw.println(" Alarm Stats:");
828 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
829 for (Map.Entry<String, BroadcastStats> be : mBroadcastStats.entrySet()) {
830 BroadcastStats bs = be.getValue();
831 pw.print(" ");
832 if (bs.nesting > 0) pw.print("*ACTIVE* ");
833 pw.print(be.getKey());
834 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
835 pw.print(" running, "); pw.print(bs.numWakeup);
836 pw.println(" wakeups:");
837 tmpFilters.clear();
838 for (Map.Entry<Pair<String, ComponentName>, FilterStats> fe
839 : bs.filterStats.entrySet()) {
840 tmpFilters.add(fe.getValue());
841 }
842 Collections.sort(tmpFilters, comparator);
843 for (int i=0; i<tmpFilters.size(); i++) {
844 FilterStats fs = tmpFilters.get(i);
845 pw.print(" ");
846 if (fs.nesting > 0) pw.print("*ACTIVE* ");
847 TimeUtils.formatDuration(fs.aggregateTime, pw);
848 pw.print(" "); pw.print(fs.numWakeup);
849 pw.print(" wakes " ); pw.print(fs.count);
850 pw.print(" alarms:");
851 if (fs.mTarget.first != null) {
852 pw.print(" act="); pw.print(fs.mTarget.first);
853 }
854 if (fs.mTarget.second != null) {
855 pw.print(" cmp="); pw.print(fs.mTarget.second.toShortString());
856 }
857 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858 }
859 }
Christopher Tate18a75f12013-07-01 18:18:59 -0700860
861 if (WAKEUP_STATS) {
862 pw.println();
863 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -0700864 long last = -1;
865 for (WakeupEvent event : mRecentWakeups) {
866 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
867 pw.print('|');
868 if (last < 0) {
869 pw.print('0');
870 } else {
871 pw.print(event.when - last);
872 }
873 last = event.when;
874 pw.print('|'); pw.print(event.uid);
875 pw.print('|'); pw.print(event.action);
876 pw.println();
877 }
878 pw.println();
879 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 }
881 }
882
Dianne Hackborn043fcd92010-10-06 14:27:34 -0700883 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
884 String prefix, String label, long now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 for (int i=list.size()-1; i>=0; i--) {
886 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700887 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
888 pw.print(": "); pw.println(a);
Dianne Hackborn043fcd92010-10-06 14:27:34 -0700889 a.dump(pw, prefix + " ", now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 }
891 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700892
893 private static final String labelForType(int type) {
894 switch (type) {
895 case RTC: return "RTC";
896 case RTC_WAKEUP : return "RTC_WAKEUP";
897 case ELAPSED_REALTIME : return "ELAPSED";
898 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
899 default:
900 break;
901 }
902 return "--unknown--";
903 }
904
905 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
906 String prefix, long nowELAPSED, long nowRTC) {
907 for (int i=list.size()-1; i>=0; i--) {
908 Alarm a = list.get(i);
909 final String label = labelForType(a.type);
910 long now = (a.type <= RTC) ? nowRTC : nowELAPSED;
911 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
912 pw.print(": "); pw.println(a);
913 a.dump(pw, prefix + " ", now);
914 }
915 }
916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 private native int init();
918 private native void close(int fd);
Jeff Brown11c5f1a2010-03-31 15:29:40 -0700919 private native void set(int fd, int type, long seconds, long nanoseconds);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920 private native int waitForAlarm(int fd);
921 private native int setKernelTimezone(int fd, int minuteswest);
922
Christopher Tatee0a22b32013-07-11 14:43:13 -0700923 private void triggerAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED, long nowRTC) {
924 Batch batch;
Dianne Hackborn390517b2013-05-30 15:03:32 -0700925
Christopher Tatee0a22b32013-07-11 14:43:13 -0700926 // batches are temporally sorted, so we need only pull from the
927 // start of the list until we either empty it or hit a batch
928 // that is not yet deliverable
929 while ((batch = mAlarmBatches.get(0)) != null) {
930 if (batch.start > nowELAPSED) {
931 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 break;
933 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934
Christopher Tatee0a22b32013-07-11 14:43:13 -0700935 // We will (re)schedule some alarms now; don't let that interfere
936 // with delivery of this current batch
937 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -0700938
Christopher Tatee0a22b32013-07-11 14:43:13 -0700939 final int N = batch.size();
940 for (int i = 0; i < N; i++) {
941 Alarm alarm = batch.get(i);
942 alarm.count = 1;
943 triggerList.add(alarm);
944
945 // Recurring alarms may have passed several alarm intervals while the
946 // phone was asleep or off, so pass a trigger count when sending them.
947 if (alarm.repeatInterval > 0) {
948 // this adjustment will be zero if we're late by
949 // less than one full repeat interval
950 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
951
952 // Also schedule its next recurrence
953 final long delta = alarm.count * alarm.repeatInterval;
954 final long nextElapsed = alarm.whenElapsed + delta;
955 setImplLocked(alarm.type, alarm.when + delta, nextElapsed,
956 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
957 alarm.repeatInterval, alarm.operation, batch.standalone);
Dianne Hackborn390517b2013-05-30 15:03:32 -0700958 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959
Dianne Hackborn390517b2013-05-30 15:03:32 -0700960 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700963
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 /**
965 * This Comparator sorts Alarms into increasing time order.
966 */
967 public static class IncreasingTimeOrder implements Comparator<Alarm> {
968 public int compare(Alarm a1, Alarm a2) {
969 long when1 = a1.when;
970 long when2 = a2.when;
971 if (when1 - when2 > 0) {
972 return 1;
973 }
974 if (when1 - when2 < 0) {
975 return -1;
976 }
977 return 0;
978 }
979 }
980
981 private static class Alarm {
982 public int type;
983 public int count;
984 public long when;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700985 public long whenElapsed; // 'when' in the elapsed time base
986 public long maxWhen; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 public long repeatInterval;
988 public PendingIntent operation;
989
Christopher Tatee0a22b32013-07-11 14:43:13 -0700990 public Alarm(int _type, long _when, long _whenElapsed, long _maxWhen,
991 long _interval, PendingIntent _op) {
992 type = _type;
993 when = _when;
994 whenElapsed = _whenElapsed;
995 maxWhen = _maxWhen;
996 repeatInterval = _interval;
997 operation = _op;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700999
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000 @Override
1001 public String toString()
1002 {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001003 StringBuilder sb = new StringBuilder(128);
1004 sb.append("Alarm{");
1005 sb.append(Integer.toHexString(System.identityHashCode(this)));
1006 sb.append(" type ");
1007 sb.append(type);
1008 sb.append(" ");
1009 sb.append(operation.getTargetPackage());
1010 sb.append('}');
1011 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 }
1013
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001014 public void dump(PrintWriter pw, String prefix, long now) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001015 pw.print(prefix); pw.print("type="); pw.print(type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001016 pw.print(" whenElapsed="); pw.print(whenElapsed);
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001017 pw.print(" when="); TimeUtils.formatDuration(when, now, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001018 pw.print(" repeatInterval="); pw.print(repeatInterval);
1019 pw.print(" count="); pw.println(count);
1020 pw.print(prefix); pw.print("operation="); pw.println(operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021 }
1022 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001023
Christopher Tatee0a22b32013-07-11 14:43:13 -07001024 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
1025 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07001026 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
1027 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001028 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07001029 break;
1030 }
1031
Christopher Tatee0a22b32013-07-11 14:43:13 -07001032 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07001033 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
1034 Alarm a = b.alarms.get(nextAlarm);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001035 WakeupEvent e = new WakeupEvent(nowRTC,
1036 a.operation.getCreatorUid(),
1037 a.operation.getIntent().getAction());
1038 mRecentWakeups.add(e);
1039 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001040 }
1041 }
1042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 private class AlarmThread extends Thread
1044 {
1045 public AlarmThread()
1046 {
1047 super("AlarmManager");
1048 }
1049
1050 public void run()
1051 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07001052 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
1053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 while (true)
1055 {
1056 int result = waitForAlarm(mDescriptor);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001057
1058 triggerList.clear();
1059
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 if ((result & TIME_CHANGED_MASK) != 0) {
1061 remove(mTimeTickSender);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001062 rebatchAllAlarms();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 mClockReceiver.scheduleTimeTickEvent();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001064 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
Dianne Hackborn89ba6752011-01-23 16:51:16 -08001065 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1066 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001067 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 }
1069
1070 synchronized (mLock) {
1071 final long nowRTC = System.currentTimeMillis();
1072 final long nowELAPSED = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001073 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 TAG, "Checking for alarms... rtc=" + nowRTC
1075 + ", elapsed=" + nowELAPSED);
1076
Christopher Tate18a75f12013-07-01 18:18:59 -07001077 if (WAKEUP_STATS) {
1078 if ((result & IS_WAKEUP_MASK) != 0) {
1079 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
1080 int n = 0;
1081 for (WakeupEvent event : mRecentWakeups) {
1082 if (event.when > newEarliest) break;
1083 n++; // number of now-stale entries at the list head
1084 }
1085 for (int i = 0; i < n; i++) {
1086 mRecentWakeups.remove();
1087 }
1088
Christopher Tatee0a22b32013-07-11 14:43:13 -07001089 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Christopher Tate18a75f12013-07-01 18:18:59 -07001090 }
1091 }
1092
Christopher Tatee0a22b32013-07-11 14:43:13 -07001093 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
1094 rescheduleKernelAlarmsLocked();
1095
1096 // now deliver the alarm intents
Dianne Hackborn390517b2013-05-30 15:03:32 -07001097 for (int i=0; i<triggerList.size(); i++) {
1098 Alarm alarm = triggerList.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001100 if (localLOGV) Slog.v(TAG, "sending alarm " + alarm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001101 alarm.operation.send(mContext, 0,
1102 mBackgroundIntent.putExtra(
1103 Intent.EXTRA_ALARM_COUNT, alarm.count),
1104 mResultReceiver, mHandler);
1105
Christopher Tatec4a07d12012-04-06 14:19:13 -07001106 // we have an active broadcast so stay awake.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 if (mBroadcastRefCount == 0) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07001108 setWakelockWorkSource(alarm.operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 mWakeLock.acquire();
1110 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001111 final InFlight inflight = new InFlight(AlarmManagerService.this,
1112 alarm.operation);
1113 mInFlight.add(inflight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001114 mBroadcastRefCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08001115
1116 final BroadcastStats bs = inflight.mBroadcastStats;
1117 bs.count++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 if (bs.nesting == 0) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001119 bs.nesting = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 bs.startTime = nowELAPSED;
1121 } else {
1122 bs.nesting++;
1123 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001124 final FilterStats fs = inflight.mFilterStats;
1125 fs.count++;
1126 if (fs.nesting == 0) {
1127 fs.nesting = 1;
1128 fs.startTime = nowELAPSED;
1129 } else {
1130 fs.nesting++;
1131 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001132 if (alarm.type == ELAPSED_REALTIME_WAKEUP
1133 || alarm.type == RTC_WAKEUP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 bs.numWakeup++;
Dianne Hackborn81038902012-11-26 17:04:09 -08001135 fs.numWakeup++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001136 ActivityManagerNative.noteWakeupAlarm(
1137 alarm.operation);
1138 }
1139 } catch (PendingIntent.CanceledException e) {
1140 if (alarm.repeatInterval > 0) {
1141 // This IntentSender is no longer valid, but this
1142 // is a repeating alarm, so toss the hoser.
1143 remove(alarm.operation);
1144 }
1145 } catch (RuntimeException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001146 Slog.w(TAG, "Failure sending alarm.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 }
1148 }
1149 }
1150 }
1151 }
1152 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07001153
1154 void setWakelockWorkSource(PendingIntent pi) {
1155 try {
1156 final int uid = ActivityManagerNative.getDefault()
1157 .getUidForIntentSender(pi.getTarget());
1158 if (uid >= 0) {
1159 mWakeLock.setWorkSource(new WorkSource(uid));
1160 return;
1161 }
1162 } catch (Exception e) {
1163 }
1164
1165 // Something went wrong; fall back to attributing the lock to the OS
1166 mWakeLock.setWorkSource(null);
1167 }
1168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 private class AlarmHandler extends Handler {
1170 public static final int ALARM_EVENT = 1;
1171 public static final int MINUTE_CHANGE_EVENT = 2;
1172 public static final int DATE_CHANGE_EVENT = 3;
1173
1174 public AlarmHandler() {
1175 }
1176
1177 public void handleMessage(Message msg) {
1178 if (msg.what == ALARM_EVENT) {
1179 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
1180 synchronized (mLock) {
1181 final long nowRTC = System.currentTimeMillis();
Christopher Tatee0a22b32013-07-11 14:43:13 -07001182 final long nowELAPSED = SystemClock.elapsedRealtime();
1183 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 }
1185
1186 // now trigger the alarms without the lock held
Dianne Hackborn390517b2013-05-30 15:03:32 -07001187 for (int i=0; i<triggerList.size(); i++) {
1188 Alarm alarm = triggerList.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189 try {
1190 alarm.operation.send();
1191 } catch (PendingIntent.CanceledException e) {
1192 if (alarm.repeatInterval > 0) {
1193 // This IntentSender is no longer valid, but this
1194 // is a repeating alarm, so toss the hoser.
1195 remove(alarm.operation);
1196 }
1197 }
1198 }
1199 }
1200 }
1201 }
1202
1203 class ClockReceiver extends BroadcastReceiver {
1204 public ClockReceiver() {
1205 IntentFilter filter = new IntentFilter();
1206 filter.addAction(Intent.ACTION_TIME_TICK);
1207 filter.addAction(Intent.ACTION_DATE_CHANGED);
1208 mContext.registerReceiver(this, filter);
1209 }
1210
1211 @Override
1212 public void onReceive(Context context, Intent intent) {
1213 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
1214 scheduleTimeTickEvent();
1215 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
1216 // Since the kernel does not keep track of DST, we need to
1217 // reset the TZ information at the beginning of each day
1218 // based off of the current Zone gmt offset + userspace tracked
1219 // daylight savings information.
1220 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02001221 int gmtOffset = zone.getOffset(System.currentTimeMillis());
1222 setKernelTimezone(mDescriptor, -(gmtOffset / 60000));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223 scheduleDateChangedEvent();
1224 }
1225 }
1226
1227 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07001228 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09001229 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07001230
1231 // Schedule this event for the amount of time that it would take to get to
1232 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09001233 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07001234
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001235 set(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
1236 0, mTimeTickSender, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237 }
1238
1239 public void scheduleDateChangedEvent() {
1240 Calendar calendar = Calendar.getInstance();
1241 calendar.setTimeInMillis(System.currentTimeMillis());
1242 calendar.set(Calendar.HOUR, 0);
1243 calendar.set(Calendar.MINUTE, 0);
1244 calendar.set(Calendar.SECOND, 0);
1245 calendar.set(Calendar.MILLISECOND, 0);
1246 calendar.add(Calendar.DAY_OF_MONTH, 1);
1247
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001248 set(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249 }
1250 }
1251
1252 class UninstallReceiver extends BroadcastReceiver {
1253 public UninstallReceiver() {
1254 IntentFilter filter = new IntentFilter();
1255 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1256 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001257 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001258 filter.addDataScheme("package");
1259 mContext.registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001260 // Register for events related to sdcard installation.
1261 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001262 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001263 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001264 mContext.registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265 }
1266
1267 @Override
1268 public void onReceive(Context context, Intent intent) {
1269 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001270 String action = intent.getAction();
1271 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001272 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
1273 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
1274 for (String packageName : pkgList) {
1275 if (lookForPackageLocked(packageName)) {
1276 setResultCode(Activity.RESULT_OK);
1277 return;
1278 }
1279 }
1280 return;
1281 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001282 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001283 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
1284 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
1285 if (userHandle >= 0) {
1286 removeUserLocked(userHandle);
1287 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001288 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08001289 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
1290 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
1291 // This package is being updated; don't kill its alarms.
1292 return;
1293 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001294 Uri data = intent.getData();
1295 if (data != null) {
1296 String pkg = data.getSchemeSpecificPart();
1297 if (pkg != null) {
1298 pkgList = new String[]{pkg};
1299 }
1300 }
1301 }
1302 if (pkgList != null && (pkgList.length > 0)) {
1303 for (String pkg : pkgList) {
1304 removeLocked(pkg);
1305 mBroadcastStats.remove(pkg);
1306 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307 }
1308 }
1309 }
1310 }
1311
1312 private final BroadcastStats getStatsLocked(PendingIntent pi) {
1313 String pkg = pi.getTargetPackage();
1314 BroadcastStats bs = mBroadcastStats.get(pkg);
1315 if (bs == null) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001316 bs = new BroadcastStats(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 mBroadcastStats.put(pkg, bs);
1318 }
1319 return bs;
1320 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001321
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 class ResultReceiver implements PendingIntent.OnFinished {
1323 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
1324 String resultData, Bundle resultExtras) {
1325 synchronized (mLock) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001326 InFlight inflight = null;
1327 for (int i=0; i<mInFlight.size(); i++) {
1328 if (mInFlight.get(i).mPendingIntent == pi) {
1329 inflight = mInFlight.remove(i);
1330 break;
1331 }
1332 }
1333 if (inflight != null) {
1334 final long nowELAPSED = SystemClock.elapsedRealtime();
1335 BroadcastStats bs = inflight.mBroadcastStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001336 bs.nesting--;
1337 if (bs.nesting <= 0) {
1338 bs.nesting = 0;
Dianne Hackborn81038902012-11-26 17:04:09 -08001339 bs.aggregateTime += nowELAPSED - bs.startTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001341 FilterStats fs = inflight.mFilterStats;
1342 fs.nesting--;
1343 if (fs.nesting <= 0) {
1344 fs.nesting = 0;
1345 fs.aggregateTime += nowELAPSED - fs.startTime;
1346 }
1347 } else {
1348 mLog.w("No in-flight alarm for " + pi + " " + intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001349 }
1350 mBroadcastRefCount--;
1351 if (mBroadcastRefCount == 0) {
1352 mWakeLock.release();
Dianne Hackborn81038902012-11-26 17:04:09 -08001353 if (mInFlight.size() > 0) {
1354 mLog.w("Finished all broadcasts with " + mInFlight.size()
1355 + " remaining inflights");
1356 for (int i=0; i<mInFlight.size(); i++) {
1357 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
1358 }
1359 mInFlight.clear();
1360 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07001361 } else {
1362 // the next of our alarms is now in flight. reattribute the wakelock.
Dianne Hackborn81038902012-11-26 17:04:09 -08001363 if (mInFlight.size() > 0) {
1364 setWakelockWorkSource(mInFlight.get(0).mPendingIntent);
Christopher Tatec4a07d12012-04-06 14:19:13 -07001365 } else {
1366 // should never happen
Dianne Hackborn81038902012-11-26 17:04:09 -08001367 mLog.w("Alarm wakelock still held but sent queue empty");
Christopher Tatec4a07d12012-04-06 14:19:13 -07001368 mWakeLock.setWorkSource(null);
1369 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 }
1371 }
1372 }
1373 }
1374}