blob: b70a34ec727ce953baae908fea26aa5bbe8dbd7c [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
Christopher Tate4cb338d2013-07-26 13:11:31 -070045import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import java.io.FileDescriptor;
47import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070048import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -080050import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import java.util.Calendar;
52import java.util.Collections;
53import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -050054import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -070056import java.util.LinkedList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import java.util.Map;
58import java.util.TimeZone;
59
Christopher Tatee0a22b32013-07-11 14:43:13 -070060import static android.app.AlarmManager.RTC_WAKEUP;
61import static android.app.AlarmManager.RTC;
62import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
63import static android.app.AlarmManager.ELAPSED_REALTIME;
64
Dianne Hackborn81038902012-11-26 17:04:09 -080065import com.android.internal.util.LocalLog;
66
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067class AlarmManagerService extends IAlarmManager.Stub {
68 // The threshold for how long an alarm can be late before we print a
69 // warning message. The time duration is in milliseconds.
70 private static final long LATE_ALARM_THRESHOLD = 10 * 1000;
Christopher Tatee0a22b32013-07-11 14:43:13 -070071
72 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
73 private static final int RTC_MASK = 1 << RTC;
74 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
75 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076 private static final int TIME_CHANGED_MASK = 1 << 16;
Christopher Tate18a75f12013-07-01 18:18:59 -070077 private static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -080078
Christopher Tatee0a22b32013-07-11 14:43:13 -070079 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
80 private static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -080081
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082 private static final String TAG = "AlarmManager";
83 private static final String ClockReceiver_TAG = "ClockReceiver";
84 private static final boolean localLOGV = false;
Christopher Tate4cb338d2013-07-26 13:11:31 -070085 private static final boolean DEBUG_BATCH = localLOGV || false;
Christopher Tatecdccf642013-07-29 16:23:05 -070086 private static final boolean DEBUG_VALIDATE = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087 private static final int ALARM_EVENT = 1;
88 private static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
89
90 private static final Intent mBackgroundIntent
91 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Christopher Tatee0a22b32013-07-11 14:43:13 -070092 private static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093
Christopher Tate95b58e22013-09-05 14:31:52 -070094 private static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -070095
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096 private final Context mContext;
Dianne Hackborn81038902012-11-26 17:04:09 -080097
98 private final LocalLog mLog = new LocalLog(TAG);
99
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100 private Object mLock = new Object();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102 private int mDescriptor;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700103 private long mNextWakeup;
104 private long mNextNonWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105 private int mBroadcastRefCount = 0;
106 private PowerManager.WakeLock mWakeLock;
Dianne Hackborn81038902012-11-26 17:04:09 -0800107 private ArrayList<InFlight> mInFlight = new ArrayList<InFlight>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108 private final AlarmThread mWaitThread = new AlarmThread();
109 private final AlarmHandler mHandler = new AlarmHandler();
110 private ClockReceiver mClockReceiver;
111 private UninstallReceiver mUninstallReceiver;
112 private final ResultReceiver mResultReceiver = new ResultReceiver();
113 private final PendingIntent mTimeTickSender;
114 private final PendingIntent mDateChangeSender;
Dianne Hackborn81038902012-11-26 17:04:09 -0800115
Christopher Tate18a75f12013-07-01 18:18:59 -0700116 class WakeupEvent {
117 public long when;
118 public int uid;
119 public String action;
120
121 public WakeupEvent(long theTime, int theUid, String theAction) {
122 when = theTime;
123 uid = theUid;
124 action = theAction;
125 }
126 }
127
128 private final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
129 private final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
130
Christopher Tatee0a22b32013-07-11 14:43:13 -0700131 static final class Batch {
132 long start; // These endpoints are always in ELAPSED
133 long end;
134 boolean standalone; // certain "batches" don't participate in coalescing
135
136 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
137
138 Batch() {
139 start = 0;
140 end = Long.MAX_VALUE;
141 }
142
143 Batch(Alarm seed) {
144 start = seed.whenElapsed;
145 end = seed.maxWhen;
146 alarms.add(seed);
147 }
148
149 int size() {
150 return alarms.size();
151 }
152
153 Alarm get(int index) {
154 return alarms.get(index);
155 }
156
157 boolean canHold(long whenElapsed, long maxWhen) {
158 return (end >= whenElapsed) && (start <= maxWhen);
159 }
160
161 boolean add(Alarm alarm) {
162 boolean newStart = false;
163 // narrows the batch if necessary; presumes that canHold(alarm) is true
164 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
165 if (index < 0) {
166 index = 0 - index - 1;
167 }
168 alarms.add(index, alarm);
169 if (DEBUG_BATCH) {
170 Slog.v(TAG, "Adding " + alarm + " to " + this);
171 }
172 if (alarm.whenElapsed > start) {
173 start = alarm.whenElapsed;
174 newStart = true;
175 }
176 if (alarm.maxWhen < end) {
177 end = alarm.maxWhen;
178 }
179
180 if (DEBUG_BATCH) {
181 Slog.v(TAG, " => now " + this);
182 }
183 return newStart;
184 }
185
186 boolean remove(final PendingIntent operation) {
187 boolean didRemove = false;
188 long newStart = 0; // recalculate endpoints as we go
189 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700190 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700191 Alarm alarm = alarms.get(i);
192 if (alarm.operation.equals(operation)) {
193 alarms.remove(i);
194 didRemove = true;
195 } else {
196 if (alarm.whenElapsed > newStart) {
197 newStart = alarm.whenElapsed;
198 }
199 if (alarm.maxWhen < newEnd) {
200 newEnd = alarm.maxWhen;
201 }
202 i++;
203 }
204 }
205 if (didRemove) {
206 // commit the new batch bounds
207 start = newStart;
208 end = newEnd;
209 }
210 return didRemove;
211 }
212
213 boolean remove(final String packageName) {
214 boolean didRemove = false;
215 long newStart = 0; // recalculate endpoints as we go
216 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700217 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700218 Alarm alarm = alarms.get(i);
219 if (alarm.operation.getTargetPackage().equals(packageName)) {
220 alarms.remove(i);
221 didRemove = true;
222 } else {
223 if (alarm.whenElapsed > newStart) {
224 newStart = alarm.whenElapsed;
225 }
226 if (alarm.maxWhen < newEnd) {
227 newEnd = alarm.maxWhen;
228 }
229 i++;
230 }
231 }
232 if (didRemove) {
233 // commit the new batch bounds
234 start = newStart;
235 end = newEnd;
236 }
237 return didRemove;
238 }
239
240 boolean remove(final int userHandle) {
241 boolean didRemove = false;
242 long newStart = 0; // recalculate endpoints as we go
243 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700244 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700245 Alarm alarm = alarms.get(i);
246 if (UserHandle.getUserId(alarm.operation.getCreatorUid()) == userHandle) {
247 alarms.remove(i);
248 didRemove = true;
249 } else {
250 if (alarm.whenElapsed > newStart) {
251 newStart = alarm.whenElapsed;
252 }
253 if (alarm.maxWhen < newEnd) {
254 newEnd = alarm.maxWhen;
255 }
256 i++;
257 }
258 }
259 if (didRemove) {
260 // commit the new batch bounds
261 start = newStart;
262 end = newEnd;
263 }
264 return didRemove;
265 }
266
267 boolean hasPackage(final String packageName) {
268 final int N = alarms.size();
269 for (int i = 0; i < N; i++) {
270 Alarm a = alarms.get(i);
271 if (a.operation.getTargetPackage().equals(packageName)) {
272 return true;
273 }
274 }
275 return false;
276 }
277
278 boolean hasWakeups() {
279 final int N = alarms.size();
280 for (int i = 0; i < N; i++) {
281 Alarm a = alarms.get(i);
282 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
283 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
284 return true;
285 }
286 }
287 return false;
288 }
289
290 @Override
291 public String toString() {
292 StringBuilder b = new StringBuilder(40);
293 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
294 b.append(" num="); b.append(size());
295 b.append(" start="); b.append(start);
296 b.append(" end="); b.append(end);
297 if (standalone) {
298 b.append(" STANDALONE");
299 }
300 b.append('}');
301 return b.toString();
302 }
303 }
304
305 static class BatchTimeOrder implements Comparator<Batch> {
306 public int compare(Batch b1, Batch b2) {
307 long when1 = b1.start;
308 long when2 = b2.start;
309 if (when1 - when2 > 0) {
310 return 1;
311 }
312 if (when1 - when2 < 0) {
313 return -1;
314 }
315 return 0;
316 }
317 }
318
319 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700320 private static final long MIN_FUZZABLE_INTERVAL = 10000;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700321 private static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
322 private final ArrayList<Batch> mAlarmBatches = new ArrayList<Batch>();
323
324 static long convertToElapsed(long when, int type) {
325 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
326 if (isRtc) {
327 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
328 }
329 return when;
330 }
331
332 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
333 // calculate the end of our nominal delivery window for the alarm.
334 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
335 // Current heuristic: batchable window is 75% of either the recurrence interval
336 // [for a periodic alarm] or of the time from now to the desired delivery time,
337 // with a minimum delay/interval of 10 seconds, under which we will simply not
338 // defer the alarm.
339 long futurity = (interval == 0)
340 ? (triggerAtTime - now)
341 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700342 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700343 futurity = 0;
344 }
345 return triggerAtTime + (long)(.75 * futurity);
346 }
347
348 // returns true if the batch was added at the head
349 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
350 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
351 if (index < 0) {
352 index = 0 - index - 1;
353 }
354 list.add(index, newBatch);
355 return (index == 0);
356 }
357
Christopher Tate385e4982013-07-23 18:22:29 -0700358 // Return the index of the matching batch, or -1 if none found.
359 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700360 final int N = mAlarmBatches.size();
361 for (int i = 0; i < N; i++) {
362 Batch b = mAlarmBatches.get(i);
363 if (!b.standalone && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700364 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700365 }
366 }
Christopher Tate385e4982013-07-23 18:22:29 -0700367 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700368 }
369
370 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
371 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700372 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700373 rebatchAllAlarmsLocked(true);
374 }
375 }
376
377 void rebatchAllAlarmsLocked(boolean doValidate) {
378 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
379 mAlarmBatches.clear();
380 final long nowElapsed = SystemClock.elapsedRealtime();
381 final int oldBatches = oldSet.size();
382 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
383 Batch batch = oldSet.get(batchNum);
384 final int N = batch.size();
385 for (int i = 0; i < N; i++) {
386 Alarm a = batch.get(i);
387 long whenElapsed = convertToElapsed(a.when, a.type);
Christopher Tate3e04b472013-10-21 17:51:31 -0700388 final long maxElapsed;
389 if (a.whenElapsed == a.maxWhen) {
390 // Exact
391 maxElapsed = whenElapsed;
392 } else {
393 // Not exact. Preserve any explicit window, otherwise recalculate
394 // the window based on the alarm's new futurity. Note that this
395 // reflects a policy of preferring timely to deferred delivery.
396 maxElapsed = (a.windowLength > 0)
397 ? (whenElapsed + a.windowLength)
398 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
399 }
400 setImplLocked(a.type, a.when, whenElapsed, a.windowLength, maxElapsed,
David Christieebe51fc2013-07-26 13:23:29 -0700401 a.repeatInterval, a.operation, batch.standalone, doValidate, a.workSource);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700402 }
403 }
404 }
405
Dianne Hackborn81038902012-11-26 17:04:09 -0800406 private static final class InFlight extends Intent {
407 final PendingIntent mPendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700408 final WorkSource mWorkSource;
Dianne Hackborn81038902012-11-26 17:04:09 -0800409 final Pair<String, ComponentName> mTarget;
410 final BroadcastStats mBroadcastStats;
411 final FilterStats mFilterStats;
412
David Christieebe51fc2013-07-26 13:23:29 -0700413 InFlight(AlarmManagerService service, PendingIntent pendingIntent, WorkSource workSource) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800414 mPendingIntent = pendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700415 mWorkSource = workSource;
Dianne Hackborn81038902012-11-26 17:04:09 -0800416 Intent intent = pendingIntent.getIntent();
417 mTarget = intent != null
418 ? new Pair<String, ComponentName>(intent.getAction(), intent.getComponent())
419 : null;
420 mBroadcastStats = service.getStatsLocked(pendingIntent);
421 FilterStats fs = mBroadcastStats.filterStats.get(mTarget);
422 if (fs == null) {
423 fs = new FilterStats(mBroadcastStats, mTarget);
424 mBroadcastStats.filterStats.put(mTarget, fs);
425 }
426 mFilterStats = fs;
427 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800429
430 private static final class FilterStats {
431 final BroadcastStats mBroadcastStats;
432 final Pair<String, ComponentName> mTarget;
433
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800434 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800435 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436 int numWakeup;
437 long startTime;
438 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -0800439
440 FilterStats(BroadcastStats broadcastStats, Pair<String, ComponentName> target) {
441 mBroadcastStats = broadcastStats;
442 mTarget = target;
443 }
444 }
445
446 private static final class BroadcastStats {
447 final String mPackageName;
448
449 long aggregateTime;
450 int count;
451 int numWakeup;
452 long startTime;
453 int nesting;
454 final HashMap<Pair<String, ComponentName>, FilterStats> filterStats
455 = new HashMap<Pair<String, ComponentName>, FilterStats>();
456
457 BroadcastStats(String packageName) {
458 mPackageName = packageName;
459 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800460 }
461
462 private final HashMap<String, BroadcastStats> mBroadcastStats
463 = new HashMap<String, BroadcastStats>();
464
465 public AlarmManagerService(Context context) {
466 mContext = context;
467 mDescriptor = init();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700468 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800469
470 // We have to set current TimeZone info to kernel
471 // because kernel doesn't keep this after reboot
472 String tz = SystemProperties.get(TIMEZONE_PROPERTY);
473 if (tz != null) {
474 setTimeZone(tz);
475 }
476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800477 PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
478 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
479
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700480 mTimeTickSender = PendingIntent.getBroadcastAsUser(context, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800481 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700482 Intent.FLAG_RECEIVER_REGISTERED_ONLY
483 | Intent.FLAG_RECEIVER_FOREGROUND), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700484 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800485 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
486 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700487 mDateChangeSender = PendingIntent.getBroadcastAsUser(context, 0, intent,
488 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489
490 // now that we have initied the driver schedule the alarm
491 mClockReceiver= new ClockReceiver();
492 mClockReceiver.scheduleTimeTickEvent();
493 mClockReceiver.scheduleDateChangedEvent();
494 mUninstallReceiver = new UninstallReceiver();
495
496 if (mDescriptor != -1) {
497 mWaitThread.start();
498 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800499 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800500 }
501 }
502
503 protected void finalize() throws Throwable {
504 try {
505 close(mDescriptor);
506 } finally {
507 super.finalize();
508 }
509 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700510
511 @Override
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700512 public void set(int type, long triggerAtTime, long windowLength, long interval,
David Christieebe51fc2013-07-26 13:23:29 -0700513 PendingIntent operation, WorkSource workSource) {
514 if (workSource != null) {
515 mContext.enforceCallingPermission(
516 android.Manifest.permission.UPDATE_DEVICE_STATS,
517 "AlarmManager.set");
518 }
519
520 set(type, triggerAtTime, windowLength, interval, operation, false, workSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700522
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700523 public void set(int type, long triggerAtTime, long windowLength, long interval,
David Christieebe51fc2013-07-26 13:23:29 -0700524 PendingIntent operation, boolean isStandalone, WorkSource workSource) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 if (operation == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800526 Slog.w(TAG, "set/setRepeating ignored because there is no intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800527 return;
528 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700529
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700530 // Sanity check the window length. This will catch people mistakenly
531 // trying to pass an end-of-window timestamp rather than a duration.
532 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
533 Slog.w(TAG, "Window length " + windowLength
534 + "ms suspiciously long; limiting to 1 hour");
535 windowLength = AlarmManager.INTERVAL_HOUR;
536 }
537
Christopher Tatee0a22b32013-07-11 14:43:13 -0700538 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
539 throw new IllegalArgumentException("Invalid alarm type " + type);
540 }
541
Christopher Tate5f221e82013-07-30 17:13:15 -0700542 if (triggerAtTime < 0) {
543 final long who = Binder.getCallingUid();
544 final long what = Binder.getCallingPid();
545 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + who
546 + " pid=" + what);
547 triggerAtTime = 0;
548 }
549
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700550 final long nowElapsed = SystemClock.elapsedRealtime();
551 final long triggerElapsed = convertToElapsed(triggerAtTime, type);
552 final long maxElapsed;
553 if (windowLength == AlarmManager.WINDOW_EXACT) {
554 maxElapsed = triggerElapsed;
555 } else if (windowLength < 0) {
556 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
557 } else {
558 maxElapsed = triggerElapsed + windowLength;
559 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800561 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700562 if (DEBUG_BATCH) {
563 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700564 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -0700565 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
566 + " interval=" + interval + " standalone=" + isStandalone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800567 }
Christopher Tate3e04b472013-10-21 17:51:31 -0700568 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
David Christieebe51fc2013-07-26 13:23:29 -0700569 interval, operation, isStandalone, true, workSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800570 }
571 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800572
Christopher Tate3e04b472013-10-21 17:51:31 -0700573 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
574 long maxWhen, long interval, PendingIntent operation, boolean isStandalone,
575 boolean doValidate, WorkSource workSource) {
576 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
577 operation, workSource);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700578 removeLocked(operation);
Christopher Tateb8849c12011-02-08 13:39:01 -0800579
Christopher Tate4cb338d2013-07-26 13:11:31 -0700580 boolean reschedule;
Christopher Tate385e4982013-07-23 18:22:29 -0700581 int whichBatch = (isStandalone) ? -1 : attemptCoalesceLocked(whenElapsed, maxWhen);
582 if (whichBatch < 0) {
583 Batch batch = new Batch(a);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700584 batch.standalone = isStandalone;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700585 reschedule = addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586 } else {
Christopher Tate385e4982013-07-23 18:22:29 -0700587 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700588 reschedule = batch.add(a);
Christopher Tate385e4982013-07-23 18:22:29 -0700589 if (reschedule) {
590 // The start time of this batch advanced, so batch ordering may
591 // have just been broken. Move it to where it now belongs.
592 mAlarmBatches.remove(whichBatch);
593 addBatchLocked(mAlarmBatches, batch);
594 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 }
596
Christopher Tate4cb338d2013-07-26 13:11:31 -0700597 if (DEBUG_VALIDATE) {
Christopher Tate5f221e82013-07-30 17:13:15 -0700598 if (doValidate && !validateConsistencyLocked()) {
599 Slog.v(TAG, "Tipping-point operation: type=" + type + " when=" + when
600 + " when(hex)=" + Long.toHexString(when)
601 + " whenElapsed=" + whenElapsed + " maxWhen=" + maxWhen
602 + " interval=" + interval + " op=" + operation
603 + " standalone=" + isStandalone);
Christopher Tate4cb338d2013-07-26 13:11:31 -0700604 rebatchAllAlarmsLocked(false);
605 reschedule = true;
606 }
607 }
608
Christopher Tatee0a22b32013-07-11 14:43:13 -0700609 if (reschedule) {
610 rescheduleKernelAlarmsLocked();
611 }
612 }
613
Christopher Tate4cb338d2013-07-26 13:11:31 -0700614 private void logBatchesLocked() {
615 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
616 PrintWriter pw = new PrintWriter(bs);
617 final long nowRTC = System.currentTimeMillis();
618 final long nowELAPSED = SystemClock.elapsedRealtime();
619 final int NZ = mAlarmBatches.size();
620 for (int iz = 0; iz < NZ; iz++) {
621 Batch bz = mAlarmBatches.get(iz);
Christopher Tate5f221e82013-07-30 17:13:15 -0700622 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Christopher Tate4cb338d2013-07-26 13:11:31 -0700623 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC);
Christopher Tate5f221e82013-07-30 17:13:15 -0700624 pw.flush();
Christopher Tate4cb338d2013-07-26 13:11:31 -0700625 Slog.v(TAG, bs.toString());
626 bs.reset();
627 }
628 }
629
630 private boolean validateConsistencyLocked() {
631 if (DEBUG_VALIDATE) {
632 long lastTime = Long.MIN_VALUE;
633 final int N = mAlarmBatches.size();
634 for (int i = 0; i < N; i++) {
635 Batch b = mAlarmBatches.get(i);
636 if (b.start >= lastTime) {
637 // duplicate start times are okay because of standalone batches
638 lastTime = b.start;
639 } else {
640 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
641 logBatchesLocked();
642 return false;
643 }
644 }
645 }
646 return true;
647 }
648
Christopher Tatee0a22b32013-07-11 14:43:13 -0700649 private Batch findFirstWakeupBatchLocked() {
650 final int N = mAlarmBatches.size();
651 for (int i = 0; i < N; i++) {
652 Batch b = mAlarmBatches.get(i);
653 if (b.hasWakeups()) {
654 return b;
655 }
656 }
657 return null;
658 }
659
660 private void rescheduleKernelAlarmsLocked() {
661 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
662 // prior to that which contains no wakeups, we schedule that as well.
Christopher Tate20f170d2013-07-31 13:01:02 -0700663 if (mAlarmBatches.size() > 0) {
664 final Batch firstWakeup = findFirstWakeupBatchLocked();
665 final Batch firstBatch = mAlarmBatches.get(0);
666 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
667 mNextWakeup = firstWakeup.start;
668 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
669 }
670 if (firstBatch != firstWakeup && mNextNonWakeup != firstBatch.start) {
671 mNextNonWakeup = firstBatch.start;
672 setLocked(ELAPSED_REALTIME, firstBatch.start);
673 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700674 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675 }
676
Dan Egnor97e44942010-02-04 20:27:47 -0800677 public void setTime(long millis) {
678 mContext.enforceCallingOrSelfPermission(
679 "android.permission.SET_TIME",
680 "setTime");
681
682 SystemClock.setCurrentTimeMillis(millis);
683 }
684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 public void setTimeZone(String tz) {
686 mContext.enforceCallingOrSelfPermission(
687 "android.permission.SET_TIME_ZONE",
688 "setTimeZone");
689
Christopher Tate89779822012-08-31 14:40:03 -0700690 long oldId = Binder.clearCallingIdentity();
691 try {
692 if (TextUtils.isEmpty(tz)) return;
693 TimeZone zone = TimeZone.getTimeZone(tz);
694 // Prevent reentrant calls from stepping on each other when writing
695 // the time zone property
696 boolean timeZoneWasChanged = false;
697 synchronized (this) {
698 String current = SystemProperties.get(TIMEZONE_PROPERTY);
699 if (current == null || !current.equals(zone.getID())) {
700 if (localLOGV) {
701 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
702 }
703 timeZoneWasChanged = true;
704 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
705 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706
Christopher Tate89779822012-08-31 14:40:03 -0700707 // Update the kernel timezone information
708 // Kernel tracks time offsets as 'minutes west of GMT'
709 int gmtOffset = zone.getOffset(System.currentTimeMillis());
710 setKernelTimezone(mDescriptor, -(gmtOffset / 60000));
711 }
712
713 TimeZone.setDefault(null);
714
715 if (timeZoneWasChanged) {
716 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
717 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
718 intent.putExtra("time-zone", zone.getID());
719 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
720 }
721 } finally {
722 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 }
724 }
725
726 public void remove(PendingIntent operation) {
727 if (operation == null) {
728 return;
729 }
730 synchronized (mLock) {
731 removeLocked(operation);
732 }
733 }
734
735 public void removeLocked(PendingIntent operation) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700736 boolean didRemove = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700737 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
738 Batch b = mAlarmBatches.get(i);
Christopher Tate4cb338d2013-07-26 13:11:31 -0700739 didRemove |= b.remove(operation);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700740 if (b.size() == 0) {
741 mAlarmBatches.remove(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800742 }
743 }
Christopher Tate4cb338d2013-07-26 13:11:31 -0700744
745 if (didRemove) {
746 if (DEBUG_BATCH) {
747 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
748 }
749 rebatchAllAlarmsLocked(true);
750 rescheduleKernelAlarmsLocked();
751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 public void removeLocked(String packageName) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700755 boolean didRemove = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700756 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
757 Batch b = mAlarmBatches.get(i);
Christopher Tate4cb338d2013-07-26 13:11:31 -0700758 didRemove |= b.remove(packageName);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700759 if (b.size() == 0) {
760 mAlarmBatches.remove(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800761 }
762 }
Christopher Tate4cb338d2013-07-26 13:11:31 -0700763
764 if (didRemove) {
765 if (DEBUG_BATCH) {
766 Slog.v(TAG, "remove(package) changed bounds; rebatching");
767 }
768 rebatchAllAlarmsLocked(true);
769 rescheduleKernelAlarmsLocked();
770 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700772
773 public void removeUserLocked(int userHandle) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700774 boolean didRemove = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700775 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
776 Batch b = mAlarmBatches.get(i);
Christopher Tate4cb338d2013-07-26 13:11:31 -0700777 didRemove |= b.remove(userHandle);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700778 if (b.size() == 0) {
779 mAlarmBatches.remove(i);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700780 }
781 }
Christopher Tate4cb338d2013-07-26 13:11:31 -0700782
783 if (didRemove) {
784 if (DEBUG_BATCH) {
785 Slog.v(TAG, "remove(user) changed bounds; rebatching");
786 }
787 rebatchAllAlarmsLocked(true);
788 rescheduleKernelAlarmsLocked();
789 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700790 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -0800791
Christopher Tatee0a22b32013-07-11 14:43:13 -0700792 public boolean lookForPackageLocked(String packageName) {
793 for (int i = 0; i < mAlarmBatches.size(); i++) {
794 Batch b = mAlarmBatches.get(i);
795 if (b.hasPackage(packageName)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -0800796 return true;
797 }
798 }
799 return false;
800 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801
Christopher Tatee0a22b32013-07-11 14:43:13 -0700802 private void setLocked(int type, long when)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800803 {
804 if (mDescriptor != -1)
805 {
Jeff Brown11c5f1a2010-03-31 15:29:40 -0700806 // The kernel never triggers alarms with negative wakeup times
807 // so we ensure they are positive.
808 long alarmSeconds, alarmNanoseconds;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700809 if (when < 0) {
Jeff Brown11c5f1a2010-03-31 15:29:40 -0700810 alarmSeconds = 0;
811 alarmNanoseconds = 0;
812 } else {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700813 alarmSeconds = when / 1000;
814 alarmNanoseconds = (when % 1000) * 1000 * 1000;
Jeff Brown11c5f1a2010-03-31 15:29:40 -0700815 }
816
Christopher Tatee0a22b32013-07-11 14:43:13 -0700817 set(mDescriptor, type, alarmSeconds, alarmNanoseconds);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 }
819 else
820 {
821 Message msg = Message.obtain();
822 msg.what = ALARM_EVENT;
823
824 mHandler.removeMessages(ALARM_EVENT);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700825 mHandler.sendMessageAtTime(msg, when);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 }
827 }
828
829 @Override
830 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
831 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
832 != PackageManager.PERMISSION_GRANTED) {
833 pw.println("Permission Denial: can't dump AlarmManager from from pid="
834 + Binder.getCallingPid()
835 + ", uid=" + Binder.getCallingUid());
836 return;
837 }
838
839 synchronized (mLock) {
840 pw.println("Current Alarm Manager state:");
Christopher Tatee0a22b32013-07-11 14:43:13 -0700841 final long nowRTC = System.currentTimeMillis();
842 final long nowELAPSED = SystemClock.elapsedRealtime();
843 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
844
845 pw.print("nowRTC="); pw.print(nowRTC);
846 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
847 pw.print(" nowELAPSED="); pw.println(nowELAPSED);
848
849 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
850 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
851 pw.print("Next alarm: "); pw.print(mNextNonWakeup);
852 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
853 pw.print("Next wakeup: "); pw.print(mNextWakeup);
854 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
855
856 if (mAlarmBatches.size() > 0) {
857 pw.println();
858 pw.print("Pending alarm batches: ");
859 pw.println(mAlarmBatches.size());
860 for (Batch b : mAlarmBatches) {
861 pw.print(b); pw.println(':');
862 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC);
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700863 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800865
866 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700867 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -0800868 pw.println();
869
870 if (mLog.dump(pw, " Recent problems", " ")) {
871 pw.println();
872 }
873
874 final FilterStats[] topFilters = new FilterStats[10];
875 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
876 @Override
877 public int compare(FilterStats lhs, FilterStats rhs) {
878 if (lhs.aggregateTime < rhs.aggregateTime) {
879 return 1;
880 } else if (lhs.aggregateTime > rhs.aggregateTime) {
881 return -1;
882 }
883 return 0;
884 }
885 };
886 int len = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 for (Map.Entry<String, BroadcastStats> be : mBroadcastStats.entrySet()) {
888 BroadcastStats bs = be.getValue();
Dianne Hackborn81038902012-11-26 17:04:09 -0800889 for (Map.Entry<Pair<String, ComponentName>, FilterStats> fe
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 : bs.filterStats.entrySet()) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800891 FilterStats fs = fe.getValue();
892 int pos = len > 0
893 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
894 if (pos < 0) {
895 pos = -pos - 1;
896 }
897 if (pos < topFilters.length) {
898 int copylen = topFilters.length - pos - 1;
899 if (copylen > 0) {
900 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
901 }
902 topFilters[pos] = fs;
903 if (len < topFilters.length) {
904 len++;
905 }
906 }
907 }
908 }
909 if (len > 0) {
910 pw.println(" Top Alarms:");
911 for (int i=0; i<len; i++) {
912 FilterStats fs = topFilters[i];
913 pw.print(" ");
914 if (fs.nesting > 0) pw.print("*ACTIVE* ");
915 TimeUtils.formatDuration(fs.aggregateTime, pw);
916 pw.print(" running, "); pw.print(fs.numWakeup);
917 pw.print(" wakeups, "); pw.print(fs.count);
918 pw.print(" alarms: "); pw.print(fs.mBroadcastStats.mPackageName);
919 pw.println();
920 pw.print(" ");
921 if (fs.mTarget.first != null) {
922 pw.print(" act="); pw.print(fs.mTarget.first);
923 }
924 if (fs.mTarget.second != null) {
925 pw.print(" cmp="); pw.print(fs.mTarget.second.toShortString());
926 }
927 pw.println();
928 }
929 }
930
931 pw.println(" ");
932 pw.println(" Alarm Stats:");
933 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
934 for (Map.Entry<String, BroadcastStats> be : mBroadcastStats.entrySet()) {
935 BroadcastStats bs = be.getValue();
936 pw.print(" ");
937 if (bs.nesting > 0) pw.print("*ACTIVE* ");
938 pw.print(be.getKey());
939 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
940 pw.print(" running, "); pw.print(bs.numWakeup);
941 pw.println(" wakeups:");
942 tmpFilters.clear();
943 for (Map.Entry<Pair<String, ComponentName>, FilterStats> fe
944 : bs.filterStats.entrySet()) {
945 tmpFilters.add(fe.getValue());
946 }
947 Collections.sort(tmpFilters, comparator);
948 for (int i=0; i<tmpFilters.size(); i++) {
949 FilterStats fs = tmpFilters.get(i);
950 pw.print(" ");
951 if (fs.nesting > 0) pw.print("*ACTIVE* ");
952 TimeUtils.formatDuration(fs.aggregateTime, pw);
953 pw.print(" "); pw.print(fs.numWakeup);
954 pw.print(" wakes " ); pw.print(fs.count);
955 pw.print(" alarms:");
956 if (fs.mTarget.first != null) {
957 pw.print(" act="); pw.print(fs.mTarget.first);
958 }
959 if (fs.mTarget.second != null) {
960 pw.print(" cmp="); pw.print(fs.mTarget.second.toShortString());
961 }
962 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963 }
964 }
Christopher Tate18a75f12013-07-01 18:18:59 -0700965
966 if (WAKEUP_STATS) {
967 pw.println();
968 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -0700969 long last = -1;
970 for (WakeupEvent event : mRecentWakeups) {
971 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
972 pw.print('|');
973 if (last < 0) {
974 pw.print('0');
975 } else {
976 pw.print(event.when - last);
977 }
978 last = event.when;
979 pw.print('|'); pw.print(event.uid);
980 pw.print('|'); pw.print(event.action);
981 pw.println();
982 }
983 pw.println();
984 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 }
986 }
987
Dianne Hackborn043fcd92010-10-06 14:27:34 -0700988 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
989 String prefix, String label, long now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 for (int i=list.size()-1; i>=0; i--) {
991 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700992 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
993 pw.print(": "); pw.println(a);
Dianne Hackborn043fcd92010-10-06 14:27:34 -0700994 a.dump(pw, prefix + " ", now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995 }
996 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700997
998 private static final String labelForType(int type) {
999 switch (type) {
1000 case RTC: return "RTC";
1001 case RTC_WAKEUP : return "RTC_WAKEUP";
1002 case ELAPSED_REALTIME : return "ELAPSED";
1003 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
1004 default:
1005 break;
1006 }
1007 return "--unknown--";
1008 }
1009
1010 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
1011 String prefix, long nowELAPSED, long nowRTC) {
1012 for (int i=list.size()-1; i>=0; i--) {
1013 Alarm a = list.get(i);
1014 final String label = labelForType(a.type);
1015 long now = (a.type <= RTC) ? nowRTC : nowELAPSED;
1016 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1017 pw.print(": "); pw.println(a);
1018 a.dump(pw, prefix + " ", now);
1019 }
1020 }
1021
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022 private native int init();
1023 private native void close(int fd);
Jeff Brown11c5f1a2010-03-31 15:29:40 -07001024 private native void set(int fd, int type, long seconds, long nanoseconds);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025 private native int waitForAlarm(int fd);
1026 private native int setKernelTimezone(int fd, int minuteswest);
1027
Christopher Tatee0a22b32013-07-11 14:43:13 -07001028 private void triggerAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED, long nowRTC) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001029 // batches are temporally sorted, so we need only pull from the
1030 // start of the list until we either empty it or hit a batch
1031 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07001032 while (mAlarmBatches.size() > 0) {
1033 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001034 if (batch.start > nowELAPSED) {
1035 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 break;
1037 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038
Christopher Tatee0a22b32013-07-11 14:43:13 -07001039 // We will (re)schedule some alarms now; don't let that interfere
1040 // with delivery of this current batch
1041 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001042
Christopher Tatee0a22b32013-07-11 14:43:13 -07001043 final int N = batch.size();
1044 for (int i = 0; i < N; i++) {
1045 Alarm alarm = batch.get(i);
1046 alarm.count = 1;
1047 triggerList.add(alarm);
1048
1049 // Recurring alarms may have passed several alarm intervals while the
1050 // phone was asleep or off, so pass a trigger count when sending them.
1051 if (alarm.repeatInterval > 0) {
1052 // this adjustment will be zero if we're late by
1053 // less than one full repeat interval
1054 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
1055
1056 // Also schedule its next recurrence
1057 final long delta = alarm.count * alarm.repeatInterval;
1058 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07001059 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07001060 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
David Christieebe51fc2013-07-26 13:23:29 -07001061 alarm.repeatInterval, alarm.operation, batch.standalone, true,
1062 alarm.workSource);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001063 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064
Dianne Hackborn390517b2013-05-30 15:03:32 -07001065 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001068
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 /**
1070 * This Comparator sorts Alarms into increasing time order.
1071 */
1072 public static class IncreasingTimeOrder implements Comparator<Alarm> {
1073 public int compare(Alarm a1, Alarm a2) {
1074 long when1 = a1.when;
1075 long when2 = a2.when;
1076 if (when1 - when2 > 0) {
1077 return 1;
1078 }
1079 if (when1 - when2 < 0) {
1080 return -1;
1081 }
1082 return 0;
1083 }
1084 }
1085
1086 private static class Alarm {
1087 public int type;
1088 public int count;
1089 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07001090 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001091 public long whenElapsed; // 'when' in the elapsed time base
1092 public long maxWhen; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 public long repeatInterval;
1094 public PendingIntent operation;
David Christieebe51fc2013-07-26 13:23:29 -07001095 public WorkSource workSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096
Christopher Tate3e04b472013-10-21 17:51:31 -07001097 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
David Christieebe51fc2013-07-26 13:23:29 -07001098 long _interval, PendingIntent _op, WorkSource _ws) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001099 type = _type;
1100 when = _when;
1101 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07001102 windowLength = _windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001103 maxWhen = _maxWhen;
1104 repeatInterval = _interval;
1105 operation = _op;
David Christieebe51fc2013-07-26 13:23:29 -07001106 workSource = _ws;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 @Override
1110 public String toString()
1111 {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001112 StringBuilder sb = new StringBuilder(128);
1113 sb.append("Alarm{");
1114 sb.append(Integer.toHexString(System.identityHashCode(this)));
1115 sb.append(" type ");
1116 sb.append(type);
1117 sb.append(" ");
1118 sb.append(operation.getTargetPackage());
1119 sb.append('}');
1120 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 }
1122
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001123 public void dump(PrintWriter pw, String prefix, long now) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001124 pw.print(prefix); pw.print("type="); pw.print(type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001125 pw.print(" whenElapsed="); pw.print(whenElapsed);
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001126 pw.print(" when="); TimeUtils.formatDuration(when, now, pw);
Christopher Tate3e04b472013-10-21 17:51:31 -07001127 pw.print(" window="); pw.print(windowLength);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001128 pw.print(" repeatInterval="); pw.print(repeatInterval);
1129 pw.print(" count="); pw.println(count);
1130 pw.print(prefix); pw.print("operation="); pw.println(operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 }
1132 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001133
Christopher Tatee0a22b32013-07-11 14:43:13 -07001134 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
1135 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07001136 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
1137 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001138 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07001139 break;
1140 }
1141
Christopher Tatee0a22b32013-07-11 14:43:13 -07001142 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07001143 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
1144 Alarm a = b.alarms.get(nextAlarm);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001145 WakeupEvent e = new WakeupEvent(nowRTC,
1146 a.operation.getCreatorUid(),
1147 a.operation.getIntent().getAction());
1148 mRecentWakeups.add(e);
1149 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001150 }
1151 }
1152
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 private class AlarmThread extends Thread
1154 {
1155 public AlarmThread()
1156 {
1157 super("AlarmManager");
1158 }
1159
1160 public void run()
1161 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07001162 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
1163
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 while (true)
1165 {
1166 int result = waitForAlarm(mDescriptor);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001167
1168 triggerList.clear();
1169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001170 if ((result & TIME_CHANGED_MASK) != 0) {
Christopher Tate385e4982013-07-23 18:22:29 -07001171 if (DEBUG_BATCH) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001172 Slog.v(TAG, "Time changed notification from kernel; rebatching");
Christopher Tate385e4982013-07-23 18:22:29 -07001173 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 remove(mTimeTickSender);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001175 rebatchAllAlarms();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 mClockReceiver.scheduleTimeTickEvent();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001177 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
Dianne Hackborn89ba6752011-01-23 16:51:16 -08001178 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1179 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001180 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 }
1182
1183 synchronized (mLock) {
1184 final long nowRTC = System.currentTimeMillis();
1185 final long nowELAPSED = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001186 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001187 TAG, "Checking for alarms... rtc=" + nowRTC
1188 + ", elapsed=" + nowELAPSED);
1189
Christopher Tate18a75f12013-07-01 18:18:59 -07001190 if (WAKEUP_STATS) {
1191 if ((result & IS_WAKEUP_MASK) != 0) {
1192 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
1193 int n = 0;
1194 for (WakeupEvent event : mRecentWakeups) {
1195 if (event.when > newEarliest) break;
1196 n++; // number of now-stale entries at the list head
1197 }
1198 for (int i = 0; i < n; i++) {
1199 mRecentWakeups.remove();
1200 }
1201
Christopher Tatee0a22b32013-07-11 14:43:13 -07001202 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Christopher Tate18a75f12013-07-01 18:18:59 -07001203 }
1204 }
1205
Christopher Tatee0a22b32013-07-11 14:43:13 -07001206 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
1207 rescheduleKernelAlarmsLocked();
1208
1209 // now deliver the alarm intents
Dianne Hackborn390517b2013-05-30 15:03:32 -07001210 for (int i=0; i<triggerList.size(); i++) {
1211 Alarm alarm = triggerList.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001213 if (localLOGV) Slog.v(TAG, "sending alarm " + alarm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 alarm.operation.send(mContext, 0,
1215 mBackgroundIntent.putExtra(
1216 Intent.EXTRA_ALARM_COUNT, alarm.count),
1217 mResultReceiver, mHandler);
1218
Christopher Tatec4a07d12012-04-06 14:19:13 -07001219 // we have an active broadcast so stay awake.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001220 if (mBroadcastRefCount == 0) {
David Christieebe51fc2013-07-26 13:23:29 -07001221 setWakelockWorkSource(alarm.operation, alarm.workSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 mWakeLock.acquire();
1223 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001224 final InFlight inflight = new InFlight(AlarmManagerService.this,
David Christieebe51fc2013-07-26 13:23:29 -07001225 alarm.operation, alarm.workSource);
Dianne Hackborn81038902012-11-26 17:04:09 -08001226 mInFlight.add(inflight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001227 mBroadcastRefCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08001228
1229 final BroadcastStats bs = inflight.mBroadcastStats;
1230 bs.count++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 if (bs.nesting == 0) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001232 bs.nesting = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 bs.startTime = nowELAPSED;
1234 } else {
1235 bs.nesting++;
1236 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001237 final FilterStats fs = inflight.mFilterStats;
1238 fs.count++;
1239 if (fs.nesting == 0) {
1240 fs.nesting = 1;
1241 fs.startTime = nowELAPSED;
1242 } else {
1243 fs.nesting++;
1244 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001245 if (alarm.type == ELAPSED_REALTIME_WAKEUP
1246 || alarm.type == RTC_WAKEUP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001247 bs.numWakeup++;
Dianne Hackborn81038902012-11-26 17:04:09 -08001248 fs.numWakeup++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249 ActivityManagerNative.noteWakeupAlarm(
1250 alarm.operation);
1251 }
1252 } catch (PendingIntent.CanceledException e) {
1253 if (alarm.repeatInterval > 0) {
1254 // This IntentSender is no longer valid, but this
1255 // is a repeating alarm, so toss the hoser.
1256 remove(alarm.operation);
1257 }
1258 } catch (RuntimeException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001259 Slog.w(TAG, "Failure sending alarm.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001260 }
1261 }
1262 }
1263 }
1264 }
1265 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07001266
David Christieebe51fc2013-07-26 13:23:29 -07001267 /**
1268 * Attribute blame for a WakeLock.
1269 * @param pi PendingIntent to attribute blame to if ws is null.
1270 * @param ws WorkSource to attribute blame.
1271 */
1272 void setWakelockWorkSource(PendingIntent pi, WorkSource ws) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07001273 try {
David Christieebe51fc2013-07-26 13:23:29 -07001274 if (ws != null) {
1275 mWakeLock.setWorkSource(ws);
1276 return;
1277 }
1278
Christopher Tatec4a07d12012-04-06 14:19:13 -07001279 final int uid = ActivityManagerNative.getDefault()
1280 .getUidForIntentSender(pi.getTarget());
1281 if (uid >= 0) {
1282 mWakeLock.setWorkSource(new WorkSource(uid));
1283 return;
1284 }
1285 } catch (Exception e) {
1286 }
1287
1288 // Something went wrong; fall back to attributing the lock to the OS
1289 mWakeLock.setWorkSource(null);
1290 }
1291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 private class AlarmHandler extends Handler {
1293 public static final int ALARM_EVENT = 1;
1294 public static final int MINUTE_CHANGE_EVENT = 2;
1295 public static final int DATE_CHANGE_EVENT = 3;
1296
1297 public AlarmHandler() {
1298 }
1299
1300 public void handleMessage(Message msg) {
1301 if (msg.what == ALARM_EVENT) {
1302 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
1303 synchronized (mLock) {
1304 final long nowRTC = System.currentTimeMillis();
Christopher Tatee0a22b32013-07-11 14:43:13 -07001305 final long nowELAPSED = SystemClock.elapsedRealtime();
1306 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307 }
1308
1309 // now trigger the alarms without the lock held
Dianne Hackborn390517b2013-05-30 15:03:32 -07001310 for (int i=0; i<triggerList.size(); i++) {
1311 Alarm alarm = triggerList.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 try {
1313 alarm.operation.send();
1314 } catch (PendingIntent.CanceledException e) {
1315 if (alarm.repeatInterval > 0) {
1316 // This IntentSender is no longer valid, but this
1317 // is a repeating alarm, so toss the hoser.
1318 remove(alarm.operation);
1319 }
1320 }
1321 }
1322 }
1323 }
1324 }
1325
1326 class ClockReceiver extends BroadcastReceiver {
1327 public ClockReceiver() {
1328 IntentFilter filter = new IntentFilter();
1329 filter.addAction(Intent.ACTION_TIME_TICK);
1330 filter.addAction(Intent.ACTION_DATE_CHANGED);
1331 mContext.registerReceiver(this, filter);
1332 }
1333
1334 @Override
1335 public void onReceive(Context context, Intent intent) {
1336 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001337 if (DEBUG_BATCH) {
1338 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
1339 }
1340 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001341 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
1342 // Since the kernel does not keep track of DST, we need to
1343 // reset the TZ information at the beginning of each day
1344 // based off of the current Zone gmt offset + userspace tracked
1345 // daylight savings information.
1346 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02001347 int gmtOffset = zone.getOffset(System.currentTimeMillis());
1348 setKernelTimezone(mDescriptor, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07001349 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350 }
1351 }
1352
1353 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07001354 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09001355 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07001356
1357 // Schedule this event for the amount of time that it would take to get to
1358 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09001359 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07001360
David Christieebe51fc2013-07-26 13:23:29 -07001361 final WorkSource workSource = null; // Let system take blame for time tick events.
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001362 set(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
David Christieebe51fc2013-07-26 13:23:29 -07001363 0, mTimeTickSender, true, workSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 }
Christopher Tate385e4982013-07-23 18:22:29 -07001365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366 public void scheduleDateChangedEvent() {
1367 Calendar calendar = Calendar.getInstance();
1368 calendar.setTimeInMillis(System.currentTimeMillis());
1369 calendar.set(Calendar.HOUR, 0);
1370 calendar.set(Calendar.MINUTE, 0);
1371 calendar.set(Calendar.SECOND, 0);
1372 calendar.set(Calendar.MILLISECOND, 0);
1373 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07001374
1375 final WorkSource workSource = null; // Let system take blame for date change events.
1376 set(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, true, workSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 }
1378 }
1379
1380 class UninstallReceiver extends BroadcastReceiver {
1381 public UninstallReceiver() {
1382 IntentFilter filter = new IntentFilter();
1383 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1384 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001385 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 filter.addDataScheme("package");
1387 mContext.registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001388 // Register for events related to sdcard installation.
1389 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001390 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001391 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001392 mContext.registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393 }
1394
1395 @Override
1396 public void onReceive(Context context, Intent intent) {
1397 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001398 String action = intent.getAction();
1399 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001400 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
1401 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
1402 for (String packageName : pkgList) {
1403 if (lookForPackageLocked(packageName)) {
1404 setResultCode(Activity.RESULT_OK);
1405 return;
1406 }
1407 }
1408 return;
1409 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001410 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001411 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
1412 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
1413 if (userHandle >= 0) {
1414 removeUserLocked(userHandle);
1415 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001416 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08001417 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
1418 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
1419 // This package is being updated; don't kill its alarms.
1420 return;
1421 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001422 Uri data = intent.getData();
1423 if (data != null) {
1424 String pkg = data.getSchemeSpecificPart();
1425 if (pkg != null) {
1426 pkgList = new String[]{pkg};
1427 }
1428 }
1429 }
1430 if (pkgList != null && (pkgList.length > 0)) {
1431 for (String pkg : pkgList) {
1432 removeLocked(pkg);
1433 mBroadcastStats.remove(pkg);
1434 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 }
1436 }
1437 }
1438 }
1439
1440 private final BroadcastStats getStatsLocked(PendingIntent pi) {
1441 String pkg = pi.getTargetPackage();
1442 BroadcastStats bs = mBroadcastStats.get(pkg);
1443 if (bs == null) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001444 bs = new BroadcastStats(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 mBroadcastStats.put(pkg, bs);
1446 }
1447 return bs;
1448 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450 class ResultReceiver implements PendingIntent.OnFinished {
1451 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
1452 String resultData, Bundle resultExtras) {
1453 synchronized (mLock) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001454 InFlight inflight = null;
1455 for (int i=0; i<mInFlight.size(); i++) {
1456 if (mInFlight.get(i).mPendingIntent == pi) {
1457 inflight = mInFlight.remove(i);
1458 break;
1459 }
1460 }
1461 if (inflight != null) {
1462 final long nowELAPSED = SystemClock.elapsedRealtime();
1463 BroadcastStats bs = inflight.mBroadcastStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 bs.nesting--;
1465 if (bs.nesting <= 0) {
1466 bs.nesting = 0;
Dianne Hackborn81038902012-11-26 17:04:09 -08001467 bs.aggregateTime += nowELAPSED - bs.startTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001469 FilterStats fs = inflight.mFilterStats;
1470 fs.nesting--;
1471 if (fs.nesting <= 0) {
1472 fs.nesting = 0;
1473 fs.aggregateTime += nowELAPSED - fs.startTime;
1474 }
1475 } else {
1476 mLog.w("No in-flight alarm for " + pi + " " + intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 }
1478 mBroadcastRefCount--;
1479 if (mBroadcastRefCount == 0) {
1480 mWakeLock.release();
Dianne Hackborn81038902012-11-26 17:04:09 -08001481 if (mInFlight.size() > 0) {
1482 mLog.w("Finished all broadcasts with " + mInFlight.size()
1483 + " remaining inflights");
1484 for (int i=0; i<mInFlight.size(); i++) {
1485 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
1486 }
1487 mInFlight.clear();
1488 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07001489 } else {
1490 // the next of our alarms is now in flight. reattribute the wakelock.
Dianne Hackborn81038902012-11-26 17:04:09 -08001491 if (mInFlight.size() > 0) {
David Christieebe51fc2013-07-26 13:23:29 -07001492 InFlight inFlight = mInFlight.get(0);
1493 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource);
Christopher Tatec4a07d12012-04-06 14:19:13 -07001494 } else {
1495 // should never happen
Dianne Hackborn81038902012-11-26 17:04:09 -08001496 mLog.w("Alarm wakelock still held but sent queue empty");
Christopher Tatec4a07d12012-04-06 14:19:13 -07001497 mWakeLock.setWorkSource(null);
1498 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 }
1500 }
1501 }
1502 }
1503}