blob: b1489ad8d241dd3c4af1b996cdfbae526d34d6d1 [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import android.app.IAlarmManager;
22import android.app.PendingIntent;
23import android.content.BroadcastReceiver;
Dianne Hackborn81038902012-11-26 17:04:09 -080024import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.content.Context;
26import android.content.Intent;
27import android.content.IntentFilter;
28import android.content.pm.PackageManager;
29import android.net.Uri;
30import android.os.Binder;
31import android.os.Bundle;
32import android.os.Handler;
33import android.os.Message;
34import android.os.PowerManager;
35import android.os.SystemClock;
36import android.os.SystemProperties;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070037import android.os.UserHandle;
Christopher Tatec4a07d12012-04-06 14:19:13 -070038import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.text.TextUtils;
Dianne Hackborn81038902012-11-26 17:04:09 -080040import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -080041import android.util.Slog;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070042import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043
44import java.io.FileDescriptor;
45import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070046import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -080048import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import java.util.Calendar;
50import java.util.Collections;
51import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -050052import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -070054import java.util.LinkedList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import java.util.Map;
56import java.util.TimeZone;
57
Christopher Tatee0a22b32013-07-11 14:43:13 -070058import static android.app.AlarmManager.RTC_WAKEUP;
59import static android.app.AlarmManager.RTC;
60import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
61import static android.app.AlarmManager.ELAPSED_REALTIME;
62
Dianne Hackborn81038902012-11-26 17:04:09 -080063import com.android.internal.util.LocalLog;
64
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065class AlarmManagerService extends IAlarmManager.Stub {
66 // The threshold for how long an alarm can be late before we print a
67 // warning message. The time duration is in milliseconds.
68 private static final long LATE_ALARM_THRESHOLD = 10 * 1000;
Christopher Tatee0a22b32013-07-11 14:43:13 -070069
70 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
71 private static final int RTC_MASK = 1 << RTC;
72 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
73 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074 private static final int TIME_CHANGED_MASK = 1 << 16;
Christopher Tate18a75f12013-07-01 18:18:59 -070075 private static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -080076
Christopher Tatee0a22b32013-07-11 14:43:13 -070077 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
78 private static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -080079
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080 private static final String TAG = "AlarmManager";
81 private static final String ClockReceiver_TAG = "ClockReceiver";
82 private static final boolean localLOGV = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -070083 private static final boolean DEBUG_BATCH = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084 private static final int ALARM_EVENT = 1;
85 private static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
86
87 private static final Intent mBackgroundIntent
88 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Christopher Tatee0a22b32013-07-11 14:43:13 -070089 private static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090
Christopher Tate18a75f12013-07-01 18:18:59 -070091 private static final boolean WAKEUP_STATS = true;
92
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093 private final Context mContext;
Dianne Hackborn81038902012-11-26 17:04:09 -080094
95 private final LocalLog mLog = new LocalLog(TAG);
96
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097 private Object mLock = new Object();
Christopher Tatee0a22b32013-07-11 14:43:13 -070098
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099 private int mDescriptor;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700100 private long mNextWakeup;
101 private long mNextNonWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102 private int mBroadcastRefCount = 0;
103 private PowerManager.WakeLock mWakeLock;
Dianne Hackborn81038902012-11-26 17:04:09 -0800104 private ArrayList<InFlight> mInFlight = new ArrayList<InFlight>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105 private final AlarmThread mWaitThread = new AlarmThread();
106 private final AlarmHandler mHandler = new AlarmHandler();
107 private ClockReceiver mClockReceiver;
108 private UninstallReceiver mUninstallReceiver;
109 private final ResultReceiver mResultReceiver = new ResultReceiver();
110 private final PendingIntent mTimeTickSender;
111 private final PendingIntent mDateChangeSender;
Dianne Hackborn81038902012-11-26 17:04:09 -0800112
Christopher Tate18a75f12013-07-01 18:18:59 -0700113 class WakeupEvent {
114 public long when;
115 public int uid;
116 public String action;
117
118 public WakeupEvent(long theTime, int theUid, String theAction) {
119 when = theTime;
120 uid = theUid;
121 action = theAction;
122 }
123 }
124
125 private final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
126 private final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
127
Christopher Tatee0a22b32013-07-11 14:43:13 -0700128 static final class Batch {
129 long start; // These endpoints are always in ELAPSED
130 long end;
131 boolean standalone; // certain "batches" don't participate in coalescing
132
133 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
134
135 Batch() {
136 start = 0;
137 end = Long.MAX_VALUE;
138 }
139
140 Batch(Alarm seed) {
141 start = seed.whenElapsed;
142 end = seed.maxWhen;
143 alarms.add(seed);
144 }
145
146 int size() {
147 return alarms.size();
148 }
149
150 Alarm get(int index) {
151 return alarms.get(index);
152 }
153
154 boolean canHold(long whenElapsed, long maxWhen) {
155 return (end >= whenElapsed) && (start <= maxWhen);
156 }
157
158 boolean add(Alarm alarm) {
159 boolean newStart = false;
160 // narrows the batch if necessary; presumes that canHold(alarm) is true
161 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
162 if (index < 0) {
163 index = 0 - index - 1;
164 }
165 alarms.add(index, alarm);
166 if (DEBUG_BATCH) {
167 Slog.v(TAG, "Adding " + alarm + " to " + this);
168 }
169 if (alarm.whenElapsed > start) {
170 start = alarm.whenElapsed;
171 newStart = true;
172 }
173 if (alarm.maxWhen < end) {
174 end = alarm.maxWhen;
175 }
176
177 if (DEBUG_BATCH) {
178 Slog.v(TAG, " => now " + this);
179 }
180 return newStart;
181 }
182
183 boolean remove(final PendingIntent operation) {
184 boolean didRemove = false;
185 long newStart = 0; // recalculate endpoints as we go
186 long newEnd = Long.MAX_VALUE;
187 for (int i = 0; i < alarms.size(); i++) {
188 Alarm alarm = alarms.get(i);
189 if (alarm.operation.equals(operation)) {
190 alarms.remove(i);
191 didRemove = true;
192 } else {
193 if (alarm.whenElapsed > newStart) {
194 newStart = alarm.whenElapsed;
195 }
196 if (alarm.maxWhen < newEnd) {
197 newEnd = alarm.maxWhen;
198 }
199 i++;
200 }
201 }
202 if (didRemove) {
203 // commit the new batch bounds
204 start = newStart;
205 end = newEnd;
206 }
207 return didRemove;
208 }
209
210 boolean remove(final String packageName) {
211 boolean didRemove = false;
212 long newStart = 0; // recalculate endpoints as we go
213 long newEnd = Long.MAX_VALUE;
214 for (int i = 0; i < alarms.size(); i++) {
215 Alarm alarm = alarms.get(i);
216 if (alarm.operation.getTargetPackage().equals(packageName)) {
217 alarms.remove(i);
218 didRemove = true;
219 } else {
220 if (alarm.whenElapsed > newStart) {
221 newStart = alarm.whenElapsed;
222 }
223 if (alarm.maxWhen < newEnd) {
224 newEnd = alarm.maxWhen;
225 }
226 i++;
227 }
228 }
229 if (didRemove) {
230 // commit the new batch bounds
231 start = newStart;
232 end = newEnd;
233 }
234 return didRemove;
235 }
236
237 boolean remove(final int userHandle) {
238 boolean didRemove = false;
239 long newStart = 0; // recalculate endpoints as we go
240 long newEnd = Long.MAX_VALUE;
241 for (int i = 0; i < alarms.size(); i++) {
242 Alarm alarm = alarms.get(i);
243 if (UserHandle.getUserId(alarm.operation.getCreatorUid()) == userHandle) {
244 alarms.remove(i);
245 didRemove = true;
246 } 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 hasPackage(final String packageName) {
265 final int N = alarms.size();
266 for (int i = 0; i < N; i++) {
267 Alarm a = alarms.get(i);
268 if (a.operation.getTargetPackage().equals(packageName)) {
269 return true;
270 }
271 }
272 return false;
273 }
274
275 boolean hasWakeups() {
276 final int N = alarms.size();
277 for (int i = 0; i < N; i++) {
278 Alarm a = alarms.get(i);
279 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
280 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
281 return true;
282 }
283 }
284 return false;
285 }
286
287 @Override
288 public String toString() {
289 StringBuilder b = new StringBuilder(40);
290 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
291 b.append(" num="); b.append(size());
292 b.append(" start="); b.append(start);
293 b.append(" end="); b.append(end);
294 if (standalone) {
295 b.append(" STANDALONE");
296 }
297 b.append('}');
298 return b.toString();
299 }
300 }
301
302 static class BatchTimeOrder implements Comparator<Batch> {
303 public int compare(Batch b1, Batch b2) {
304 long when1 = b1.start;
305 long when2 = b2.start;
306 if (when1 - when2 > 0) {
307 return 1;
308 }
309 if (when1 - when2 < 0) {
310 return -1;
311 }
312 return 0;
313 }
314 }
315
316 // minimum recurrence period or alarm futurity for us to be able to fuzz it
317 private static final long MAX_FUZZABLE_INTERVAL = 10000;
318 private static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
319 private final ArrayList<Batch> mAlarmBatches = new ArrayList<Batch>();
320
321 static long convertToElapsed(long when, int type) {
322 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
323 if (isRtc) {
324 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
325 }
326 return when;
327 }
328
329 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
330 // calculate the end of our nominal delivery window for the alarm.
331 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
332 // Current heuristic: batchable window is 75% of either the recurrence interval
333 // [for a periodic alarm] or of the time from now to the desired delivery time,
334 // with a minimum delay/interval of 10 seconds, under which we will simply not
335 // defer the alarm.
336 long futurity = (interval == 0)
337 ? (triggerAtTime - now)
338 : interval;
339 if (futurity < MAX_FUZZABLE_INTERVAL) {
340 futurity = 0;
341 }
342 return triggerAtTime + (long)(.75 * futurity);
343 }
344
345 // returns true if the batch was added at the head
346 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
347 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
348 if (index < 0) {
349 index = 0 - index - 1;
350 }
351 list.add(index, newBatch);
352 return (index == 0);
353 }
354
355 Batch attemptCoalesceLocked(long whenElapsed, long maxWhen) {
356 final int N = mAlarmBatches.size();
357 for (int i = 0; i < N; i++) {
358 Batch b = mAlarmBatches.get(i);
359 if (!b.standalone && b.canHold(whenElapsed, maxWhen)) {
360 return b;
361 }
362 }
363 return null;
364 }
365
366 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
367 void rebatchAllAlarms() {
368 if (DEBUG_BATCH) {
369 Slog.v(TAG, "RTC changed; rebatching");
370 }
371 synchronized (mLock) {
372 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
373 mAlarmBatches.clear();
374 final long nowElapsed = SystemClock.elapsedRealtime();
375 for (Batch batch : oldSet) {
376 final int N = batch.size();
377 for (int i = 0; i < N; i++) {
378 Alarm a = batch.get(i);
379 long whenElapsed = convertToElapsed(a.when, a.type);
380 long maxElapsed = (a.whenElapsed == a.maxWhen)
381 ? whenElapsed
382 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
383 if (batch.standalone) {
384 // this will also be the only alarm in the batch
385 a = new Alarm(a.type, a.when, whenElapsed, maxElapsed,
386 a.repeatInterval, a.operation);
387 Batch newBatch = new Batch(a);
388 newBatch.standalone = true;
389 addBatchLocked(mAlarmBatches, newBatch);
390 } else {
391 setImplLocked(a.type, a.when, whenElapsed, maxElapsed,
392 a.repeatInterval, a.operation, false);
393 }
394 }
395 }
396 }
397 }
398
Dianne Hackborn81038902012-11-26 17:04:09 -0800399 private static final class InFlight extends Intent {
400 final PendingIntent mPendingIntent;
401 final Pair<String, ComponentName> mTarget;
402 final BroadcastStats mBroadcastStats;
403 final FilterStats mFilterStats;
404
405 InFlight(AlarmManagerService service, PendingIntent pendingIntent) {
406 mPendingIntent = pendingIntent;
407 Intent intent = pendingIntent.getIntent();
408 mTarget = intent != null
409 ? new Pair<String, ComponentName>(intent.getAction(), intent.getComponent())
410 : null;
411 mBroadcastStats = service.getStatsLocked(pendingIntent);
412 FilterStats fs = mBroadcastStats.filterStats.get(mTarget);
413 if (fs == null) {
414 fs = new FilterStats(mBroadcastStats, mTarget);
415 mBroadcastStats.filterStats.put(mTarget, fs);
416 }
417 mFilterStats = fs;
418 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800419 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800420
421 private static final class FilterStats {
422 final BroadcastStats mBroadcastStats;
423 final Pair<String, ComponentName> mTarget;
424
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800425 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800426 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800427 int numWakeup;
428 long startTime;
429 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -0800430
431 FilterStats(BroadcastStats broadcastStats, Pair<String, ComponentName> target) {
432 mBroadcastStats = broadcastStats;
433 mTarget = target;
434 }
435 }
436
437 private static final class BroadcastStats {
438 final String mPackageName;
439
440 long aggregateTime;
441 int count;
442 int numWakeup;
443 long startTime;
444 int nesting;
445 final HashMap<Pair<String, ComponentName>, FilterStats> filterStats
446 = new HashMap<Pair<String, ComponentName>, FilterStats>();
447
448 BroadcastStats(String packageName) {
449 mPackageName = packageName;
450 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451 }
452
453 private final HashMap<String, BroadcastStats> mBroadcastStats
454 = new HashMap<String, BroadcastStats>();
455
456 public AlarmManagerService(Context context) {
457 mContext = context;
458 mDescriptor = init();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700459 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800460
461 // We have to set current TimeZone info to kernel
462 // because kernel doesn't keep this after reboot
463 String tz = SystemProperties.get(TIMEZONE_PROPERTY);
464 if (tz != null) {
465 setTimeZone(tz);
466 }
467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800468 PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
469 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
470
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700471 mTimeTickSender = PendingIntent.getBroadcastAsUser(context, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800472 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700473 Intent.FLAG_RECEIVER_REGISTERED_ONLY), 0,
474 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800475 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
476 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700477 mDateChangeSender = PendingIntent.getBroadcastAsUser(context, 0, intent,
478 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800479
480 // now that we have initied the driver schedule the alarm
481 mClockReceiver= new ClockReceiver();
482 mClockReceiver.scheduleTimeTickEvent();
483 mClockReceiver.scheduleDateChangedEvent();
484 mUninstallReceiver = new UninstallReceiver();
485
486 if (mDescriptor != -1) {
487 mWaitThread.start();
488 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800489 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800490 }
491 }
492
493 protected void finalize() throws Throwable {
494 try {
495 close(mDescriptor);
496 } finally {
497 super.finalize();
498 }
499 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700500
501 @Override
502 public void set(int type, long triggerAtTime, long interval,
503 PendingIntent operation, boolean isExact) {
504 set(type, triggerAtTime, interval, operation, isExact, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700506
507 public void set(int type, long triggerAtTime, long interval,
508 PendingIntent operation, boolean isExact, boolean isStandalone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800509 if (operation == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800510 Slog.w(TAG, "set/setRepeating ignored because there is no intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800511 return;
512 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700513
514 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
515 throw new IllegalArgumentException("Invalid alarm type " + type);
516 }
517
518 long nowElapsed = SystemClock.elapsedRealtime();
519 long triggerElapsed = convertToElapsed(triggerAtTime, type);
520 long maxElapsed = (isExact)
521 ? triggerElapsed
522 : maxTriggerTime(nowElapsed, triggerElapsed, interval);
523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700525 if (DEBUG_BATCH) {
526 Slog.v(TAG, "set(" + operation + ") : type=" + type
527 + " triggerAtTime=" + triggerAtTime
528 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
529 + " interval=" + interval + " standalone=" + isStandalone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700531 setImplLocked(type, triggerAtTime, triggerElapsed, maxElapsed,
532 interval, operation, isStandalone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533 }
534 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535
Christopher Tatee0a22b32013-07-11 14:43:13 -0700536 private void setImplLocked(int type, long when, long whenElapsed, long maxWhen, long interval,
537 PendingIntent operation, boolean isStandalone) {
538 Alarm a = new Alarm(type, when, whenElapsed, maxWhen, interval, operation);
539 removeLocked(operation);
Christopher Tateb8849c12011-02-08 13:39:01 -0800540
Christopher Tatee0a22b32013-07-11 14:43:13 -0700541 final boolean reschedule;
542 Batch batch = (isStandalone) ? null : attemptCoalesceLocked(whenElapsed, maxWhen);
543 if (batch == null) {
544 batch = new Batch(a);
545 batch.standalone = isStandalone;
546 if (DEBUG_BATCH) {
547 Slog.v(TAG, "Starting new alarm batch " + batch);
548 }
549 reschedule = addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800550 } else {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700551 reschedule = batch.add(a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 }
553
Christopher Tatee0a22b32013-07-11 14:43:13 -0700554 if (reschedule) {
555 rescheduleKernelAlarmsLocked();
556 }
557 }
558
559 private Batch findFirstWakeupBatchLocked() {
560 final int N = mAlarmBatches.size();
561 for (int i = 0; i < N; i++) {
562 Batch b = mAlarmBatches.get(i);
563 if (b.hasWakeups()) {
564 return b;
565 }
566 }
567 return null;
568 }
569
570 private void rescheduleKernelAlarmsLocked() {
571 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
572 // prior to that which contains no wakeups, we schedule that as well.
573 final Batch firstWakeup = findFirstWakeupBatchLocked();
574 final Batch firstBatch = mAlarmBatches.get(0);
575 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
576 mNextWakeup = firstWakeup.start;
577 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
578 }
579 if (firstBatch != firstWakeup && mNextNonWakeup != firstBatch.start) {
580 mNextNonWakeup = firstBatch.start;
581 setLocked(ELAPSED_REALTIME, firstBatch.start);
582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 }
584
Dan Egnor97e44942010-02-04 20:27:47 -0800585 public void setTime(long millis) {
586 mContext.enforceCallingOrSelfPermission(
587 "android.permission.SET_TIME",
588 "setTime");
589
590 SystemClock.setCurrentTimeMillis(millis);
591 }
592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800593 public void setTimeZone(String tz) {
594 mContext.enforceCallingOrSelfPermission(
595 "android.permission.SET_TIME_ZONE",
596 "setTimeZone");
597
Christopher Tate89779822012-08-31 14:40:03 -0700598 long oldId = Binder.clearCallingIdentity();
599 try {
600 if (TextUtils.isEmpty(tz)) return;
601 TimeZone zone = TimeZone.getTimeZone(tz);
602 // Prevent reentrant calls from stepping on each other when writing
603 // the time zone property
604 boolean timeZoneWasChanged = false;
605 synchronized (this) {
606 String current = SystemProperties.get(TIMEZONE_PROPERTY);
607 if (current == null || !current.equals(zone.getID())) {
608 if (localLOGV) {
609 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
610 }
611 timeZoneWasChanged = true;
612 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
613 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800614
Christopher Tate89779822012-08-31 14:40:03 -0700615 // Update the kernel timezone information
616 // Kernel tracks time offsets as 'minutes west of GMT'
617 int gmtOffset = zone.getOffset(System.currentTimeMillis());
618 setKernelTimezone(mDescriptor, -(gmtOffset / 60000));
619 }
620
621 TimeZone.setDefault(null);
622
623 if (timeZoneWasChanged) {
624 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
625 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
626 intent.putExtra("time-zone", zone.getID());
627 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
628 }
629 } finally {
630 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800631 }
632 }
633
634 public void remove(PendingIntent operation) {
635 if (operation == null) {
636 return;
637 }
638 synchronized (mLock) {
639 removeLocked(operation);
640 }
641 }
642
643 public void removeLocked(PendingIntent operation) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700644 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
645 Batch b = mAlarmBatches.get(i);
646 b.remove(operation);
647 if (b.size() == 0) {
648 mAlarmBatches.remove(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649 }
650 }
651 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 public void removeLocked(String packageName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700654 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
655 Batch b = mAlarmBatches.get(i);
656 b.remove(packageName);
657 if (b.size() == 0) {
658 mAlarmBatches.remove(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659 }
660 }
661 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700662
663 public void removeUserLocked(int userHandle) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700664 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
665 Batch b = mAlarmBatches.get(i);
666 b.remove(userHandle);
667 if (b.size() == 0) {
668 mAlarmBatches.remove(i);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700669 }
670 }
671 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -0800672
Christopher Tatee0a22b32013-07-11 14:43:13 -0700673 public boolean lookForPackageLocked(String packageName) {
674 for (int i = 0; i < mAlarmBatches.size(); i++) {
675 Batch b = mAlarmBatches.get(i);
676 if (b.hasPackage(packageName)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -0800677 return true;
678 }
679 }
680 return false;
681 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800682
Christopher Tatee0a22b32013-07-11 14:43:13 -0700683 private void setLocked(int type, long when)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 {
685 if (mDescriptor != -1)
686 {
Jeff Brown11c5f1a2010-03-31 15:29:40 -0700687 // The kernel never triggers alarms with negative wakeup times
688 // so we ensure they are positive.
689 long alarmSeconds, alarmNanoseconds;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700690 if (when < 0) {
Jeff Brown11c5f1a2010-03-31 15:29:40 -0700691 alarmSeconds = 0;
692 alarmNanoseconds = 0;
693 } else {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700694 alarmSeconds = when / 1000;
695 alarmNanoseconds = (when % 1000) * 1000 * 1000;
Jeff Brown11c5f1a2010-03-31 15:29:40 -0700696 }
697
Christopher Tatee0a22b32013-07-11 14:43:13 -0700698 set(mDescriptor, type, alarmSeconds, alarmNanoseconds);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 }
700 else
701 {
702 Message msg = Message.obtain();
703 msg.what = ALARM_EVENT;
704
705 mHandler.removeMessages(ALARM_EVENT);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700706 mHandler.sendMessageAtTime(msg, when);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 }
708 }
709
710 @Override
711 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
712 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
713 != PackageManager.PERMISSION_GRANTED) {
714 pw.println("Permission Denial: can't dump AlarmManager from from pid="
715 + Binder.getCallingPid()
716 + ", uid=" + Binder.getCallingUid());
717 return;
718 }
719
720 synchronized (mLock) {
721 pw.println("Current Alarm Manager state:");
Christopher Tatee0a22b32013-07-11 14:43:13 -0700722 final long nowRTC = System.currentTimeMillis();
723 final long nowELAPSED = SystemClock.elapsedRealtime();
724 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
725
726 pw.print("nowRTC="); pw.print(nowRTC);
727 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
728 pw.print(" nowELAPSED="); pw.println(nowELAPSED);
729
730 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
731 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
732 pw.print("Next alarm: "); pw.print(mNextNonWakeup);
733 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
734 pw.print("Next wakeup: "); pw.print(mNextWakeup);
735 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
736
737 if (mAlarmBatches.size() > 0) {
738 pw.println();
739 pw.print("Pending alarm batches: ");
740 pw.println(mAlarmBatches.size());
741 for (Batch b : mAlarmBatches) {
742 pw.print(b); pw.println(':');
743 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC);
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700744 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800746
747 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700748 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -0800749 pw.println();
750
751 if (mLog.dump(pw, " Recent problems", " ")) {
752 pw.println();
753 }
754
755 final FilterStats[] topFilters = new FilterStats[10];
756 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
757 @Override
758 public int compare(FilterStats lhs, FilterStats rhs) {
759 if (lhs.aggregateTime < rhs.aggregateTime) {
760 return 1;
761 } else if (lhs.aggregateTime > rhs.aggregateTime) {
762 return -1;
763 }
764 return 0;
765 }
766 };
767 int len = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768 for (Map.Entry<String, BroadcastStats> be : mBroadcastStats.entrySet()) {
769 BroadcastStats bs = be.getValue();
Dianne Hackborn81038902012-11-26 17:04:09 -0800770 for (Map.Entry<Pair<String, ComponentName>, FilterStats> fe
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 : bs.filterStats.entrySet()) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800772 FilterStats fs = fe.getValue();
773 int pos = len > 0
774 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
775 if (pos < 0) {
776 pos = -pos - 1;
777 }
778 if (pos < topFilters.length) {
779 int copylen = topFilters.length - pos - 1;
780 if (copylen > 0) {
781 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
782 }
783 topFilters[pos] = fs;
784 if (len < topFilters.length) {
785 len++;
786 }
787 }
788 }
789 }
790 if (len > 0) {
791 pw.println(" Top Alarms:");
792 for (int i=0; i<len; i++) {
793 FilterStats fs = topFilters[i];
794 pw.print(" ");
795 if (fs.nesting > 0) pw.print("*ACTIVE* ");
796 TimeUtils.formatDuration(fs.aggregateTime, pw);
797 pw.print(" running, "); pw.print(fs.numWakeup);
798 pw.print(" wakeups, "); pw.print(fs.count);
799 pw.print(" alarms: "); pw.print(fs.mBroadcastStats.mPackageName);
800 pw.println();
801 pw.print(" ");
802 if (fs.mTarget.first != null) {
803 pw.print(" act="); pw.print(fs.mTarget.first);
804 }
805 if (fs.mTarget.second != null) {
806 pw.print(" cmp="); pw.print(fs.mTarget.second.toShortString());
807 }
808 pw.println();
809 }
810 }
811
812 pw.println(" ");
813 pw.println(" Alarm Stats:");
814 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
815 for (Map.Entry<String, BroadcastStats> be : mBroadcastStats.entrySet()) {
816 BroadcastStats bs = be.getValue();
817 pw.print(" ");
818 if (bs.nesting > 0) pw.print("*ACTIVE* ");
819 pw.print(be.getKey());
820 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
821 pw.print(" running, "); pw.print(bs.numWakeup);
822 pw.println(" wakeups:");
823 tmpFilters.clear();
824 for (Map.Entry<Pair<String, ComponentName>, FilterStats> fe
825 : bs.filterStats.entrySet()) {
826 tmpFilters.add(fe.getValue());
827 }
828 Collections.sort(tmpFilters, comparator);
829 for (int i=0; i<tmpFilters.size(); i++) {
830 FilterStats fs = tmpFilters.get(i);
831 pw.print(" ");
832 if (fs.nesting > 0) pw.print("*ACTIVE* ");
833 TimeUtils.formatDuration(fs.aggregateTime, pw);
834 pw.print(" "); pw.print(fs.numWakeup);
835 pw.print(" wakes " ); pw.print(fs.count);
836 pw.print(" alarms:");
837 if (fs.mTarget.first != null) {
838 pw.print(" act="); pw.print(fs.mTarget.first);
839 }
840 if (fs.mTarget.second != null) {
841 pw.print(" cmp="); pw.print(fs.mTarget.second.toShortString());
842 }
843 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 }
845 }
Christopher Tate18a75f12013-07-01 18:18:59 -0700846
847 if (WAKEUP_STATS) {
848 pw.println();
849 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -0700850 long last = -1;
851 for (WakeupEvent event : mRecentWakeups) {
852 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
853 pw.print('|');
854 if (last < 0) {
855 pw.print('0');
856 } else {
857 pw.print(event.when - last);
858 }
859 last = event.when;
860 pw.print('|'); pw.print(event.uid);
861 pw.print('|'); pw.print(event.action);
862 pw.println();
863 }
864 pw.println();
865 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 }
867 }
868
Dianne Hackborn043fcd92010-10-06 14:27:34 -0700869 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
870 String prefix, String label, long now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 for (int i=list.size()-1; i>=0; i--) {
872 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700873 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
874 pw.print(": "); pw.println(a);
Dianne Hackborn043fcd92010-10-06 14:27:34 -0700875 a.dump(pw, prefix + " ", now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 }
877 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700878
879 private static final String labelForType(int type) {
880 switch (type) {
881 case RTC: return "RTC";
882 case RTC_WAKEUP : return "RTC_WAKEUP";
883 case ELAPSED_REALTIME : return "ELAPSED";
884 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
885 default:
886 break;
887 }
888 return "--unknown--";
889 }
890
891 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
892 String prefix, long nowELAPSED, long nowRTC) {
893 for (int i=list.size()-1; i>=0; i--) {
894 Alarm a = list.get(i);
895 final String label = labelForType(a.type);
896 long now = (a.type <= RTC) ? nowRTC : nowELAPSED;
897 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
898 pw.print(": "); pw.println(a);
899 a.dump(pw, prefix + " ", now);
900 }
901 }
902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 private native int init();
904 private native void close(int fd);
Jeff Brown11c5f1a2010-03-31 15:29:40 -0700905 private native void set(int fd, int type, long seconds, long nanoseconds);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 private native int waitForAlarm(int fd);
907 private native int setKernelTimezone(int fd, int minuteswest);
908
Christopher Tatee0a22b32013-07-11 14:43:13 -0700909 private void triggerAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED, long nowRTC) {
910 Batch batch;
Dianne Hackborn390517b2013-05-30 15:03:32 -0700911
Christopher Tatee0a22b32013-07-11 14:43:13 -0700912 // batches are temporally sorted, so we need only pull from the
913 // start of the list until we either empty it or hit a batch
914 // that is not yet deliverable
915 while ((batch = mAlarmBatches.get(0)) != null) {
916 if (batch.start > nowELAPSED) {
917 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 break;
919 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920
Christopher Tatee0a22b32013-07-11 14:43:13 -0700921 // We will (re)schedule some alarms now; don't let that interfere
922 // with delivery of this current batch
923 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -0700924
Christopher Tatee0a22b32013-07-11 14:43:13 -0700925 final int N = batch.size();
926 for (int i = 0; i < N; i++) {
927 Alarm alarm = batch.get(i);
928 alarm.count = 1;
929 triggerList.add(alarm);
930
931 // Recurring alarms may have passed several alarm intervals while the
932 // phone was asleep or off, so pass a trigger count when sending them.
933 if (alarm.repeatInterval > 0) {
934 // this adjustment will be zero if we're late by
935 // less than one full repeat interval
936 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
937
938 // Also schedule its next recurrence
939 final long delta = alarm.count * alarm.repeatInterval;
940 final long nextElapsed = alarm.whenElapsed + delta;
941 setImplLocked(alarm.type, alarm.when + delta, nextElapsed,
942 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
943 alarm.repeatInterval, alarm.operation, batch.standalone);
Dianne Hackborn390517b2013-05-30 15:03:32 -0700944 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945
Dianne Hackborn390517b2013-05-30 15:03:32 -0700946 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700949
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 /**
951 * This Comparator sorts Alarms into increasing time order.
952 */
953 public static class IncreasingTimeOrder implements Comparator<Alarm> {
954 public int compare(Alarm a1, Alarm a2) {
955 long when1 = a1.when;
956 long when2 = a2.when;
957 if (when1 - when2 > 0) {
958 return 1;
959 }
960 if (when1 - when2 < 0) {
961 return -1;
962 }
963 return 0;
964 }
965 }
966
967 private static class Alarm {
968 public int type;
969 public int count;
970 public long when;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700971 public long whenElapsed; // 'when' in the elapsed time base
972 public long maxWhen; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 public long repeatInterval;
974 public PendingIntent operation;
975
Christopher Tatee0a22b32013-07-11 14:43:13 -0700976 public Alarm(int _type, long _when, long _whenElapsed, long _maxWhen,
977 long _interval, PendingIntent _op) {
978 type = _type;
979 when = _when;
980 whenElapsed = _whenElapsed;
981 maxWhen = _maxWhen;
982 repeatInterval = _interval;
983 operation = _op;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700985
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 @Override
987 public String toString()
988 {
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700989 StringBuilder sb = new StringBuilder(128);
990 sb.append("Alarm{");
991 sb.append(Integer.toHexString(System.identityHashCode(this)));
992 sb.append(" type ");
993 sb.append(type);
994 sb.append(" ");
995 sb.append(operation.getTargetPackage());
996 sb.append('}');
997 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 }
999
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001000 public void dump(PrintWriter pw, String prefix, long now) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001001 pw.print(prefix); pw.print("type="); pw.print(type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001002 pw.print(" whenElapsed="); pw.print(whenElapsed);
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001003 pw.print(" when="); TimeUtils.formatDuration(when, now, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001004 pw.print(" repeatInterval="); pw.print(repeatInterval);
1005 pw.print(" count="); pw.println(count);
1006 pw.print(prefix); pw.print("operation="); pw.println(operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 }
1008 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001009
Christopher Tatee0a22b32013-07-11 14:43:13 -07001010 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
1011 final int numBatches = batches.size();
1012 for (int i = 0; i < numBatches; i++) {
1013 Batch b = batches.get(i);
1014 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07001015 break;
1016 }
1017
Christopher Tatee0a22b32013-07-11 14:43:13 -07001018 final int numAlarms = b.alarms.size();
1019 for (int j = 0; j < numAlarms; j++) {
1020 Alarm a = b.alarms.get(i);
1021 WakeupEvent e = new WakeupEvent(nowRTC,
1022 a.operation.getCreatorUid(),
1023 a.operation.getIntent().getAction());
1024 mRecentWakeups.add(e);
1025 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001026 }
1027 }
1028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 private class AlarmThread extends Thread
1030 {
1031 public AlarmThread()
1032 {
1033 super("AlarmManager");
1034 }
1035
1036 public void run()
1037 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07001038 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
1039
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 while (true)
1041 {
1042 int result = waitForAlarm(mDescriptor);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001043
1044 triggerList.clear();
1045
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 if ((result & TIME_CHANGED_MASK) != 0) {
1047 remove(mTimeTickSender);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001048 rebatchAllAlarms();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 mClockReceiver.scheduleTimeTickEvent();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001050 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
Dianne Hackborn89ba6752011-01-23 16:51:16 -08001051 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1052 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001053 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 }
1055
1056 synchronized (mLock) {
1057 final long nowRTC = System.currentTimeMillis();
1058 final long nowELAPSED = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001059 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 TAG, "Checking for alarms... rtc=" + nowRTC
1061 + ", elapsed=" + nowELAPSED);
1062
Christopher Tate18a75f12013-07-01 18:18:59 -07001063 if (WAKEUP_STATS) {
1064 if ((result & IS_WAKEUP_MASK) != 0) {
1065 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
1066 int n = 0;
1067 for (WakeupEvent event : mRecentWakeups) {
1068 if (event.when > newEarliest) break;
1069 n++; // number of now-stale entries at the list head
1070 }
1071 for (int i = 0; i < n; i++) {
1072 mRecentWakeups.remove();
1073 }
1074
Christopher Tatee0a22b32013-07-11 14:43:13 -07001075 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Christopher Tate18a75f12013-07-01 18:18:59 -07001076 }
1077 }
1078
Christopher Tatee0a22b32013-07-11 14:43:13 -07001079 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
1080 rescheduleKernelAlarmsLocked();
1081
1082 // now deliver the alarm intents
Dianne Hackborn390517b2013-05-30 15:03:32 -07001083 for (int i=0; i<triggerList.size(); i++) {
1084 Alarm alarm = triggerList.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001086 if (localLOGV) Slog.v(TAG, "sending alarm " + alarm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001087 alarm.operation.send(mContext, 0,
1088 mBackgroundIntent.putExtra(
1089 Intent.EXTRA_ALARM_COUNT, alarm.count),
1090 mResultReceiver, mHandler);
1091
Christopher Tatec4a07d12012-04-06 14:19:13 -07001092 // we have an active broadcast so stay awake.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 if (mBroadcastRefCount == 0) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07001094 setWakelockWorkSource(alarm.operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 mWakeLock.acquire();
1096 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001097 final InFlight inflight = new InFlight(AlarmManagerService.this,
1098 alarm.operation);
1099 mInFlight.add(inflight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 mBroadcastRefCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08001101
1102 final BroadcastStats bs = inflight.mBroadcastStats;
1103 bs.count++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 if (bs.nesting == 0) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001105 bs.nesting = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 bs.startTime = nowELAPSED;
1107 } else {
1108 bs.nesting++;
1109 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001110 final FilterStats fs = inflight.mFilterStats;
1111 fs.count++;
1112 if (fs.nesting == 0) {
1113 fs.nesting = 1;
1114 fs.startTime = nowELAPSED;
1115 } else {
1116 fs.nesting++;
1117 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001118 if (alarm.type == ELAPSED_REALTIME_WAKEUP
1119 || alarm.type == RTC_WAKEUP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 bs.numWakeup++;
Dianne Hackborn81038902012-11-26 17:04:09 -08001121 fs.numWakeup++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 ActivityManagerNative.noteWakeupAlarm(
1123 alarm.operation);
1124 }
1125 } catch (PendingIntent.CanceledException e) {
1126 if (alarm.repeatInterval > 0) {
1127 // This IntentSender is no longer valid, but this
1128 // is a repeating alarm, so toss the hoser.
1129 remove(alarm.operation);
1130 }
1131 } catch (RuntimeException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001132 Slog.w(TAG, "Failure sending alarm.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 }
1134 }
1135 }
1136 }
1137 }
1138 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07001139
1140 void setWakelockWorkSource(PendingIntent pi) {
1141 try {
1142 final int uid = ActivityManagerNative.getDefault()
1143 .getUidForIntentSender(pi.getTarget());
1144 if (uid >= 0) {
1145 mWakeLock.setWorkSource(new WorkSource(uid));
1146 return;
1147 }
1148 } catch (Exception e) {
1149 }
1150
1151 // Something went wrong; fall back to attributing the lock to the OS
1152 mWakeLock.setWorkSource(null);
1153 }
1154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155 private class AlarmHandler extends Handler {
1156 public static final int ALARM_EVENT = 1;
1157 public static final int MINUTE_CHANGE_EVENT = 2;
1158 public static final int DATE_CHANGE_EVENT = 3;
1159
1160 public AlarmHandler() {
1161 }
1162
1163 public void handleMessage(Message msg) {
1164 if (msg.what == ALARM_EVENT) {
1165 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
1166 synchronized (mLock) {
1167 final long nowRTC = System.currentTimeMillis();
Christopher Tatee0a22b32013-07-11 14:43:13 -07001168 final long nowELAPSED = SystemClock.elapsedRealtime();
1169 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001170 }
1171
1172 // now trigger the alarms without the lock held
Dianne Hackborn390517b2013-05-30 15:03:32 -07001173 for (int i=0; i<triggerList.size(); i++) {
1174 Alarm alarm = triggerList.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175 try {
1176 alarm.operation.send();
1177 } catch (PendingIntent.CanceledException e) {
1178 if (alarm.repeatInterval > 0) {
1179 // This IntentSender is no longer valid, but this
1180 // is a repeating alarm, so toss the hoser.
1181 remove(alarm.operation);
1182 }
1183 }
1184 }
1185 }
1186 }
1187 }
1188
1189 class ClockReceiver extends BroadcastReceiver {
1190 public ClockReceiver() {
1191 IntentFilter filter = new IntentFilter();
1192 filter.addAction(Intent.ACTION_TIME_TICK);
1193 filter.addAction(Intent.ACTION_DATE_CHANGED);
1194 mContext.registerReceiver(this, filter);
1195 }
1196
1197 @Override
1198 public void onReceive(Context context, Intent intent) {
1199 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
1200 scheduleTimeTickEvent();
1201 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
1202 // Since the kernel does not keep track of DST, we need to
1203 // reset the TZ information at the beginning of each day
1204 // based off of the current Zone gmt offset + userspace tracked
1205 // daylight savings information.
1206 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02001207 int gmtOffset = zone.getOffset(System.currentTimeMillis());
1208 setKernelTimezone(mDescriptor, -(gmtOffset / 60000));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 scheduleDateChangedEvent();
1210 }
1211 }
1212
1213 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07001214 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09001215 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07001216
1217 // Schedule this event for the amount of time that it would take to get to
1218 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09001219 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07001220
Christopher Tatee0a22b32013-07-11 14:43:13 -07001221 set(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay,
1222 0, mTimeTickSender, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223 }
1224
1225 public void scheduleDateChangedEvent() {
1226 Calendar calendar = Calendar.getInstance();
1227 calendar.setTimeInMillis(System.currentTimeMillis());
1228 calendar.set(Calendar.HOUR, 0);
1229 calendar.set(Calendar.MINUTE, 0);
1230 calendar.set(Calendar.SECOND, 0);
1231 calendar.set(Calendar.MILLISECOND, 0);
1232 calendar.add(Calendar.DAY_OF_MONTH, 1);
1233
Christopher Tatee0a22b32013-07-11 14:43:13 -07001234 set(RTC, calendar.getTimeInMillis(), 0, mDateChangeSender, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 }
1236 }
1237
1238 class UninstallReceiver extends BroadcastReceiver {
1239 public UninstallReceiver() {
1240 IntentFilter filter = new IntentFilter();
1241 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1242 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001243 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001244 filter.addDataScheme("package");
1245 mContext.registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001246 // Register for events related to sdcard installation.
1247 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001248 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001249 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001250 mContext.registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001251 }
1252
1253 @Override
1254 public void onReceive(Context context, Intent intent) {
1255 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001256 String action = intent.getAction();
1257 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001258 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
1259 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
1260 for (String packageName : pkgList) {
1261 if (lookForPackageLocked(packageName)) {
1262 setResultCode(Activity.RESULT_OK);
1263 return;
1264 }
1265 }
1266 return;
1267 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001268 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001269 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
1270 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
1271 if (userHandle >= 0) {
1272 removeUserLocked(userHandle);
1273 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001274 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08001275 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
1276 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
1277 // This package is being updated; don't kill its alarms.
1278 return;
1279 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001280 Uri data = intent.getData();
1281 if (data != null) {
1282 String pkg = data.getSchemeSpecificPart();
1283 if (pkg != null) {
1284 pkgList = new String[]{pkg};
1285 }
1286 }
1287 }
1288 if (pkgList != null && (pkgList.length > 0)) {
1289 for (String pkg : pkgList) {
1290 removeLocked(pkg);
1291 mBroadcastStats.remove(pkg);
1292 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293 }
1294 }
1295 }
1296 }
1297
1298 private final BroadcastStats getStatsLocked(PendingIntent pi) {
1299 String pkg = pi.getTargetPackage();
1300 BroadcastStats bs = mBroadcastStats.get(pkg);
1301 if (bs == null) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001302 bs = new BroadcastStats(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001303 mBroadcastStats.put(pkg, bs);
1304 }
1305 return bs;
1306 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 class ResultReceiver implements PendingIntent.OnFinished {
1309 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
1310 String resultData, Bundle resultExtras) {
1311 synchronized (mLock) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001312 InFlight inflight = null;
1313 for (int i=0; i<mInFlight.size(); i++) {
1314 if (mInFlight.get(i).mPendingIntent == pi) {
1315 inflight = mInFlight.remove(i);
1316 break;
1317 }
1318 }
1319 if (inflight != null) {
1320 final long nowELAPSED = SystemClock.elapsedRealtime();
1321 BroadcastStats bs = inflight.mBroadcastStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 bs.nesting--;
1323 if (bs.nesting <= 0) {
1324 bs.nesting = 0;
Dianne Hackborn81038902012-11-26 17:04:09 -08001325 bs.aggregateTime += nowELAPSED - bs.startTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001327 FilterStats fs = inflight.mFilterStats;
1328 fs.nesting--;
1329 if (fs.nesting <= 0) {
1330 fs.nesting = 0;
1331 fs.aggregateTime += nowELAPSED - fs.startTime;
1332 }
1333 } else {
1334 mLog.w("No in-flight alarm for " + pi + " " + intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 }
1336 mBroadcastRefCount--;
1337 if (mBroadcastRefCount == 0) {
1338 mWakeLock.release();
Dianne Hackborn81038902012-11-26 17:04:09 -08001339 if (mInFlight.size() > 0) {
1340 mLog.w("Finished all broadcasts with " + mInFlight.size()
1341 + " remaining inflights");
1342 for (int i=0; i<mInFlight.size(); i++) {
1343 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
1344 }
1345 mInFlight.clear();
1346 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07001347 } else {
1348 // the next of our alarms is now in flight. reattribute the wakelock.
Dianne Hackborn81038902012-11-26 17:04:09 -08001349 if (mInFlight.size() > 0) {
1350 setWakelockWorkSource(mInFlight.get(0).mPendingIntent);
Christopher Tatec4a07d12012-04-06 14:19:13 -07001351 } else {
1352 // should never happen
Dianne Hackborn81038902012-11-26 17:04:09 -08001353 mLog.w("Alarm wakelock still held but sent queue empty");
Christopher Tatec4a07d12012-04-06 14:19:13 -07001354 mWakeLock.setWorkSource(null);
1355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 }
1357 }
1358 }
1359 }
1360}