blob: d0b98aee4ec4d232483221ce895315dd79db5ddf [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
Christopher Tate385e4982013-07-23 18:22:29 -0700356 // Return the index of the matching batch, or -1 if none found.
357 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700358 final int N = mAlarmBatches.size();
359 for (int i = 0; i < N; i++) {
360 Batch b = mAlarmBatches.get(i);
361 if (!b.standalone && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700362 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700363 }
364 }
Christopher Tate385e4982013-07-23 18:22:29 -0700365 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700366 }
367
368 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
369 void rebatchAllAlarms() {
370 if (DEBUG_BATCH) {
371 Slog.v(TAG, "RTC changed; rebatching");
372 }
373 synchronized (mLock) {
374 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
375 mAlarmBatches.clear();
376 final long nowElapsed = SystemClock.elapsedRealtime();
377 for (Batch batch : oldSet) {
378 final int N = batch.size();
379 for (int i = 0; i < N; i++) {
380 Alarm a = batch.get(i);
381 long whenElapsed = convertToElapsed(a.when, a.type);
382 long maxElapsed = (a.whenElapsed == a.maxWhen)
383 ? whenElapsed
384 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
385 if (batch.standalone) {
386 // this will also be the only alarm in the batch
387 a = new Alarm(a.type, a.when, whenElapsed, maxElapsed,
388 a.repeatInterval, a.operation);
389 Batch newBatch = new Batch(a);
390 newBatch.standalone = true;
391 addBatchLocked(mAlarmBatches, newBatch);
392 } else {
393 setImplLocked(a.type, a.when, whenElapsed, maxElapsed,
394 a.repeatInterval, a.operation, false);
395 }
396 }
397 }
398 }
399 }
400
Dianne Hackborn81038902012-11-26 17:04:09 -0800401 private static final class InFlight extends Intent {
402 final PendingIntent mPendingIntent;
403 final Pair<String, ComponentName> mTarget;
404 final BroadcastStats mBroadcastStats;
405 final FilterStats mFilterStats;
406
407 InFlight(AlarmManagerService service, PendingIntent pendingIntent) {
408 mPendingIntent = pendingIntent;
409 Intent intent = pendingIntent.getIntent();
410 mTarget = intent != null
411 ? new Pair<String, ComponentName>(intent.getAction(), intent.getComponent())
412 : null;
413 mBroadcastStats = service.getStatsLocked(pendingIntent);
414 FilterStats fs = mBroadcastStats.filterStats.get(mTarget);
415 if (fs == null) {
416 fs = new FilterStats(mBroadcastStats, mTarget);
417 mBroadcastStats.filterStats.put(mTarget, fs);
418 }
419 mFilterStats = fs;
420 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800421 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800422
423 private static final class FilterStats {
424 final BroadcastStats mBroadcastStats;
425 final Pair<String, ComponentName> mTarget;
426
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800427 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800428 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800429 int numWakeup;
430 long startTime;
431 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -0800432
433 FilterStats(BroadcastStats broadcastStats, Pair<String, ComponentName> target) {
434 mBroadcastStats = broadcastStats;
435 mTarget = target;
436 }
437 }
438
439 private static final class BroadcastStats {
440 final String mPackageName;
441
442 long aggregateTime;
443 int count;
444 int numWakeup;
445 long startTime;
446 int nesting;
447 final HashMap<Pair<String, ComponentName>, FilterStats> filterStats
448 = new HashMap<Pair<String, ComponentName>, FilterStats>();
449
450 BroadcastStats(String packageName) {
451 mPackageName = packageName;
452 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800453 }
454
455 private final HashMap<String, BroadcastStats> mBroadcastStats
456 = new HashMap<String, BroadcastStats>();
457
458 public AlarmManagerService(Context context) {
459 mContext = context;
460 mDescriptor = init();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700461 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800462
463 // We have to set current TimeZone info to kernel
464 // because kernel doesn't keep this after reboot
465 String tz = SystemProperties.get(TIMEZONE_PROPERTY);
466 if (tz != null) {
467 setTimeZone(tz);
468 }
469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800470 PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
471 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
472
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700473 mTimeTickSender = PendingIntent.getBroadcastAsUser(context, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800474 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700475 Intent.FLAG_RECEIVER_REGISTERED_ONLY), 0,
476 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800477 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
478 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700479 mDateChangeSender = PendingIntent.getBroadcastAsUser(context, 0, intent,
480 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800481
482 // now that we have initied the driver schedule the alarm
483 mClockReceiver= new ClockReceiver();
484 mClockReceiver.scheduleTimeTickEvent();
485 mClockReceiver.scheduleDateChangedEvent();
486 mUninstallReceiver = new UninstallReceiver();
487
488 if (mDescriptor != -1) {
489 mWaitThread.start();
490 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800491 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492 }
493 }
494
495 protected void finalize() throws Throwable {
496 try {
497 close(mDescriptor);
498 } finally {
499 super.finalize();
500 }
501 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700502
503 @Override
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700504 public void set(int type, long triggerAtTime, long windowLength, long interval,
505 PendingIntent operation) {
506 set(type, triggerAtTime, windowLength, interval, operation, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800507 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700508
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700509 public void set(int type, long triggerAtTime, long windowLength, long interval,
510 PendingIntent operation, boolean isStandalone) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800511 if (operation == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800512 Slog.w(TAG, "set/setRepeating ignored because there is no intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513 return;
514 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700515
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700516 // Sanity check the window length. This will catch people mistakenly
517 // trying to pass an end-of-window timestamp rather than a duration.
518 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
519 Slog.w(TAG, "Window length " + windowLength
520 + "ms suspiciously long; limiting to 1 hour");
521 windowLength = AlarmManager.INTERVAL_HOUR;
522 }
523
Christopher Tatee0a22b32013-07-11 14:43:13 -0700524 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
525 throw new IllegalArgumentException("Invalid alarm type " + type);
526 }
527
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700528 final long nowElapsed = SystemClock.elapsedRealtime();
529 final long triggerElapsed = convertToElapsed(triggerAtTime, type);
530 final long maxElapsed;
531 if (windowLength == AlarmManager.WINDOW_EXACT) {
532 maxElapsed = triggerElapsed;
533 } else if (windowLength < 0) {
534 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
535 } else {
536 maxElapsed = triggerElapsed + windowLength;
537 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800539 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700540 if (DEBUG_BATCH) {
541 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700542 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -0700543 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
544 + " interval=" + interval + " standalone=" + isStandalone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800545 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700546 setImplLocked(type, triggerAtTime, triggerElapsed, maxElapsed,
547 interval, operation, isStandalone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800548 }
549 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800550
Christopher Tatee0a22b32013-07-11 14:43:13 -0700551 private void setImplLocked(int type, long when, long whenElapsed, long maxWhen, long interval,
552 PendingIntent operation, boolean isStandalone) {
553 Alarm a = new Alarm(type, when, whenElapsed, maxWhen, interval, operation);
554 removeLocked(operation);
Christopher Tateb8849c12011-02-08 13:39:01 -0800555
Christopher Tatee0a22b32013-07-11 14:43:13 -0700556 final boolean reschedule;
Christopher Tate385e4982013-07-23 18:22:29 -0700557 int whichBatch = (isStandalone) ? -1 : attemptCoalesceLocked(whenElapsed, maxWhen);
558 if (whichBatch < 0) {
559 Batch batch = new Batch(a);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700560 batch.standalone = isStandalone;
561 if (DEBUG_BATCH) {
562 Slog.v(TAG, "Starting new alarm batch " + batch);
563 }
564 reschedule = addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800565 } else {
Christopher Tate385e4982013-07-23 18:22:29 -0700566 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700567 reschedule = batch.add(a);
Christopher Tate385e4982013-07-23 18:22:29 -0700568 if (reschedule) {
569 // The start time of this batch advanced, so batch ordering may
570 // have just been broken. Move it to where it now belongs.
571 mAlarmBatches.remove(whichBatch);
572 addBatchLocked(mAlarmBatches, batch);
573 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800574 }
575
Christopher Tatee0a22b32013-07-11 14:43:13 -0700576 if (reschedule) {
577 rescheduleKernelAlarmsLocked();
578 }
579 }
580
581 private Batch findFirstWakeupBatchLocked() {
582 final int N = mAlarmBatches.size();
583 for (int i = 0; i < N; i++) {
584 Batch b = mAlarmBatches.get(i);
585 if (b.hasWakeups()) {
586 return b;
587 }
588 }
589 return null;
590 }
591
592 private void rescheduleKernelAlarmsLocked() {
593 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
594 // prior to that which contains no wakeups, we schedule that as well.
595 final Batch firstWakeup = findFirstWakeupBatchLocked();
596 final Batch firstBatch = mAlarmBatches.get(0);
597 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
598 mNextWakeup = firstWakeup.start;
599 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
600 }
601 if (firstBatch != firstWakeup && mNextNonWakeup != firstBatch.start) {
602 mNextNonWakeup = firstBatch.start;
603 setLocked(ELAPSED_REALTIME, firstBatch.start);
604 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605 }
606
Dan Egnor97e44942010-02-04 20:27:47 -0800607 public void setTime(long millis) {
608 mContext.enforceCallingOrSelfPermission(
609 "android.permission.SET_TIME",
610 "setTime");
611
612 SystemClock.setCurrentTimeMillis(millis);
613 }
614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800615 public void setTimeZone(String tz) {
616 mContext.enforceCallingOrSelfPermission(
617 "android.permission.SET_TIME_ZONE",
618 "setTimeZone");
619
Christopher Tate89779822012-08-31 14:40:03 -0700620 long oldId = Binder.clearCallingIdentity();
621 try {
622 if (TextUtils.isEmpty(tz)) return;
623 TimeZone zone = TimeZone.getTimeZone(tz);
624 // Prevent reentrant calls from stepping on each other when writing
625 // the time zone property
626 boolean timeZoneWasChanged = false;
627 synchronized (this) {
628 String current = SystemProperties.get(TIMEZONE_PROPERTY);
629 if (current == null || !current.equals(zone.getID())) {
630 if (localLOGV) {
631 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
632 }
633 timeZoneWasChanged = true;
634 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800636
Christopher Tate89779822012-08-31 14:40:03 -0700637 // Update the kernel timezone information
638 // Kernel tracks time offsets as 'minutes west of GMT'
639 int gmtOffset = zone.getOffset(System.currentTimeMillis());
640 setKernelTimezone(mDescriptor, -(gmtOffset / 60000));
641 }
642
643 TimeZone.setDefault(null);
644
645 if (timeZoneWasChanged) {
646 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
647 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
648 intent.putExtra("time-zone", zone.getID());
649 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
650 }
651 } finally {
652 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 }
654 }
655
656 public void remove(PendingIntent operation) {
657 if (operation == null) {
658 return;
659 }
660 synchronized (mLock) {
661 removeLocked(operation);
662 }
663 }
664
665 public void removeLocked(PendingIntent operation) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700666 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
667 Batch b = mAlarmBatches.get(i);
668 b.remove(operation);
669 if (b.size() == 0) {
670 mAlarmBatches.remove(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 }
672 }
673 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675 public void removeLocked(String packageName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700676 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
677 Batch b = mAlarmBatches.get(i);
678 b.remove(packageName);
679 if (b.size() == 0) {
680 mAlarmBatches.remove(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 }
682 }
683 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700684
685 public void removeUserLocked(int userHandle) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700686 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
687 Batch b = mAlarmBatches.get(i);
688 b.remove(userHandle);
689 if (b.size() == 0) {
690 mAlarmBatches.remove(i);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700691 }
692 }
693 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -0800694
Christopher Tatee0a22b32013-07-11 14:43:13 -0700695 public boolean lookForPackageLocked(String packageName) {
696 for (int i = 0; i < mAlarmBatches.size(); i++) {
697 Batch b = mAlarmBatches.get(i);
698 if (b.hasPackage(packageName)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -0800699 return true;
700 }
701 }
702 return false;
703 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704
Christopher Tatee0a22b32013-07-11 14:43:13 -0700705 private void setLocked(int type, long when)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 {
707 if (mDescriptor != -1)
708 {
Jeff Brown11c5f1a2010-03-31 15:29:40 -0700709 // The kernel never triggers alarms with negative wakeup times
710 // so we ensure they are positive.
711 long alarmSeconds, alarmNanoseconds;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700712 if (when < 0) {
Jeff Brown11c5f1a2010-03-31 15:29:40 -0700713 alarmSeconds = 0;
714 alarmNanoseconds = 0;
715 } else {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700716 alarmSeconds = when / 1000;
717 alarmNanoseconds = (when % 1000) * 1000 * 1000;
Jeff Brown11c5f1a2010-03-31 15:29:40 -0700718 }
719
Christopher Tatee0a22b32013-07-11 14:43:13 -0700720 set(mDescriptor, type, alarmSeconds, alarmNanoseconds);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 }
722 else
723 {
724 Message msg = Message.obtain();
725 msg.what = ALARM_EVENT;
726
727 mHandler.removeMessages(ALARM_EVENT);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700728 mHandler.sendMessageAtTime(msg, when);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 }
730 }
731
732 @Override
733 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
734 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
735 != PackageManager.PERMISSION_GRANTED) {
736 pw.println("Permission Denial: can't dump AlarmManager from from pid="
737 + Binder.getCallingPid()
738 + ", uid=" + Binder.getCallingUid());
739 return;
740 }
741
742 synchronized (mLock) {
743 pw.println("Current Alarm Manager state:");
Christopher Tatee0a22b32013-07-11 14:43:13 -0700744 final long nowRTC = System.currentTimeMillis();
745 final long nowELAPSED = SystemClock.elapsedRealtime();
746 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
747
748 pw.print("nowRTC="); pw.print(nowRTC);
749 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
750 pw.print(" nowELAPSED="); pw.println(nowELAPSED);
751
752 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
753 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
754 pw.print("Next alarm: "); pw.print(mNextNonWakeup);
755 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
756 pw.print("Next wakeup: "); pw.print(mNextWakeup);
757 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
758
759 if (mAlarmBatches.size() > 0) {
760 pw.println();
761 pw.print("Pending alarm batches: ");
762 pw.println(mAlarmBatches.size());
763 for (Batch b : mAlarmBatches) {
764 pw.print(b); pw.println(':');
765 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC);
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700766 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800768
769 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700770 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -0800771 pw.println();
772
773 if (mLog.dump(pw, " Recent problems", " ")) {
774 pw.println();
775 }
776
777 final FilterStats[] topFilters = new FilterStats[10];
778 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
779 @Override
780 public int compare(FilterStats lhs, FilterStats rhs) {
781 if (lhs.aggregateTime < rhs.aggregateTime) {
782 return 1;
783 } else if (lhs.aggregateTime > rhs.aggregateTime) {
784 return -1;
785 }
786 return 0;
787 }
788 };
789 int len = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790 for (Map.Entry<String, BroadcastStats> be : mBroadcastStats.entrySet()) {
791 BroadcastStats bs = be.getValue();
Dianne Hackborn81038902012-11-26 17:04:09 -0800792 for (Map.Entry<Pair<String, ComponentName>, FilterStats> fe
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 : bs.filterStats.entrySet()) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800794 FilterStats fs = fe.getValue();
795 int pos = len > 0
796 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
797 if (pos < 0) {
798 pos = -pos - 1;
799 }
800 if (pos < topFilters.length) {
801 int copylen = topFilters.length - pos - 1;
802 if (copylen > 0) {
803 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
804 }
805 topFilters[pos] = fs;
806 if (len < topFilters.length) {
807 len++;
808 }
809 }
810 }
811 }
812 if (len > 0) {
813 pw.println(" Top Alarms:");
814 for (int i=0; i<len; i++) {
815 FilterStats fs = topFilters[i];
816 pw.print(" ");
817 if (fs.nesting > 0) pw.print("*ACTIVE* ");
818 TimeUtils.formatDuration(fs.aggregateTime, pw);
819 pw.print(" running, "); pw.print(fs.numWakeup);
820 pw.print(" wakeups, "); pw.print(fs.count);
821 pw.print(" alarms: "); pw.print(fs.mBroadcastStats.mPackageName);
822 pw.println();
823 pw.print(" ");
824 if (fs.mTarget.first != null) {
825 pw.print(" act="); pw.print(fs.mTarget.first);
826 }
827 if (fs.mTarget.second != null) {
828 pw.print(" cmp="); pw.print(fs.mTarget.second.toShortString());
829 }
830 pw.println();
831 }
832 }
833
834 pw.println(" ");
835 pw.println(" Alarm Stats:");
836 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
837 for (Map.Entry<String, BroadcastStats> be : mBroadcastStats.entrySet()) {
838 BroadcastStats bs = be.getValue();
839 pw.print(" ");
840 if (bs.nesting > 0) pw.print("*ACTIVE* ");
841 pw.print(be.getKey());
842 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
843 pw.print(" running, "); pw.print(bs.numWakeup);
844 pw.println(" wakeups:");
845 tmpFilters.clear();
846 for (Map.Entry<Pair<String, ComponentName>, FilterStats> fe
847 : bs.filterStats.entrySet()) {
848 tmpFilters.add(fe.getValue());
849 }
850 Collections.sort(tmpFilters, comparator);
851 for (int i=0; i<tmpFilters.size(); i++) {
852 FilterStats fs = tmpFilters.get(i);
853 pw.print(" ");
854 if (fs.nesting > 0) pw.print("*ACTIVE* ");
855 TimeUtils.formatDuration(fs.aggregateTime, pw);
856 pw.print(" "); pw.print(fs.numWakeup);
857 pw.print(" wakes " ); pw.print(fs.count);
858 pw.print(" alarms:");
859 if (fs.mTarget.first != null) {
860 pw.print(" act="); pw.print(fs.mTarget.first);
861 }
862 if (fs.mTarget.second != null) {
863 pw.print(" cmp="); pw.print(fs.mTarget.second.toShortString());
864 }
865 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 }
867 }
Christopher Tate18a75f12013-07-01 18:18:59 -0700868
869 if (WAKEUP_STATS) {
870 pw.println();
871 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -0700872 long last = -1;
873 for (WakeupEvent event : mRecentWakeups) {
874 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
875 pw.print('|');
876 if (last < 0) {
877 pw.print('0');
878 } else {
879 pw.print(event.when - last);
880 }
881 last = event.when;
882 pw.print('|'); pw.print(event.uid);
883 pw.print('|'); pw.print(event.action);
884 pw.println();
885 }
886 pw.println();
887 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 }
889 }
890
Dianne Hackborn043fcd92010-10-06 14:27:34 -0700891 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
892 String prefix, String label, long now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 for (int i=list.size()-1; i>=0; i--) {
894 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700895 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
896 pw.print(": "); pw.println(a);
Dianne Hackborn043fcd92010-10-06 14:27:34 -0700897 a.dump(pw, prefix + " ", now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898 }
899 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700900
901 private static final String labelForType(int type) {
902 switch (type) {
903 case RTC: return "RTC";
904 case RTC_WAKEUP : return "RTC_WAKEUP";
905 case ELAPSED_REALTIME : return "ELAPSED";
906 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
907 default:
908 break;
909 }
910 return "--unknown--";
911 }
912
913 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
914 String prefix, long nowELAPSED, long nowRTC) {
915 for (int i=list.size()-1; i>=0; i--) {
916 Alarm a = list.get(i);
917 final String label = labelForType(a.type);
918 long now = (a.type <= RTC) ? nowRTC : nowELAPSED;
919 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
920 pw.print(": "); pw.println(a);
921 a.dump(pw, prefix + " ", now);
922 }
923 }
924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 private native int init();
926 private native void close(int fd);
Jeff Brown11c5f1a2010-03-31 15:29:40 -0700927 private native void set(int fd, int type, long seconds, long nanoseconds);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 private native int waitForAlarm(int fd);
929 private native int setKernelTimezone(int fd, int minuteswest);
930
Christopher Tatee0a22b32013-07-11 14:43:13 -0700931 private void triggerAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED, long nowRTC) {
932 Batch batch;
Dianne Hackborn390517b2013-05-30 15:03:32 -0700933
Christopher Tatee0a22b32013-07-11 14:43:13 -0700934 // batches are temporally sorted, so we need only pull from the
935 // start of the list until we either empty it or hit a batch
936 // that is not yet deliverable
937 while ((batch = mAlarmBatches.get(0)) != null) {
938 if (batch.start > nowELAPSED) {
939 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 break;
941 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942
Christopher Tatee0a22b32013-07-11 14:43:13 -0700943 // We will (re)schedule some alarms now; don't let that interfere
944 // with delivery of this current batch
945 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -0700946
Christopher Tatee0a22b32013-07-11 14:43:13 -0700947 final int N = batch.size();
948 for (int i = 0; i < N; i++) {
949 Alarm alarm = batch.get(i);
950 alarm.count = 1;
951 triggerList.add(alarm);
952
953 // Recurring alarms may have passed several alarm intervals while the
954 // phone was asleep or off, so pass a trigger count when sending them.
955 if (alarm.repeatInterval > 0) {
956 // this adjustment will be zero if we're late by
957 // less than one full repeat interval
958 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
959
960 // Also schedule its next recurrence
961 final long delta = alarm.count * alarm.repeatInterval;
962 final long nextElapsed = alarm.whenElapsed + delta;
963 setImplLocked(alarm.type, alarm.when + delta, nextElapsed,
964 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
965 alarm.repeatInterval, alarm.operation, batch.standalone);
Dianne Hackborn390517b2013-05-30 15:03:32 -0700966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967
Dianne Hackborn390517b2013-05-30 15:03:32 -0700968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700971
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 /**
973 * This Comparator sorts Alarms into increasing time order.
974 */
975 public static class IncreasingTimeOrder implements Comparator<Alarm> {
976 public int compare(Alarm a1, Alarm a2) {
977 long when1 = a1.when;
978 long when2 = a2.when;
979 if (when1 - when2 > 0) {
980 return 1;
981 }
982 if (when1 - when2 < 0) {
983 return -1;
984 }
985 return 0;
986 }
987 }
988
989 private static class Alarm {
990 public int type;
991 public int count;
992 public long when;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700993 public long whenElapsed; // 'when' in the elapsed time base
994 public long maxWhen; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995 public long repeatInterval;
996 public PendingIntent operation;
997
Christopher Tatee0a22b32013-07-11 14:43:13 -0700998 public Alarm(int _type, long _when, long _whenElapsed, long _maxWhen,
999 long _interval, PendingIntent _op) {
1000 type = _type;
1001 when = _when;
1002 whenElapsed = _whenElapsed;
1003 maxWhen = _maxWhen;
1004 repeatInterval = _interval;
1005 operation = _op;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 @Override
1009 public String toString()
1010 {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001011 StringBuilder sb = new StringBuilder(128);
1012 sb.append("Alarm{");
1013 sb.append(Integer.toHexString(System.identityHashCode(this)));
1014 sb.append(" type ");
1015 sb.append(type);
1016 sb.append(" ");
1017 sb.append(operation.getTargetPackage());
1018 sb.append('}');
1019 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 }
1021
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001022 public void dump(PrintWriter pw, String prefix, long now) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001023 pw.print(prefix); pw.print("type="); pw.print(type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001024 pw.print(" whenElapsed="); pw.print(whenElapsed);
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001025 pw.print(" when="); TimeUtils.formatDuration(when, now, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001026 pw.print(" repeatInterval="); pw.print(repeatInterval);
1027 pw.print(" count="); pw.println(count);
1028 pw.print(prefix); pw.print("operation="); pw.println(operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 }
1030 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001031
Christopher Tatee0a22b32013-07-11 14:43:13 -07001032 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
1033 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07001034 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
1035 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001036 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07001037 break;
1038 }
1039
Christopher Tatee0a22b32013-07-11 14:43:13 -07001040 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07001041 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
1042 Alarm a = b.alarms.get(nextAlarm);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001043 WakeupEvent e = new WakeupEvent(nowRTC,
1044 a.operation.getCreatorUid(),
1045 a.operation.getIntent().getAction());
1046 mRecentWakeups.add(e);
1047 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001048 }
1049 }
1050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 private class AlarmThread extends Thread
1052 {
1053 public AlarmThread()
1054 {
1055 super("AlarmManager");
1056 }
1057
1058 public void run()
1059 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07001060 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
1061
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 while (true)
1063 {
1064 int result = waitForAlarm(mDescriptor);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001065
1066 triggerList.clear();
1067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 if ((result & TIME_CHANGED_MASK) != 0) {
Christopher Tate385e4982013-07-23 18:22:29 -07001069 if (DEBUG_BATCH) {
1070 Slog.v(TAG, "Time changed notification from kernel");
1071 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072 remove(mTimeTickSender);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001073 rebatchAllAlarms();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 mClockReceiver.scheduleTimeTickEvent();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001075 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
Dianne Hackborn89ba6752011-01-23 16:51:16 -08001076 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1077 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001078 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 }
1080
1081 synchronized (mLock) {
1082 final long nowRTC = System.currentTimeMillis();
1083 final long nowELAPSED = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001084 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 TAG, "Checking for alarms... rtc=" + nowRTC
1086 + ", elapsed=" + nowELAPSED);
1087
Christopher Tate18a75f12013-07-01 18:18:59 -07001088 if (WAKEUP_STATS) {
1089 if ((result & IS_WAKEUP_MASK) != 0) {
1090 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
1091 int n = 0;
1092 for (WakeupEvent event : mRecentWakeups) {
1093 if (event.when > newEarliest) break;
1094 n++; // number of now-stale entries at the list head
1095 }
1096 for (int i = 0; i < n; i++) {
1097 mRecentWakeups.remove();
1098 }
1099
Christopher Tatee0a22b32013-07-11 14:43:13 -07001100 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Christopher Tate18a75f12013-07-01 18:18:59 -07001101 }
1102 }
1103
Christopher Tatee0a22b32013-07-11 14:43:13 -07001104 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
1105 rescheduleKernelAlarmsLocked();
1106
1107 // now deliver the alarm intents
Dianne Hackborn390517b2013-05-30 15:03:32 -07001108 for (int i=0; i<triggerList.size(); i++) {
1109 Alarm alarm = triggerList.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001111 if (localLOGV) Slog.v(TAG, "sending alarm " + alarm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 alarm.operation.send(mContext, 0,
1113 mBackgroundIntent.putExtra(
1114 Intent.EXTRA_ALARM_COUNT, alarm.count),
1115 mResultReceiver, mHandler);
1116
Christopher Tatec4a07d12012-04-06 14:19:13 -07001117 // we have an active broadcast so stay awake.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 if (mBroadcastRefCount == 0) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07001119 setWakelockWorkSource(alarm.operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 mWakeLock.acquire();
1121 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001122 final InFlight inflight = new InFlight(AlarmManagerService.this,
1123 alarm.operation);
1124 mInFlight.add(inflight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125 mBroadcastRefCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08001126
1127 final BroadcastStats bs = inflight.mBroadcastStats;
1128 bs.count++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001129 if (bs.nesting == 0) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001130 bs.nesting = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 bs.startTime = nowELAPSED;
1132 } else {
1133 bs.nesting++;
1134 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001135 final FilterStats fs = inflight.mFilterStats;
1136 fs.count++;
1137 if (fs.nesting == 0) {
1138 fs.nesting = 1;
1139 fs.startTime = nowELAPSED;
1140 } else {
1141 fs.nesting++;
1142 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001143 if (alarm.type == ELAPSED_REALTIME_WAKEUP
1144 || alarm.type == RTC_WAKEUP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001145 bs.numWakeup++;
Dianne Hackborn81038902012-11-26 17:04:09 -08001146 fs.numWakeup++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 ActivityManagerNative.noteWakeupAlarm(
1148 alarm.operation);
1149 }
1150 } catch (PendingIntent.CanceledException e) {
1151 if (alarm.repeatInterval > 0) {
1152 // This IntentSender is no longer valid, but this
1153 // is a repeating alarm, so toss the hoser.
1154 remove(alarm.operation);
1155 }
1156 } catch (RuntimeException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001157 Slog.w(TAG, "Failure sending alarm.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158 }
1159 }
1160 }
1161 }
1162 }
1163 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07001164
1165 void setWakelockWorkSource(PendingIntent pi) {
1166 try {
1167 final int uid = ActivityManagerNative.getDefault()
1168 .getUidForIntentSender(pi.getTarget());
1169 if (uid >= 0) {
1170 mWakeLock.setWorkSource(new WorkSource(uid));
1171 return;
1172 }
1173 } catch (Exception e) {
1174 }
1175
1176 // Something went wrong; fall back to attributing the lock to the OS
1177 mWakeLock.setWorkSource(null);
1178 }
1179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001180 private class AlarmHandler extends Handler {
1181 public static final int ALARM_EVENT = 1;
1182 public static final int MINUTE_CHANGE_EVENT = 2;
1183 public static final int DATE_CHANGE_EVENT = 3;
1184
1185 public AlarmHandler() {
1186 }
1187
1188 public void handleMessage(Message msg) {
1189 if (msg.what == ALARM_EVENT) {
1190 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
1191 synchronized (mLock) {
1192 final long nowRTC = System.currentTimeMillis();
Christopher Tatee0a22b32013-07-11 14:43:13 -07001193 final long nowELAPSED = SystemClock.elapsedRealtime();
1194 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 }
1196
1197 // now trigger the alarms without the lock held
Dianne Hackborn390517b2013-05-30 15:03:32 -07001198 for (int i=0; i<triggerList.size(); i++) {
1199 Alarm alarm = triggerList.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 try {
1201 alarm.operation.send();
1202 } catch (PendingIntent.CanceledException e) {
1203 if (alarm.repeatInterval > 0) {
1204 // This IntentSender is no longer valid, but this
1205 // is a repeating alarm, so toss the hoser.
1206 remove(alarm.operation);
1207 }
1208 }
1209 }
1210 }
1211 }
1212 }
1213
1214 class ClockReceiver extends BroadcastReceiver {
1215 public ClockReceiver() {
1216 IntentFilter filter = new IntentFilter();
1217 filter.addAction(Intent.ACTION_TIME_TICK);
1218 filter.addAction(Intent.ACTION_DATE_CHANGED);
1219 mContext.registerReceiver(this, filter);
1220 }
1221
1222 @Override
1223 public void onReceive(Context context, Intent intent) {
1224 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001225 if (DEBUG_BATCH) {
1226 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
1227 }
1228 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
1230 // Since the kernel does not keep track of DST, we need to
1231 // reset the TZ information at the beginning of each day
1232 // based off of the current Zone gmt offset + userspace tracked
1233 // daylight savings information.
1234 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02001235 int gmtOffset = zone.getOffset(System.currentTimeMillis());
1236 setKernelTimezone(mDescriptor, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07001237 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001238 }
1239 }
1240
1241 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07001242 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09001243 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07001244
1245 // Schedule this event for the amount of time that it would take to get to
1246 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09001247 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07001248
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001249 set(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
1250 0, mTimeTickSender, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001251 }
Christopher Tate385e4982013-07-23 18:22:29 -07001252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 public void scheduleDateChangedEvent() {
1254 Calendar calendar = Calendar.getInstance();
1255 calendar.setTimeInMillis(System.currentTimeMillis());
1256 calendar.set(Calendar.HOUR, 0);
1257 calendar.set(Calendar.MINUTE, 0);
1258 calendar.set(Calendar.SECOND, 0);
1259 calendar.set(Calendar.MILLISECOND, 0);
1260 calendar.add(Calendar.DAY_OF_MONTH, 1);
1261
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001262 set(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263 }
1264 }
1265
1266 class UninstallReceiver extends BroadcastReceiver {
1267 public UninstallReceiver() {
1268 IntentFilter filter = new IntentFilter();
1269 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1270 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001271 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001272 filter.addDataScheme("package");
1273 mContext.registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001274 // Register for events related to sdcard installation.
1275 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001276 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001277 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001278 mContext.registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 }
1280
1281 @Override
1282 public void onReceive(Context context, Intent intent) {
1283 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001284 String action = intent.getAction();
1285 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001286 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
1287 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
1288 for (String packageName : pkgList) {
1289 if (lookForPackageLocked(packageName)) {
1290 setResultCode(Activity.RESULT_OK);
1291 return;
1292 }
1293 }
1294 return;
1295 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001296 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001297 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
1298 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
1299 if (userHandle >= 0) {
1300 removeUserLocked(userHandle);
1301 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001302 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08001303 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
1304 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
1305 // This package is being updated; don't kill its alarms.
1306 return;
1307 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001308 Uri data = intent.getData();
1309 if (data != null) {
1310 String pkg = data.getSchemeSpecificPart();
1311 if (pkg != null) {
1312 pkgList = new String[]{pkg};
1313 }
1314 }
1315 }
1316 if (pkgList != null && (pkgList.length > 0)) {
1317 for (String pkg : pkgList) {
1318 removeLocked(pkg);
1319 mBroadcastStats.remove(pkg);
1320 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 }
1322 }
1323 }
1324 }
1325
1326 private final BroadcastStats getStatsLocked(PendingIntent pi) {
1327 String pkg = pi.getTargetPackage();
1328 BroadcastStats bs = mBroadcastStats.get(pkg);
1329 if (bs == null) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001330 bs = new BroadcastStats(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 mBroadcastStats.put(pkg, bs);
1332 }
1333 return bs;
1334 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001336 class ResultReceiver implements PendingIntent.OnFinished {
1337 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
1338 String resultData, Bundle resultExtras) {
1339 synchronized (mLock) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001340 InFlight inflight = null;
1341 for (int i=0; i<mInFlight.size(); i++) {
1342 if (mInFlight.get(i).mPendingIntent == pi) {
1343 inflight = mInFlight.remove(i);
1344 break;
1345 }
1346 }
1347 if (inflight != null) {
1348 final long nowELAPSED = SystemClock.elapsedRealtime();
1349 BroadcastStats bs = inflight.mBroadcastStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350 bs.nesting--;
1351 if (bs.nesting <= 0) {
1352 bs.nesting = 0;
Dianne Hackborn81038902012-11-26 17:04:09 -08001353 bs.aggregateTime += nowELAPSED - bs.startTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001355 FilterStats fs = inflight.mFilterStats;
1356 fs.nesting--;
1357 if (fs.nesting <= 0) {
1358 fs.nesting = 0;
1359 fs.aggregateTime += nowELAPSED - fs.startTime;
1360 }
1361 } else {
1362 mLog.w("No in-flight alarm for " + pi + " " + intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363 }
1364 mBroadcastRefCount--;
1365 if (mBroadcastRefCount == 0) {
1366 mWakeLock.release();
Dianne Hackborn81038902012-11-26 17:04:09 -08001367 if (mInFlight.size() > 0) {
1368 mLog.w("Finished all broadcasts with " + mInFlight.size()
1369 + " remaining inflights");
1370 for (int i=0; i<mInFlight.size(); i++) {
1371 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
1372 }
1373 mInFlight.clear();
1374 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07001375 } else {
1376 // the next of our alarms is now in flight. reattribute the wakelock.
Dianne Hackborn81038902012-11-26 17:04:09 -08001377 if (mInFlight.size() > 0) {
1378 setWakelockWorkSource(mInFlight.get(0).mPendingIntent);
Christopher Tatec4a07d12012-04-06 14:19:13 -07001379 } else {
1380 // should never happen
Dianne Hackborn81038902012-11-26 17:04:09 -08001381 mLog.w("Alarm wakelock still held but sent queue empty");
Christopher Tatec4a07d12012-04-06 14:19:13 -07001382 mWakeLock.setWorkSource(null);
1383 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 }
1385 }
1386 }
1387 }
1388}