blob: cf3ecdcfc38cb2f07587e6925f68103a6b09a7cb [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;
21import android.app.AlarmManager;
22import android.app.IAlarmManager;
23import android.app.PendingIntent;
24import android.content.BroadcastReceiver;
25import 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;
37import android.text.TextUtils;
38import android.text.format.Time;
39import android.util.EventLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080040import android.util.Slog;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070041import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042
43import java.io.FileDescriptor;
44import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070045import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import java.util.ArrayList;
47import java.util.Calendar;
48import java.util.Collections;
49import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -050050import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import java.util.HashMap;
52import java.util.Iterator;
53import java.util.Map;
54import java.util.TimeZone;
55
56class AlarmManagerService extends IAlarmManager.Stub {
57 // The threshold for how long an alarm can be late before we print a
58 // warning message. The time duration is in milliseconds.
59 private static final long LATE_ALARM_THRESHOLD = 10 * 1000;
60
61 private static final int RTC_WAKEUP_MASK = 1 << AlarmManager.RTC_WAKEUP;
62 private static final int RTC_MASK = 1 << AlarmManager.RTC;
63 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << AlarmManager.ELAPSED_REALTIME_WAKEUP;
64 private static final int ELAPSED_REALTIME_MASK = 1 << AlarmManager.ELAPSED_REALTIME;
65 private static final int TIME_CHANGED_MASK = 1 << 16;
66
67 private static final String TAG = "AlarmManager";
68 private static final String ClockReceiver_TAG = "ClockReceiver";
69 private static final boolean localLOGV = false;
70 private static final int ALARM_EVENT = 1;
71 private static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
72
73 private static final Intent mBackgroundIntent
74 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
75
76 private final Context mContext;
77
78 private Object mLock = new Object();
79
80 private final ArrayList<Alarm> mRtcWakeupAlarms = new ArrayList<Alarm>();
81 private final ArrayList<Alarm> mRtcAlarms = new ArrayList<Alarm>();
82 private final ArrayList<Alarm> mElapsedRealtimeWakeupAlarms = new ArrayList<Alarm>();
83 private final ArrayList<Alarm> mElapsedRealtimeAlarms = new ArrayList<Alarm>();
84 private final IncreasingTimeOrder mIncreasingTimeOrder = new IncreasingTimeOrder();
85
86 // slots corresponding with the inexact-repeat interval buckets,
87 // ordered from shortest to longest
88 private static final long sInexactSlotIntervals[] = {
89 AlarmManager.INTERVAL_FIFTEEN_MINUTES,
90 AlarmManager.INTERVAL_HALF_HOUR,
91 AlarmManager.INTERVAL_HOUR,
92 AlarmManager.INTERVAL_HALF_DAY,
93 AlarmManager.INTERVAL_DAY
94 };
95 private long mInexactDeliveryTimes[] = { 0, 0, 0, 0, 0};
96
97 private int mDescriptor;
98 private int mBroadcastRefCount = 0;
99 private PowerManager.WakeLock mWakeLock;
100 private final AlarmThread mWaitThread = new AlarmThread();
101 private final AlarmHandler mHandler = new AlarmHandler();
102 private ClockReceiver mClockReceiver;
103 private UninstallReceiver mUninstallReceiver;
104 private final ResultReceiver mResultReceiver = new ResultReceiver();
105 private final PendingIntent mTimeTickSender;
106 private final PendingIntent mDateChangeSender;
107
108 private static final class FilterStats {
109 int count;
110 }
111
112 private static final class BroadcastStats {
113 long aggregateTime;
114 int numWakeup;
115 long startTime;
116 int nesting;
117 HashMap<Intent.FilterComparison, FilterStats> filterStats
118 = new HashMap<Intent.FilterComparison, FilterStats>();
119 }
120
121 private final HashMap<String, BroadcastStats> mBroadcastStats
122 = new HashMap<String, BroadcastStats>();
123
124 public AlarmManagerService(Context context) {
125 mContext = context;
126 mDescriptor = init();
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800127
128 // We have to set current TimeZone info to kernel
129 // because kernel doesn't keep this after reboot
130 String tz = SystemProperties.get(TIMEZONE_PROPERTY);
131 if (tz != null) {
132 setTimeZone(tz);
133 }
134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135 PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
136 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
137
138 mTimeTickSender = PendingIntent.getBroadcast(context, 0,
139 new Intent(Intent.ACTION_TIME_TICK).addFlags(
140 Intent.FLAG_RECEIVER_REGISTERED_ONLY), 0);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800141 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
142 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
143 mDateChangeSender = PendingIntent.getBroadcast(context, 0, intent, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144
145 // now that we have initied the driver schedule the alarm
146 mClockReceiver= new ClockReceiver();
147 mClockReceiver.scheduleTimeTickEvent();
148 mClockReceiver.scheduleDateChangedEvent();
149 mUninstallReceiver = new UninstallReceiver();
150
151 if (mDescriptor != -1) {
152 mWaitThread.start();
153 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800154 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155 }
156 }
157
158 protected void finalize() throws Throwable {
159 try {
160 close(mDescriptor);
161 } finally {
162 super.finalize();
163 }
164 }
165
166 public void set(int type, long triggerAtTime, PendingIntent operation) {
167 setRepeating(type, triggerAtTime, 0, operation);
168 }
169
170 public void setRepeating(int type, long triggerAtTime, long interval,
171 PendingIntent operation) {
172 if (operation == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800173 Slog.w(TAG, "set/setRepeating ignored because there is no intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 return;
175 }
176 synchronized (mLock) {
177 Alarm alarm = new Alarm();
178 alarm.type = type;
179 alarm.when = triggerAtTime;
180 alarm.repeatInterval = interval;
181 alarm.operation = operation;
182
183 // Remove this alarm if already scheduled.
184 removeLocked(operation);
185
Joe Onorato8a9b2202010-02-26 18:56:32 -0800186 if (localLOGV) Slog.v(TAG, "set: " + alarm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187
188 int index = addAlarmLocked(alarm);
189 if (index == 0) {
190 setLocked(alarm);
191 }
192 }
193 }
194
195 public void setInexactRepeating(int type, long triggerAtTime, long interval,
196 PendingIntent operation) {
197 if (operation == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800198 Slog.w(TAG, "setInexactRepeating ignored because there is no intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 return;
200 }
201
202 // find the slot in the delivery-times array that we will use
203 int intervalSlot;
204 for (intervalSlot = 0; intervalSlot < sInexactSlotIntervals.length; intervalSlot++) {
205 if (sInexactSlotIntervals[intervalSlot] == interval) {
206 break;
207 }
208 }
209
210 // Non-bucket intervals just fall back to the less-efficient
211 // unbucketed recurring alarm implementation
212 if (intervalSlot >= sInexactSlotIntervals.length) {
213 setRepeating(type, triggerAtTime, interval, operation);
214 return;
215 }
216
217 // Align bucketed alarm deliveries by trying to match
218 // the shortest-interval bucket already scheduled
219 long bucketTime = 0;
220 for (int slot = 0; slot < mInexactDeliveryTimes.length; slot++) {
221 if (mInexactDeliveryTimes[slot] > 0) {
222 bucketTime = mInexactDeliveryTimes[slot];
223 break;
224 }
225 }
226
227 if (bucketTime == 0) {
228 // If nothing is scheduled yet, just start at the requested time
229 bucketTime = triggerAtTime;
230 } else {
231 // Align the new alarm with the existing bucketed sequence. To achieve
232 // alignment, we slide the start time around by min{interval, slot interval}
233 long adjustment = (interval <= sInexactSlotIntervals[intervalSlot])
234 ? interval : sInexactSlotIntervals[intervalSlot];
235
236 // The bucket may have started in the past; adjust
237 while (bucketTime < triggerAtTime) {
238 bucketTime += adjustment;
239 }
240
241 // Or the bucket may be set to start more than an interval beyond
242 // our requested trigger time; pull it back to meet our needs
243 while (bucketTime > triggerAtTime + adjustment) {
244 bucketTime -= adjustment;
245 }
246 }
247
248 // Remember where this bucket started (reducing the amount of later
249 // fixup required) and set the alarm with the new, bucketed start time.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800250 if (localLOGV) Slog.v(TAG, "setInexactRepeating: interval=" + interval
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 + " bucketTime=" + bucketTime);
252 mInexactDeliveryTimes[intervalSlot] = bucketTime;
253 setRepeating(type, bucketTime, interval, operation);
254 }
255
Dan Egnor97e44942010-02-04 20:27:47 -0800256 public void setTime(long millis) {
257 mContext.enforceCallingOrSelfPermission(
258 "android.permission.SET_TIME",
259 "setTime");
260
261 SystemClock.setCurrentTimeMillis(millis);
262 }
263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264 public void setTimeZone(String tz) {
265 mContext.enforceCallingOrSelfPermission(
266 "android.permission.SET_TIME_ZONE",
267 "setTimeZone");
268
269 if (TextUtils.isEmpty(tz)) return;
270 TimeZone zone = TimeZone.getTimeZone(tz);
271 // Prevent reentrant calls from stepping on each other when writing
272 // the time zone property
273 boolean timeZoneWasChanged = false;
274 synchronized (this) {
275 String current = SystemProperties.get(TIMEZONE_PROPERTY);
276 if (current == null || !current.equals(zone.getID())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800277 if (localLOGV) Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800278 timeZoneWasChanged = true;
279 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
280 }
281
282 // Update the kernel timezone information
283 // Kernel tracks time offsets as 'minutes west of GMT'
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +0200284 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Mike Lockwood1f7b4132009-11-20 15:12:51 -0500285 setKernelTimezone(mDescriptor, -(gmtOffset / 60000));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286 }
287
288 TimeZone.setDefault(null);
289
290 if (timeZoneWasChanged) {
291 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800292 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800293 intent.putExtra("time-zone", zone.getID());
294 mContext.sendBroadcast(intent);
295 }
296 }
297
298 public void remove(PendingIntent operation) {
299 if (operation == null) {
300 return;
301 }
302 synchronized (mLock) {
303 removeLocked(operation);
304 }
305 }
306
307 public void removeLocked(PendingIntent operation) {
308 removeLocked(mRtcWakeupAlarms, operation);
309 removeLocked(mRtcAlarms, operation);
310 removeLocked(mElapsedRealtimeWakeupAlarms, operation);
311 removeLocked(mElapsedRealtimeAlarms, operation);
312 }
313
314 private void removeLocked(ArrayList<Alarm> alarmList,
315 PendingIntent operation) {
316 if (alarmList.size() <= 0) {
317 return;
318 }
319
320 // iterator over the list removing any it where the intent match
321 Iterator<Alarm> it = alarmList.iterator();
322
323 while (it.hasNext()) {
324 Alarm alarm = it.next();
325 if (alarm.operation.equals(operation)) {
326 it.remove();
327 }
328 }
329 }
330
331 public void removeLocked(String packageName) {
332 removeLocked(mRtcWakeupAlarms, packageName);
333 removeLocked(mRtcAlarms, packageName);
334 removeLocked(mElapsedRealtimeWakeupAlarms, packageName);
335 removeLocked(mElapsedRealtimeAlarms, packageName);
336 }
337
338 private void removeLocked(ArrayList<Alarm> alarmList,
339 String packageName) {
340 if (alarmList.size() <= 0) {
341 return;
342 }
343
344 // iterator over the list removing any it where the intent match
345 Iterator<Alarm> it = alarmList.iterator();
346
347 while (it.hasNext()) {
348 Alarm alarm = it.next();
349 if (alarm.operation.getTargetPackage().equals(packageName)) {
350 it.remove();
351 }
352 }
353 }
354
Dianne Hackborn21f1bd12010-02-19 17:02:21 -0800355 public boolean lookForPackageLocked(String packageName) {
356 return lookForPackageLocked(mRtcWakeupAlarms, packageName)
357 || lookForPackageLocked(mRtcAlarms, packageName)
358 || lookForPackageLocked(mElapsedRealtimeWakeupAlarms, packageName)
359 || lookForPackageLocked(mElapsedRealtimeAlarms, packageName);
360 }
361
362 private boolean lookForPackageLocked(ArrayList<Alarm> alarmList, String packageName) {
363 for (int i=alarmList.size()-1; i>=0; i--) {
364 if (alarmList.get(i).operation.getTargetPackage().equals(packageName)) {
365 return true;
366 }
367 }
368 return false;
369 }
370
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800371 private ArrayList<Alarm> getAlarmList(int type) {
372 switch (type) {
373 case AlarmManager.RTC_WAKEUP: return mRtcWakeupAlarms;
374 case AlarmManager.RTC: return mRtcAlarms;
375 case AlarmManager.ELAPSED_REALTIME_WAKEUP: return mElapsedRealtimeWakeupAlarms;
376 case AlarmManager.ELAPSED_REALTIME: return mElapsedRealtimeAlarms;
377 }
378
379 return null;
380 }
381
382 private int addAlarmLocked(Alarm alarm) {
383 ArrayList<Alarm> alarmList = getAlarmList(alarm.type);
384
385 int index = Collections.binarySearch(alarmList, alarm, mIncreasingTimeOrder);
386 if (index < 0) {
387 index = 0 - index - 1;
388 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800389 if (localLOGV) Slog.v(TAG, "Adding alarm " + alarm + " at " + index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800390 alarmList.add(index, alarm);
391
392 if (localLOGV) {
393 // Display the list of alarms for this alarm type
Joe Onorato8a9b2202010-02-26 18:56:32 -0800394 Slog.v(TAG, "alarms: " + alarmList.size() + " type: " + alarm.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800395 int position = 0;
396 for (Alarm a : alarmList) {
397 Time time = new Time();
398 time.set(a.when);
399 String timeStr = time.format("%b %d %I:%M:%S %p");
Joe Onorato8a9b2202010-02-26 18:56:32 -0800400 Slog.v(TAG, position + ": " + timeStr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800401 + " " + a.operation.getTargetPackage());
402 position += 1;
403 }
404 }
405
406 return index;
407 }
408
409 public long timeToNextAlarm() {
Jeff Brown11c5f1a2010-03-31 15:29:40 -0700410 long nextAlarm = Long.MAX_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800411 synchronized (mLock) {
412 for (int i=AlarmManager.RTC_WAKEUP;
413 i<=AlarmManager.ELAPSED_REALTIME; i++) {
414 ArrayList<Alarm> alarmList = getAlarmList(i);
415 if (alarmList.size() > 0) {
416 Alarm a = alarmList.get(0);
417 if (a.when < nextAlarm) {
418 nextAlarm = a.when;
419 }
420 }
421 }
422 }
423 return nextAlarm;
424 }
425
426 private void setLocked(Alarm alarm)
427 {
428 if (mDescriptor != -1)
429 {
Jeff Brown11c5f1a2010-03-31 15:29:40 -0700430 // The kernel never triggers alarms with negative wakeup times
431 // so we ensure they are positive.
432 long alarmSeconds, alarmNanoseconds;
433 if (alarm.when < 0) {
434 alarmSeconds = 0;
435 alarmNanoseconds = 0;
436 } else {
437 alarmSeconds = alarm.when / 1000;
438 alarmNanoseconds = (alarm.when % 1000) * 1000 * 1000;
439 }
440
441 set(mDescriptor, alarm.type, alarmSeconds, alarmNanoseconds);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800442 }
443 else
444 {
445 Message msg = Message.obtain();
446 msg.what = ALARM_EVENT;
447
448 mHandler.removeMessages(ALARM_EVENT);
449 mHandler.sendMessageAtTime(msg, alarm.when);
450 }
451 }
452
453 @Override
454 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
455 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
456 != PackageManager.PERMISSION_GRANTED) {
457 pw.println("Permission Denial: can't dump AlarmManager from from pid="
458 + Binder.getCallingPid()
459 + ", uid=" + Binder.getCallingUid());
460 return;
461 }
462
463 synchronized (mLock) {
464 pw.println("Current Alarm Manager state:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700465 if (mRtcWakeupAlarms.size() > 0 || mRtcAlarms.size() > 0) {
Dianne Hackborn043fcd92010-10-06 14:27:34 -0700466 final long now = System.currentTimeMillis();
467 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800468 pw.println(" ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700469 pw.print(" Realtime wakeup (now=");
Dianne Hackborn043fcd92010-10-06 14:27:34 -0700470 pw.print(sdf.format(new Date(now))); pw.println("):");
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700471 if (mRtcWakeupAlarms.size() > 0) {
Dianne Hackborn043fcd92010-10-06 14:27:34 -0700472 dumpAlarmList(pw, mRtcWakeupAlarms, " ", "RTC_WAKEUP", now);
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700473 }
474 if (mRtcAlarms.size() > 0) {
Dianne Hackborn043fcd92010-10-06 14:27:34 -0700475 dumpAlarmList(pw, mRtcAlarms, " ", "RTC", now);
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700476 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800477 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700478 if (mElapsedRealtimeWakeupAlarms.size() > 0 || mElapsedRealtimeAlarms.size() > 0) {
Dianne Hackborn043fcd92010-10-06 14:27:34 -0700479 final long now = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 pw.println(" ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700481 pw.print(" Elapsed realtime wakeup (now=");
Dianne Hackborn043fcd92010-10-06 14:27:34 -0700482 TimeUtils.formatDuration(now, pw); pw.println("):");
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700483 if (mElapsedRealtimeWakeupAlarms.size() > 0) {
Dianne Hackborn043fcd92010-10-06 14:27:34 -0700484 dumpAlarmList(pw, mElapsedRealtimeWakeupAlarms, " ", "ELAPSED_WAKEUP", now);
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700485 }
486 if (mElapsedRealtimeAlarms.size() > 0) {
Dianne Hackborn043fcd92010-10-06 14:27:34 -0700487 dumpAlarmList(pw, mElapsedRealtimeAlarms, " ", "ELAPSED", now);
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700488 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 }
490
491 pw.println(" ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700492 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800493
494 pw.println(" ");
495 pw.println(" Alarm Stats:");
496 for (Map.Entry<String, BroadcastStats> be : mBroadcastStats.entrySet()) {
497 BroadcastStats bs = be.getValue();
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700498 pw.print(" "); pw.println(be.getKey());
499 pw.print(" "); pw.print(bs.aggregateTime);
500 pw.print("ms running, "); pw.print(bs.numWakeup);
501 pw.println(" wakeups");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800502 for (Map.Entry<Intent.FilterComparison, FilterStats> fe
503 : bs.filterStats.entrySet()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700504 pw.print(" "); pw.print(fe.getValue().count);
505 pw.print(" alarms: ");
506 pw.println(fe.getKey().getIntent().toShortString(true, false));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800507 }
508 }
509 }
510 }
511
Dianne Hackborn043fcd92010-10-06 14:27:34 -0700512 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
513 String prefix, String label, long now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800514 for (int i=list.size()-1; i>=0; i--) {
515 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700516 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
517 pw.print(": "); pw.println(a);
Dianne Hackborn043fcd92010-10-06 14:27:34 -0700518 a.dump(pw, prefix + " ", now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800519 }
520 }
521
522 private native int init();
523 private native void close(int fd);
Jeff Brown11c5f1a2010-03-31 15:29:40 -0700524 private native void set(int fd, int type, long seconds, long nanoseconds);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 private native int waitForAlarm(int fd);
526 private native int setKernelTimezone(int fd, int minuteswest);
527
528 private void triggerAlarmsLocked(ArrayList<Alarm> alarmList,
529 ArrayList<Alarm> triggerList,
530 long now)
531 {
532 Iterator<Alarm> it = alarmList.iterator();
533 ArrayList<Alarm> repeats = new ArrayList<Alarm>();
534
535 while (it.hasNext())
536 {
537 Alarm alarm = it.next();
538
Joe Onorato8a9b2202010-02-26 18:56:32 -0800539 if (localLOGV) Slog.v(TAG, "Checking active alarm when=" + alarm.when + " " + alarm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540
541 if (alarm.when > now) {
542 // don't fire alarms in the future
543 break;
544 }
545
546 // If the alarm is late, then print a warning message.
547 // Note that this can happen if the user creates a new event on
548 // the Calendar app with a reminder that is in the past. In that
549 // case, the reminder alarm will fire immediately.
550 if (localLOGV && now - alarm.when > LATE_ALARM_THRESHOLD) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800551 Slog.v(TAG, "alarm is late! alarm time: " + alarm.when
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 + " now: " + now + " delay (in seconds): "
553 + (now - alarm.when) / 1000);
554 }
555
556 // Recurring alarms may have passed several alarm intervals while the
557 // phone was asleep or off, so pass a trigger count when sending them.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800558 if (localLOGV) Slog.v(TAG, "Alarm triggering: " + alarm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559 alarm.count = 1;
560 if (alarm.repeatInterval > 0) {
561 // this adjustment will be zero if we're late by
562 // less than one full repeat interval
563 alarm.count += (now - alarm.when) / alarm.repeatInterval;
564 }
565 triggerList.add(alarm);
566
567 // remove the alarm from the list
568 it.remove();
569
570 // if it repeats queue it up to be read-added to the list
571 if (alarm.repeatInterval > 0) {
572 repeats.add(alarm);
573 }
574 }
575
576 // reset any repeating alarms.
577 it = repeats.iterator();
578 while (it.hasNext()) {
579 Alarm alarm = it.next();
580 alarm.when += alarm.count * alarm.repeatInterval;
581 addAlarmLocked(alarm);
582 }
583
584 if (alarmList.size() > 0) {
585 setLocked(alarmList.get(0));
586 }
587 }
588
589 /**
590 * This Comparator sorts Alarms into increasing time order.
591 */
592 public static class IncreasingTimeOrder implements Comparator<Alarm> {
593 public int compare(Alarm a1, Alarm a2) {
594 long when1 = a1.when;
595 long when2 = a2.when;
596 if (when1 - when2 > 0) {
597 return 1;
598 }
599 if (when1 - when2 < 0) {
600 return -1;
601 }
602 return 0;
603 }
604 }
605
606 private static class Alarm {
607 public int type;
608 public int count;
609 public long when;
610 public long repeatInterval;
611 public PendingIntent operation;
612
613 public Alarm() {
614 when = 0;
615 repeatInterval = 0;
616 operation = null;
617 }
618
619 @Override
620 public String toString()
621 {
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700622 StringBuilder sb = new StringBuilder(128);
623 sb.append("Alarm{");
624 sb.append(Integer.toHexString(System.identityHashCode(this)));
625 sb.append(" type ");
626 sb.append(type);
627 sb.append(" ");
628 sb.append(operation.getTargetPackage());
629 sb.append('}');
630 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800631 }
632
Dianne Hackborn043fcd92010-10-06 14:27:34 -0700633 public void dump(PrintWriter pw, String prefix, long now) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700634 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackborn043fcd92010-10-06 14:27:34 -0700635 pw.print(" when="); TimeUtils.formatDuration(when, now, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700636 pw.print(" repeatInterval="); pw.print(repeatInterval);
637 pw.print(" count="); pw.println(count);
638 pw.print(prefix); pw.print("operation="); pw.println(operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639 }
640 }
641
642 private class AlarmThread extends Thread
643 {
644 public AlarmThread()
645 {
646 super("AlarmManager");
647 }
648
649 public void run()
650 {
651 while (true)
652 {
653 int result = waitForAlarm(mDescriptor);
654
655 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
656
657 if ((result & TIME_CHANGED_MASK) != 0) {
658 remove(mTimeTickSender);
659 mClockReceiver.scheduleTimeTickEvent();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800660 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
661 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
662 mContext.sendBroadcast(intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800663 }
664
665 synchronized (mLock) {
666 final long nowRTC = System.currentTimeMillis();
667 final long nowELAPSED = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -0800668 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669 TAG, "Checking for alarms... rtc=" + nowRTC
670 + ", elapsed=" + nowELAPSED);
671
672 if ((result & RTC_WAKEUP_MASK) != 0)
673 triggerAlarmsLocked(mRtcWakeupAlarms, triggerList, nowRTC);
674
675 if ((result & RTC_MASK) != 0)
676 triggerAlarmsLocked(mRtcAlarms, triggerList, nowRTC);
677
678 if ((result & ELAPSED_REALTIME_WAKEUP_MASK) != 0)
679 triggerAlarmsLocked(mElapsedRealtimeWakeupAlarms, triggerList, nowELAPSED);
680
681 if ((result & ELAPSED_REALTIME_MASK) != 0)
682 triggerAlarmsLocked(mElapsedRealtimeAlarms, triggerList, nowELAPSED);
683
684 // now trigger the alarms
685 Iterator<Alarm> it = triggerList.iterator();
686 while (it.hasNext()) {
687 Alarm alarm = it.next();
688 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800689 if (localLOGV) Slog.v(TAG, "sending alarm " + alarm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 alarm.operation.send(mContext, 0,
691 mBackgroundIntent.putExtra(
692 Intent.EXTRA_ALARM_COUNT, alarm.count),
693 mResultReceiver, mHandler);
694
695 // we have an active broadcast so stay awake.
696 if (mBroadcastRefCount == 0) {
697 mWakeLock.acquire();
698 }
699 mBroadcastRefCount++;
700
701 BroadcastStats bs = getStatsLocked(alarm.operation);
702 if (bs.nesting == 0) {
703 bs.startTime = nowELAPSED;
704 } else {
705 bs.nesting++;
706 }
707 if (alarm.type == AlarmManager.ELAPSED_REALTIME_WAKEUP
708 || alarm.type == AlarmManager.RTC_WAKEUP) {
709 bs.numWakeup++;
710 ActivityManagerNative.noteWakeupAlarm(
711 alarm.operation);
712 }
713 } catch (PendingIntent.CanceledException e) {
714 if (alarm.repeatInterval > 0) {
715 // This IntentSender is no longer valid, but this
716 // is a repeating alarm, so toss the hoser.
717 remove(alarm.operation);
718 }
719 } catch (RuntimeException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800720 Slog.w(TAG, "Failure sending alarm.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 }
722 }
723 }
724 }
725 }
726 }
727
728 private class AlarmHandler extends Handler {
729 public static final int ALARM_EVENT = 1;
730 public static final int MINUTE_CHANGE_EVENT = 2;
731 public static final int DATE_CHANGE_EVENT = 3;
732
733 public AlarmHandler() {
734 }
735
736 public void handleMessage(Message msg) {
737 if (msg.what == ALARM_EVENT) {
738 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
739 synchronized (mLock) {
740 final long nowRTC = System.currentTimeMillis();
741 triggerAlarmsLocked(mRtcWakeupAlarms, triggerList, nowRTC);
742 triggerAlarmsLocked(mRtcAlarms, triggerList, nowRTC);
743 triggerAlarmsLocked(mElapsedRealtimeWakeupAlarms, triggerList, nowRTC);
744 triggerAlarmsLocked(mElapsedRealtimeAlarms, triggerList, nowRTC);
745 }
746
747 // now trigger the alarms without the lock held
748 Iterator<Alarm> it = triggerList.iterator();
749 while (it.hasNext())
750 {
751 Alarm alarm = it.next();
752 try {
753 alarm.operation.send();
754 } catch (PendingIntent.CanceledException e) {
755 if (alarm.repeatInterval > 0) {
756 // This IntentSender is no longer valid, but this
757 // is a repeating alarm, so toss the hoser.
758 remove(alarm.operation);
759 }
760 }
761 }
762 }
763 }
764 }
765
766 class ClockReceiver extends BroadcastReceiver {
767 public ClockReceiver() {
768 IntentFilter filter = new IntentFilter();
769 filter.addAction(Intent.ACTION_TIME_TICK);
770 filter.addAction(Intent.ACTION_DATE_CHANGED);
771 mContext.registerReceiver(this, filter);
772 }
773
774 @Override
775 public void onReceive(Context context, Intent intent) {
776 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
777 scheduleTimeTickEvent();
778 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
779 // Since the kernel does not keep track of DST, we need to
780 // reset the TZ information at the beginning of each day
781 // based off of the current Zone gmt offset + userspace tracked
782 // daylight savings information.
783 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +0200784 int gmtOffset = zone.getOffset(System.currentTimeMillis());
785 setKernelTimezone(mDescriptor, -(gmtOffset / 60000));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 scheduleDateChangedEvent();
787 }
788 }
789
790 public void scheduleTimeTickEvent() {
791 Calendar calendar = Calendar.getInstance();
792 calendar.setTimeInMillis(System.currentTimeMillis());
793 calendar.add(Calendar.MINUTE, 1);
794 calendar.set(Calendar.SECOND, 0);
795 calendar.set(Calendar.MILLISECOND, 0);
796
797 set(AlarmManager.RTC, calendar.getTimeInMillis(), mTimeTickSender);
798 }
799
800 public void scheduleDateChangedEvent() {
801 Calendar calendar = Calendar.getInstance();
802 calendar.setTimeInMillis(System.currentTimeMillis());
803 calendar.set(Calendar.HOUR, 0);
804 calendar.set(Calendar.MINUTE, 0);
805 calendar.set(Calendar.SECOND, 0);
806 calendar.set(Calendar.MILLISECOND, 0);
807 calendar.add(Calendar.DAY_OF_MONTH, 1);
808
809 set(AlarmManager.RTC, calendar.getTimeInMillis(), mDateChangeSender);
810 }
811 }
812
813 class UninstallReceiver extends BroadcastReceiver {
814 public UninstallReceiver() {
815 IntentFilter filter = new IntentFilter();
816 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
817 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -0800818 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 filter.addDataScheme("package");
820 mContext.registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800821 // Register for events related to sdcard installation.
822 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800823 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800824 mContext.registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825 }
826
827 @Override
828 public void onReceive(Context context, Intent intent) {
829 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800830 String action = intent.getAction();
831 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -0800832 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
833 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
834 for (String packageName : pkgList) {
835 if (lookForPackageLocked(packageName)) {
836 setResultCode(Activity.RESULT_OK);
837 return;
838 }
839 }
840 return;
841 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800842 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
843 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -0800844 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
845 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
846 // This package is being updated; don't kill its alarms.
847 return;
848 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800849 Uri data = intent.getData();
850 if (data != null) {
851 String pkg = data.getSchemeSpecificPart();
852 if (pkg != null) {
853 pkgList = new String[]{pkg};
854 }
855 }
856 }
857 if (pkgList != null && (pkgList.length > 0)) {
858 for (String pkg : pkgList) {
859 removeLocked(pkg);
860 mBroadcastStats.remove(pkg);
861 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 }
863 }
864 }
865 }
866
867 private final BroadcastStats getStatsLocked(PendingIntent pi) {
868 String pkg = pi.getTargetPackage();
869 BroadcastStats bs = mBroadcastStats.get(pkg);
870 if (bs == null) {
871 bs = new BroadcastStats();
872 mBroadcastStats.put(pkg, bs);
873 }
874 return bs;
875 }
876
877 class ResultReceiver implements PendingIntent.OnFinished {
878 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
879 String resultData, Bundle resultExtras) {
880 synchronized (mLock) {
881 BroadcastStats bs = getStatsLocked(pi);
882 if (bs != null) {
883 bs.nesting--;
884 if (bs.nesting <= 0) {
885 bs.nesting = 0;
886 bs.aggregateTime += SystemClock.elapsedRealtime()
887 - bs.startTime;
888 Intent.FilterComparison fc = new Intent.FilterComparison(intent);
889 FilterStats fs = bs.filterStats.get(fc);
890 if (fs == null) {
891 fs = new FilterStats();
892 bs.filterStats.put(fc, fs);
893 }
894 fs.count++;
895 }
896 }
897 mBroadcastRefCount--;
898 if (mBroadcastRefCount == 0) {
899 mWakeLock.release();
900 }
901 }
902 }
903 }
904}