blob: 04d6332d34c971d9f11a7da0dd17b4382c8796ca [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;
190 for (int i = 0; i < alarms.size(); i++) {
191 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;
217 for (int i = 0; i < alarms.size(); i++) {
218 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;
244 for (int i = 0; i < alarms.size(); i++) {
245 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);
388 long maxElapsed = (a.whenElapsed == a.maxWhen)
389 ? whenElapsed
390 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
391 setImplLocked(a.type, a.when, whenElapsed, maxElapsed,
David Christieebe51fc2013-07-26 13:23:29 -0700392 a.repeatInterval, a.operation, batch.standalone, doValidate, a.workSource);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700393 }
394 }
395 }
396
Dianne Hackborn81038902012-11-26 17:04:09 -0800397 private static final class InFlight extends Intent {
398 final PendingIntent mPendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700399 final WorkSource mWorkSource;
Dianne Hackborn81038902012-11-26 17:04:09 -0800400 final Pair<String, ComponentName> mTarget;
401 final BroadcastStats mBroadcastStats;
402 final FilterStats mFilterStats;
403
David Christieebe51fc2013-07-26 13:23:29 -0700404 InFlight(AlarmManagerService service, PendingIntent pendingIntent, WorkSource workSource) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800405 mPendingIntent = pendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700406 mWorkSource = workSource;
Dianne Hackborn81038902012-11-26 17:04:09 -0800407 Intent intent = pendingIntent.getIntent();
408 mTarget = intent != null
409 ? new Pair<String, ComponentName>(intent.getAction(), intent.getComponent())
410 : null;
411 mBroadcastStats = service.getStatsLocked(pendingIntent);
412 FilterStats fs = mBroadcastStats.filterStats.get(mTarget);
413 if (fs == null) {
414 fs = new FilterStats(mBroadcastStats, mTarget);
415 mBroadcastStats.filterStats.put(mTarget, fs);
416 }
417 mFilterStats = fs;
418 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800419 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800420
421 private static final class FilterStats {
422 final BroadcastStats mBroadcastStats;
423 final Pair<String, ComponentName> mTarget;
424
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800425 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800426 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800427 int numWakeup;
428 long startTime;
429 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -0800430
431 FilterStats(BroadcastStats broadcastStats, Pair<String, ComponentName> target) {
432 mBroadcastStats = broadcastStats;
433 mTarget = target;
434 }
435 }
436
437 private static final class BroadcastStats {
438 final String mPackageName;
439
440 long aggregateTime;
441 int count;
442 int numWakeup;
443 long startTime;
444 int nesting;
445 final HashMap<Pair<String, ComponentName>, FilterStats> filterStats
446 = new HashMap<Pair<String, ComponentName>, FilterStats>();
447
448 BroadcastStats(String packageName) {
449 mPackageName = packageName;
450 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451 }
452
453 private final HashMap<String, BroadcastStats> mBroadcastStats
454 = new HashMap<String, BroadcastStats>();
455
456 public AlarmManagerService(Context context) {
457 mContext = context;
458 mDescriptor = init();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700459 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800460
461 // We have to set current TimeZone info to kernel
462 // because kernel doesn't keep this after reboot
463 String tz = SystemProperties.get(TIMEZONE_PROPERTY);
464 if (tz != null) {
465 setTimeZone(tz);
466 }
467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800468 PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
469 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
470
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700471 mTimeTickSender = PendingIntent.getBroadcastAsUser(context, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800472 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700473 Intent.FLAG_RECEIVER_REGISTERED_ONLY
474 | Intent.FLAG_RECEIVER_FOREGROUND), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700475 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800476 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
477 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700478 mDateChangeSender = PendingIntent.getBroadcastAsUser(context, 0, intent,
479 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480
481 // now that we have initied the driver schedule the alarm
482 mClockReceiver= new ClockReceiver();
483 mClockReceiver.scheduleTimeTickEvent();
484 mClockReceiver.scheduleDateChangedEvent();
485 mUninstallReceiver = new UninstallReceiver();
486
487 if (mDescriptor != -1) {
488 mWaitThread.start();
489 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800490 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800491 }
492 }
493
494 protected void finalize() throws Throwable {
495 try {
496 close(mDescriptor);
497 } finally {
498 super.finalize();
499 }
500 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700501
502 @Override
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700503 public void set(int type, long triggerAtTime, long windowLength, long interval,
David Christieebe51fc2013-07-26 13:23:29 -0700504 PendingIntent operation, WorkSource workSource) {
505 if (workSource != null) {
506 mContext.enforceCallingPermission(
507 android.Manifest.permission.UPDATE_DEVICE_STATS,
508 "AlarmManager.set");
509 }
510
511 set(type, triggerAtTime, windowLength, interval, operation, false, workSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800512 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700513
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700514 public void set(int type, long triggerAtTime, long windowLength, long interval,
David Christieebe51fc2013-07-26 13:23:29 -0700515 PendingIntent operation, boolean isStandalone, WorkSource workSource) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800516 if (operation == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800517 Slog.w(TAG, "set/setRepeating ignored because there is no intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800518 return;
519 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700520
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700521 // Sanity check the window length. This will catch people mistakenly
522 // trying to pass an end-of-window timestamp rather than a duration.
523 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
524 Slog.w(TAG, "Window length " + windowLength
525 + "ms suspiciously long; limiting to 1 hour");
526 windowLength = AlarmManager.INTERVAL_HOUR;
527 }
528
Christopher Tatee0a22b32013-07-11 14:43:13 -0700529 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
530 throw new IllegalArgumentException("Invalid alarm type " + type);
531 }
532
Christopher Tate5f221e82013-07-30 17:13:15 -0700533 if (triggerAtTime < 0) {
534 final long who = Binder.getCallingUid();
535 final long what = Binder.getCallingPid();
536 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + who
537 + " pid=" + what);
538 triggerAtTime = 0;
539 }
540
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700541 final long nowElapsed = SystemClock.elapsedRealtime();
542 final long triggerElapsed = convertToElapsed(triggerAtTime, type);
543 final long maxElapsed;
544 if (windowLength == AlarmManager.WINDOW_EXACT) {
545 maxElapsed = triggerElapsed;
546 } else if (windowLength < 0) {
547 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
548 } else {
549 maxElapsed = triggerElapsed + windowLength;
550 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700553 if (DEBUG_BATCH) {
554 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700555 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -0700556 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
557 + " interval=" + interval + " standalone=" + isStandalone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800558 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700559 setImplLocked(type, triggerAtTime, triggerElapsed, maxElapsed,
David Christieebe51fc2013-07-26 13:23:29 -0700560 interval, operation, isStandalone, true, workSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800561 }
562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800563
Christopher Tatee0a22b32013-07-11 14:43:13 -0700564 private void setImplLocked(int type, long when, long whenElapsed, long maxWhen, long interval,
David Christieebe51fc2013-07-26 13:23:29 -0700565 PendingIntent operation, boolean isStandalone, boolean doValidate,
566 WorkSource workSource) {
567 Alarm a = new Alarm(type, when, whenElapsed, maxWhen, interval, operation, workSource);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700568 removeLocked(operation);
Christopher Tateb8849c12011-02-08 13:39:01 -0800569
Christopher Tate4cb338d2013-07-26 13:11:31 -0700570 boolean reschedule;
Christopher Tate385e4982013-07-23 18:22:29 -0700571 int whichBatch = (isStandalone) ? -1 : attemptCoalesceLocked(whenElapsed, maxWhen);
572 if (whichBatch < 0) {
573 Batch batch = new Batch(a);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700574 batch.standalone = isStandalone;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700575 reschedule = addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 } else {
Christopher Tate385e4982013-07-23 18:22:29 -0700577 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700578 reschedule = batch.add(a);
Christopher Tate385e4982013-07-23 18:22:29 -0700579 if (reschedule) {
580 // The start time of this batch advanced, so batch ordering may
581 // have just been broken. Move it to where it now belongs.
582 mAlarmBatches.remove(whichBatch);
583 addBatchLocked(mAlarmBatches, batch);
584 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800585 }
586
Christopher Tate4cb338d2013-07-26 13:11:31 -0700587 if (DEBUG_VALIDATE) {
Christopher Tate5f221e82013-07-30 17:13:15 -0700588 if (doValidate && !validateConsistencyLocked()) {
589 Slog.v(TAG, "Tipping-point operation: type=" + type + " when=" + when
590 + " when(hex)=" + Long.toHexString(when)
591 + " whenElapsed=" + whenElapsed + " maxWhen=" + maxWhen
592 + " interval=" + interval + " op=" + operation
593 + " standalone=" + isStandalone);
Christopher Tate4cb338d2013-07-26 13:11:31 -0700594 rebatchAllAlarmsLocked(false);
595 reschedule = true;
596 }
597 }
598
Christopher Tatee0a22b32013-07-11 14:43:13 -0700599 if (reschedule) {
600 rescheduleKernelAlarmsLocked();
601 }
602 }
603
Christopher Tate4cb338d2013-07-26 13:11:31 -0700604 private void logBatchesLocked() {
605 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
606 PrintWriter pw = new PrintWriter(bs);
607 final long nowRTC = System.currentTimeMillis();
608 final long nowELAPSED = SystemClock.elapsedRealtime();
609 final int NZ = mAlarmBatches.size();
610 for (int iz = 0; iz < NZ; iz++) {
611 Batch bz = mAlarmBatches.get(iz);
Christopher Tate5f221e82013-07-30 17:13:15 -0700612 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Christopher Tate4cb338d2013-07-26 13:11:31 -0700613 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC);
Christopher Tate5f221e82013-07-30 17:13:15 -0700614 pw.flush();
Christopher Tate4cb338d2013-07-26 13:11:31 -0700615 Slog.v(TAG, bs.toString());
616 bs.reset();
617 }
618 }
619
620 private boolean validateConsistencyLocked() {
621 if (DEBUG_VALIDATE) {
622 long lastTime = Long.MIN_VALUE;
623 final int N = mAlarmBatches.size();
624 for (int i = 0; i < N; i++) {
625 Batch b = mAlarmBatches.get(i);
626 if (b.start >= lastTime) {
627 // duplicate start times are okay because of standalone batches
628 lastTime = b.start;
629 } else {
630 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
631 logBatchesLocked();
632 return false;
633 }
634 }
635 }
636 return true;
637 }
638
Christopher Tatee0a22b32013-07-11 14:43:13 -0700639 private Batch findFirstWakeupBatchLocked() {
640 final int N = mAlarmBatches.size();
641 for (int i = 0; i < N; i++) {
642 Batch b = mAlarmBatches.get(i);
643 if (b.hasWakeups()) {
644 return b;
645 }
646 }
647 return null;
648 }
649
650 private void rescheduleKernelAlarmsLocked() {
651 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
652 // prior to that which contains no wakeups, we schedule that as well.
Christopher Tate20f170d2013-07-31 13:01:02 -0700653 if (mAlarmBatches.size() > 0) {
654 final Batch firstWakeup = findFirstWakeupBatchLocked();
655 final Batch firstBatch = mAlarmBatches.get(0);
656 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
657 mNextWakeup = firstWakeup.start;
658 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
659 }
660 if (firstBatch != firstWakeup && mNextNonWakeup != firstBatch.start) {
661 mNextNonWakeup = firstBatch.start;
662 setLocked(ELAPSED_REALTIME, firstBatch.start);
663 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700664 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665 }
666
Dan Egnor97e44942010-02-04 20:27:47 -0800667 public void setTime(long millis) {
668 mContext.enforceCallingOrSelfPermission(
669 "android.permission.SET_TIME",
670 "setTime");
671
672 SystemClock.setCurrentTimeMillis(millis);
673 }
674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675 public void setTimeZone(String tz) {
676 mContext.enforceCallingOrSelfPermission(
677 "android.permission.SET_TIME_ZONE",
678 "setTimeZone");
679
Christopher Tate89779822012-08-31 14:40:03 -0700680 long oldId = Binder.clearCallingIdentity();
681 try {
682 if (TextUtils.isEmpty(tz)) return;
683 TimeZone zone = TimeZone.getTimeZone(tz);
684 // Prevent reentrant calls from stepping on each other when writing
685 // the time zone property
686 boolean timeZoneWasChanged = false;
687 synchronized (this) {
688 String current = SystemProperties.get(TIMEZONE_PROPERTY);
689 if (current == null || !current.equals(zone.getID())) {
690 if (localLOGV) {
691 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
692 }
693 timeZoneWasChanged = true;
694 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696
Christopher Tate89779822012-08-31 14:40:03 -0700697 // Update the kernel timezone information
698 // Kernel tracks time offsets as 'minutes west of GMT'
699 int gmtOffset = zone.getOffset(System.currentTimeMillis());
700 setKernelTimezone(mDescriptor, -(gmtOffset / 60000));
701 }
702
703 TimeZone.setDefault(null);
704
705 if (timeZoneWasChanged) {
706 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
707 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
708 intent.putExtra("time-zone", zone.getID());
709 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
710 }
711 } finally {
712 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 }
714 }
715
716 public void remove(PendingIntent operation) {
717 if (operation == null) {
718 return;
719 }
720 synchronized (mLock) {
721 removeLocked(operation);
722 }
723 }
724
725 public void removeLocked(PendingIntent operation) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700726 boolean didRemove = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700727 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
728 Batch b = mAlarmBatches.get(i);
Christopher Tate4cb338d2013-07-26 13:11:31 -0700729 didRemove |= b.remove(operation);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700730 if (b.size() == 0) {
731 mAlarmBatches.remove(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 }
733 }
Christopher Tate4cb338d2013-07-26 13:11:31 -0700734
735 if (didRemove) {
736 if (DEBUG_BATCH) {
737 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
738 }
739 rebatchAllAlarmsLocked(true);
740 rescheduleKernelAlarmsLocked();
741 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800742 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744 public void removeLocked(String packageName) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700745 boolean didRemove = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700746 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
747 Batch b = mAlarmBatches.get(i);
Christopher Tate4cb338d2013-07-26 13:11:31 -0700748 didRemove |= b.remove(packageName);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700749 if (b.size() == 0) {
750 mAlarmBatches.remove(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751 }
752 }
Christopher Tate4cb338d2013-07-26 13:11:31 -0700753
754 if (didRemove) {
755 if (DEBUG_BATCH) {
756 Slog.v(TAG, "remove(package) changed bounds; rebatching");
757 }
758 rebatchAllAlarmsLocked(true);
759 rescheduleKernelAlarmsLocked();
760 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800761 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700762
763 public void removeUserLocked(int userHandle) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700764 boolean didRemove = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700765 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
766 Batch b = mAlarmBatches.get(i);
Christopher Tate4cb338d2013-07-26 13:11:31 -0700767 didRemove |= b.remove(userHandle);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700768 if (b.size() == 0) {
769 mAlarmBatches.remove(i);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700770 }
771 }
Christopher Tate4cb338d2013-07-26 13:11:31 -0700772
773 if (didRemove) {
774 if (DEBUG_BATCH) {
775 Slog.v(TAG, "remove(user) changed bounds; rebatching");
776 }
777 rebatchAllAlarmsLocked(true);
778 rescheduleKernelAlarmsLocked();
779 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700780 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -0800781
Christopher Tatee0a22b32013-07-11 14:43:13 -0700782 public boolean lookForPackageLocked(String packageName) {
783 for (int i = 0; i < mAlarmBatches.size(); i++) {
784 Batch b = mAlarmBatches.get(i);
785 if (b.hasPackage(packageName)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -0800786 return true;
787 }
788 }
789 return false;
790 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791
Christopher Tatee0a22b32013-07-11 14:43:13 -0700792 private void setLocked(int type, long when)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 {
794 if (mDescriptor != -1)
795 {
Jeff Brown11c5f1a2010-03-31 15:29:40 -0700796 // The kernel never triggers alarms with negative wakeup times
797 // so we ensure they are positive.
798 long alarmSeconds, alarmNanoseconds;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700799 if (when < 0) {
Jeff Brown11c5f1a2010-03-31 15:29:40 -0700800 alarmSeconds = 0;
801 alarmNanoseconds = 0;
802 } else {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700803 alarmSeconds = when / 1000;
804 alarmNanoseconds = (when % 1000) * 1000 * 1000;
Jeff Brown11c5f1a2010-03-31 15:29:40 -0700805 }
806
Christopher Tatee0a22b32013-07-11 14:43:13 -0700807 set(mDescriptor, type, alarmSeconds, alarmNanoseconds);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 }
809 else
810 {
811 Message msg = Message.obtain();
812 msg.what = ALARM_EVENT;
813
814 mHandler.removeMessages(ALARM_EVENT);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700815 mHandler.sendMessageAtTime(msg, when);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 }
817 }
818
819 @Override
820 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
821 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
822 != PackageManager.PERMISSION_GRANTED) {
823 pw.println("Permission Denial: can't dump AlarmManager from from pid="
824 + Binder.getCallingPid()
825 + ", uid=" + Binder.getCallingUid());
826 return;
827 }
828
829 synchronized (mLock) {
830 pw.println("Current Alarm Manager state:");
Christopher Tatee0a22b32013-07-11 14:43:13 -0700831 final long nowRTC = System.currentTimeMillis();
832 final long nowELAPSED = SystemClock.elapsedRealtime();
833 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
834
835 pw.print("nowRTC="); pw.print(nowRTC);
836 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
837 pw.print(" nowELAPSED="); pw.println(nowELAPSED);
838
839 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
840 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
841 pw.print("Next alarm: "); pw.print(mNextNonWakeup);
842 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
843 pw.print("Next wakeup: "); pw.print(mNextWakeup);
844 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
845
846 if (mAlarmBatches.size() > 0) {
847 pw.println();
848 pw.print("Pending alarm batches: ");
849 pw.println(mAlarmBatches.size());
850 for (Batch b : mAlarmBatches) {
851 pw.print(b); pw.println(':');
852 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC);
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700853 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800855
856 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700857 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -0800858 pw.println();
859
860 if (mLog.dump(pw, " Recent problems", " ")) {
861 pw.println();
862 }
863
864 final FilterStats[] topFilters = new FilterStats[10];
865 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
866 @Override
867 public int compare(FilterStats lhs, FilterStats rhs) {
868 if (lhs.aggregateTime < rhs.aggregateTime) {
869 return 1;
870 } else if (lhs.aggregateTime > rhs.aggregateTime) {
871 return -1;
872 }
873 return 0;
874 }
875 };
876 int len = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 for (Map.Entry<String, BroadcastStats> be : mBroadcastStats.entrySet()) {
878 BroadcastStats bs = be.getValue();
Dianne Hackborn81038902012-11-26 17:04:09 -0800879 for (Map.Entry<Pair<String, ComponentName>, FilterStats> fe
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 : bs.filterStats.entrySet()) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800881 FilterStats fs = fe.getValue();
882 int pos = len > 0
883 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
884 if (pos < 0) {
885 pos = -pos - 1;
886 }
887 if (pos < topFilters.length) {
888 int copylen = topFilters.length - pos - 1;
889 if (copylen > 0) {
890 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
891 }
892 topFilters[pos] = fs;
893 if (len < topFilters.length) {
894 len++;
895 }
896 }
897 }
898 }
899 if (len > 0) {
900 pw.println(" Top Alarms:");
901 for (int i=0; i<len; i++) {
902 FilterStats fs = topFilters[i];
903 pw.print(" ");
904 if (fs.nesting > 0) pw.print("*ACTIVE* ");
905 TimeUtils.formatDuration(fs.aggregateTime, pw);
906 pw.print(" running, "); pw.print(fs.numWakeup);
907 pw.print(" wakeups, "); pw.print(fs.count);
908 pw.print(" alarms: "); pw.print(fs.mBroadcastStats.mPackageName);
909 pw.println();
910 pw.print(" ");
911 if (fs.mTarget.first != null) {
912 pw.print(" act="); pw.print(fs.mTarget.first);
913 }
914 if (fs.mTarget.second != null) {
915 pw.print(" cmp="); pw.print(fs.mTarget.second.toShortString());
916 }
917 pw.println();
918 }
919 }
920
921 pw.println(" ");
922 pw.println(" Alarm Stats:");
923 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
924 for (Map.Entry<String, BroadcastStats> be : mBroadcastStats.entrySet()) {
925 BroadcastStats bs = be.getValue();
926 pw.print(" ");
927 if (bs.nesting > 0) pw.print("*ACTIVE* ");
928 pw.print(be.getKey());
929 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
930 pw.print(" running, "); pw.print(bs.numWakeup);
931 pw.println(" wakeups:");
932 tmpFilters.clear();
933 for (Map.Entry<Pair<String, ComponentName>, FilterStats> fe
934 : bs.filterStats.entrySet()) {
935 tmpFilters.add(fe.getValue());
936 }
937 Collections.sort(tmpFilters, comparator);
938 for (int i=0; i<tmpFilters.size(); i++) {
939 FilterStats fs = tmpFilters.get(i);
940 pw.print(" ");
941 if (fs.nesting > 0) pw.print("*ACTIVE* ");
942 TimeUtils.formatDuration(fs.aggregateTime, pw);
943 pw.print(" "); pw.print(fs.numWakeup);
944 pw.print(" wakes " ); pw.print(fs.count);
945 pw.print(" alarms:");
946 if (fs.mTarget.first != null) {
947 pw.print(" act="); pw.print(fs.mTarget.first);
948 }
949 if (fs.mTarget.second != null) {
950 pw.print(" cmp="); pw.print(fs.mTarget.second.toShortString());
951 }
952 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800953 }
954 }
Christopher Tate18a75f12013-07-01 18:18:59 -0700955
956 if (WAKEUP_STATS) {
957 pw.println();
958 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -0700959 long last = -1;
960 for (WakeupEvent event : mRecentWakeups) {
961 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
962 pw.print('|');
963 if (last < 0) {
964 pw.print('0');
965 } else {
966 pw.print(event.when - last);
967 }
968 last = event.when;
969 pw.print('|'); pw.print(event.uid);
970 pw.print('|'); pw.print(event.action);
971 pw.println();
972 }
973 pw.println();
974 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 }
976 }
977
Dianne Hackborn043fcd92010-10-06 14:27:34 -0700978 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
979 String prefix, String label, long now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 for (int i=list.size()-1; i>=0; i--) {
981 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700982 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
983 pw.print(": "); pw.println(a);
Dianne Hackborn043fcd92010-10-06 14:27:34 -0700984 a.dump(pw, prefix + " ", now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 }
986 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700987
988 private static final String labelForType(int type) {
989 switch (type) {
990 case RTC: return "RTC";
991 case RTC_WAKEUP : return "RTC_WAKEUP";
992 case ELAPSED_REALTIME : return "ELAPSED";
993 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
994 default:
995 break;
996 }
997 return "--unknown--";
998 }
999
1000 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
1001 String prefix, long nowELAPSED, long nowRTC) {
1002 for (int i=list.size()-1; i>=0; i--) {
1003 Alarm a = list.get(i);
1004 final String label = labelForType(a.type);
1005 long now = (a.type <= RTC) ? nowRTC : nowELAPSED;
1006 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1007 pw.print(": "); pw.println(a);
1008 a.dump(pw, prefix + " ", now);
1009 }
1010 }
1011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 private native int init();
1013 private native void close(int fd);
Jeff Brown11c5f1a2010-03-31 15:29:40 -07001014 private native void set(int fd, int type, long seconds, long nanoseconds);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 private native int waitForAlarm(int fd);
1016 private native int setKernelTimezone(int fd, int minuteswest);
1017
Christopher Tatee0a22b32013-07-11 14:43:13 -07001018 private void triggerAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED, long nowRTC) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001019 // batches are temporally sorted, so we need only pull from the
1020 // start of the list until we either empty it or hit a batch
1021 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07001022 while (mAlarmBatches.size() > 0) {
1023 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001024 if (batch.start > nowELAPSED) {
1025 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026 break;
1027 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028
Christopher Tatee0a22b32013-07-11 14:43:13 -07001029 // We will (re)schedule some alarms now; don't let that interfere
1030 // with delivery of this current batch
1031 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001032
Christopher Tatee0a22b32013-07-11 14:43:13 -07001033 final int N = batch.size();
1034 for (int i = 0; i < N; i++) {
1035 Alarm alarm = batch.get(i);
1036 alarm.count = 1;
1037 triggerList.add(alarm);
1038
1039 // Recurring alarms may have passed several alarm intervals while the
1040 // phone was asleep or off, so pass a trigger count when sending them.
1041 if (alarm.repeatInterval > 0) {
1042 // this adjustment will be zero if we're late by
1043 // less than one full repeat interval
1044 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
1045
1046 // Also schedule its next recurrence
1047 final long delta = alarm.count * alarm.repeatInterval;
1048 final long nextElapsed = alarm.whenElapsed + delta;
1049 setImplLocked(alarm.type, alarm.when + delta, nextElapsed,
1050 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
David Christieebe51fc2013-07-26 13:23:29 -07001051 alarm.repeatInterval, alarm.operation, batch.standalone, true,
1052 alarm.workSource);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001053 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054
Dianne Hackborn390517b2013-05-30 15:03:32 -07001055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001058
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 /**
1060 * This Comparator sorts Alarms into increasing time order.
1061 */
1062 public static class IncreasingTimeOrder implements Comparator<Alarm> {
1063 public int compare(Alarm a1, Alarm a2) {
1064 long when1 = a1.when;
1065 long when2 = a2.when;
1066 if (when1 - when2 > 0) {
1067 return 1;
1068 }
1069 if (when1 - when2 < 0) {
1070 return -1;
1071 }
1072 return 0;
1073 }
1074 }
1075
1076 private static class Alarm {
1077 public int type;
1078 public int count;
1079 public long when;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001080 public long whenElapsed; // 'when' in the elapsed time base
1081 public long maxWhen; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 public long repeatInterval;
1083 public PendingIntent operation;
David Christieebe51fc2013-07-26 13:23:29 -07001084 public WorkSource workSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085
Christopher Tatee0a22b32013-07-11 14:43:13 -07001086 public Alarm(int _type, long _when, long _whenElapsed, long _maxWhen,
David Christieebe51fc2013-07-26 13:23:29 -07001087 long _interval, PendingIntent _op, WorkSource _ws) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001088 type = _type;
1089 when = _when;
1090 whenElapsed = _whenElapsed;
1091 maxWhen = _maxWhen;
1092 repeatInterval = _interval;
1093 operation = _op;
David Christieebe51fc2013-07-26 13:23:29 -07001094 workSource = _ws;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 @Override
1098 public String toString()
1099 {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001100 StringBuilder sb = new StringBuilder(128);
1101 sb.append("Alarm{");
1102 sb.append(Integer.toHexString(System.identityHashCode(this)));
1103 sb.append(" type ");
1104 sb.append(type);
1105 sb.append(" ");
1106 sb.append(operation.getTargetPackage());
1107 sb.append('}');
1108 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 }
1110
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001111 public void dump(PrintWriter pw, String prefix, long now) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001112 pw.print(prefix); pw.print("type="); pw.print(type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001113 pw.print(" whenElapsed="); pw.print(whenElapsed);
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001114 pw.print(" when="); TimeUtils.formatDuration(when, now, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001115 pw.print(" repeatInterval="); pw.print(repeatInterval);
1116 pw.print(" count="); pw.println(count);
1117 pw.print(prefix); pw.print("operation="); pw.println(operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 }
1119 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001120
Christopher Tatee0a22b32013-07-11 14:43:13 -07001121 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
1122 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07001123 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
1124 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001125 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07001126 break;
1127 }
1128
Christopher Tatee0a22b32013-07-11 14:43:13 -07001129 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07001130 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
1131 Alarm a = b.alarms.get(nextAlarm);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001132 WakeupEvent e = new WakeupEvent(nowRTC,
1133 a.operation.getCreatorUid(),
1134 a.operation.getIntent().getAction());
1135 mRecentWakeups.add(e);
1136 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001137 }
1138 }
1139
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 private class AlarmThread extends Thread
1141 {
1142 public AlarmThread()
1143 {
1144 super("AlarmManager");
1145 }
1146
1147 public void run()
1148 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07001149 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
1150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 while (true)
1152 {
1153 int result = waitForAlarm(mDescriptor);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001154
1155 triggerList.clear();
1156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157 if ((result & TIME_CHANGED_MASK) != 0) {
Christopher Tate385e4982013-07-23 18:22:29 -07001158 if (DEBUG_BATCH) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001159 Slog.v(TAG, "Time changed notification from kernel; rebatching");
Christopher Tate385e4982013-07-23 18:22:29 -07001160 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 remove(mTimeTickSender);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001162 rebatchAllAlarms();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 mClockReceiver.scheduleTimeTickEvent();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001164 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
Dianne Hackborn89ba6752011-01-23 16:51:16 -08001165 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1166 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001167 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 }
1169
1170 synchronized (mLock) {
1171 final long nowRTC = System.currentTimeMillis();
1172 final long nowELAPSED = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001173 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 TAG, "Checking for alarms... rtc=" + nowRTC
1175 + ", elapsed=" + nowELAPSED);
1176
Christopher Tate18a75f12013-07-01 18:18:59 -07001177 if (WAKEUP_STATS) {
1178 if ((result & IS_WAKEUP_MASK) != 0) {
1179 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
1180 int n = 0;
1181 for (WakeupEvent event : mRecentWakeups) {
1182 if (event.when > newEarliest) break;
1183 n++; // number of now-stale entries at the list head
1184 }
1185 for (int i = 0; i < n; i++) {
1186 mRecentWakeups.remove();
1187 }
1188
Christopher Tatee0a22b32013-07-11 14:43:13 -07001189 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Christopher Tate18a75f12013-07-01 18:18:59 -07001190 }
1191 }
1192
Christopher Tatee0a22b32013-07-11 14:43:13 -07001193 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
1194 rescheduleKernelAlarmsLocked();
1195
1196 // now deliver the alarm intents
Dianne Hackborn390517b2013-05-30 15:03:32 -07001197 for (int i=0; i<triggerList.size(); i++) {
1198 Alarm alarm = triggerList.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001200 if (localLOGV) Slog.v(TAG, "sending alarm " + alarm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001201 alarm.operation.send(mContext, 0,
1202 mBackgroundIntent.putExtra(
1203 Intent.EXTRA_ALARM_COUNT, alarm.count),
1204 mResultReceiver, mHandler);
1205
Christopher Tatec4a07d12012-04-06 14:19:13 -07001206 // we have an active broadcast so stay awake.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001207 if (mBroadcastRefCount == 0) {
David Christieebe51fc2013-07-26 13:23:29 -07001208 setWakelockWorkSource(alarm.operation, alarm.workSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 mWakeLock.acquire();
1210 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001211 final InFlight inflight = new InFlight(AlarmManagerService.this,
David Christieebe51fc2013-07-26 13:23:29 -07001212 alarm.operation, alarm.workSource);
Dianne Hackborn81038902012-11-26 17:04:09 -08001213 mInFlight.add(inflight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 mBroadcastRefCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08001215
1216 final BroadcastStats bs = inflight.mBroadcastStats;
1217 bs.count++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 if (bs.nesting == 0) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001219 bs.nesting = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001220 bs.startTime = nowELAPSED;
1221 } else {
1222 bs.nesting++;
1223 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001224 final FilterStats fs = inflight.mFilterStats;
1225 fs.count++;
1226 if (fs.nesting == 0) {
1227 fs.nesting = 1;
1228 fs.startTime = nowELAPSED;
1229 } else {
1230 fs.nesting++;
1231 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001232 if (alarm.type == ELAPSED_REALTIME_WAKEUP
1233 || alarm.type == RTC_WAKEUP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234 bs.numWakeup++;
Dianne Hackborn81038902012-11-26 17:04:09 -08001235 fs.numWakeup++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001236 ActivityManagerNative.noteWakeupAlarm(
1237 alarm.operation);
1238 }
1239 } catch (PendingIntent.CanceledException e) {
1240 if (alarm.repeatInterval > 0) {
1241 // This IntentSender is no longer valid, but this
1242 // is a repeating alarm, so toss the hoser.
1243 remove(alarm.operation);
1244 }
1245 } catch (RuntimeException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001246 Slog.w(TAG, "Failure sending alarm.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001247 }
1248 }
1249 }
1250 }
1251 }
1252 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07001253
David Christieebe51fc2013-07-26 13:23:29 -07001254 /**
1255 * Attribute blame for a WakeLock.
1256 * @param pi PendingIntent to attribute blame to if ws is null.
1257 * @param ws WorkSource to attribute blame.
1258 */
1259 void setWakelockWorkSource(PendingIntent pi, WorkSource ws) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07001260 try {
David Christieebe51fc2013-07-26 13:23:29 -07001261 if (ws != null) {
1262 mWakeLock.setWorkSource(ws);
1263 return;
1264 }
1265
Christopher Tatec4a07d12012-04-06 14:19:13 -07001266 final int uid = ActivityManagerNative.getDefault()
1267 .getUidForIntentSender(pi.getTarget());
1268 if (uid >= 0) {
1269 mWakeLock.setWorkSource(new WorkSource(uid));
1270 return;
1271 }
1272 } catch (Exception e) {
1273 }
1274
1275 // Something went wrong; fall back to attributing the lock to the OS
1276 mWakeLock.setWorkSource(null);
1277 }
1278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 private class AlarmHandler extends Handler {
1280 public static final int ALARM_EVENT = 1;
1281 public static final int MINUTE_CHANGE_EVENT = 2;
1282 public static final int DATE_CHANGE_EVENT = 3;
1283
1284 public AlarmHandler() {
1285 }
1286
1287 public void handleMessage(Message msg) {
1288 if (msg.what == ALARM_EVENT) {
1289 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
1290 synchronized (mLock) {
1291 final long nowRTC = System.currentTimeMillis();
Christopher Tatee0a22b32013-07-11 14:43:13 -07001292 final long nowELAPSED = SystemClock.elapsedRealtime();
1293 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 }
1295
1296 // now trigger the alarms without the lock held
Dianne Hackborn390517b2013-05-30 15:03:32 -07001297 for (int i=0; i<triggerList.size(); i++) {
1298 Alarm alarm = triggerList.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 try {
1300 alarm.operation.send();
1301 } catch (PendingIntent.CanceledException e) {
1302 if (alarm.repeatInterval > 0) {
1303 // This IntentSender is no longer valid, but this
1304 // is a repeating alarm, so toss the hoser.
1305 remove(alarm.operation);
1306 }
1307 }
1308 }
1309 }
1310 }
1311 }
1312
1313 class ClockReceiver extends BroadcastReceiver {
1314 public ClockReceiver() {
1315 IntentFilter filter = new IntentFilter();
1316 filter.addAction(Intent.ACTION_TIME_TICK);
1317 filter.addAction(Intent.ACTION_DATE_CHANGED);
1318 mContext.registerReceiver(this, filter);
1319 }
1320
1321 @Override
1322 public void onReceive(Context context, Intent intent) {
1323 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001324 if (DEBUG_BATCH) {
1325 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
1326 }
1327 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
1329 // Since the kernel does not keep track of DST, we need to
1330 // reset the TZ information at the beginning of each day
1331 // based off of the current Zone gmt offset + userspace tracked
1332 // daylight savings information.
1333 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02001334 int gmtOffset = zone.getOffset(System.currentTimeMillis());
1335 setKernelTimezone(mDescriptor, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07001336 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337 }
1338 }
1339
1340 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07001341 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09001342 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07001343
1344 // Schedule this event for the amount of time that it would take to get to
1345 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09001346 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07001347
David Christieebe51fc2013-07-26 13:23:29 -07001348 final WorkSource workSource = null; // Let system take blame for time tick events.
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001349 set(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
David Christieebe51fc2013-07-26 13:23:29 -07001350 0, mTimeTickSender, true, workSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351 }
Christopher Tate385e4982013-07-23 18:22:29 -07001352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001353 public void scheduleDateChangedEvent() {
1354 Calendar calendar = Calendar.getInstance();
1355 calendar.setTimeInMillis(System.currentTimeMillis());
1356 calendar.set(Calendar.HOUR, 0);
1357 calendar.set(Calendar.MINUTE, 0);
1358 calendar.set(Calendar.SECOND, 0);
1359 calendar.set(Calendar.MILLISECOND, 0);
1360 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07001361
1362 final WorkSource workSource = null; // Let system take blame for date change events.
1363 set(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, true, workSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 }
1365 }
1366
1367 class UninstallReceiver extends BroadcastReceiver {
1368 public UninstallReceiver() {
1369 IntentFilter filter = new IntentFilter();
1370 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1371 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001372 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 filter.addDataScheme("package");
1374 mContext.registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001375 // Register for events related to sdcard installation.
1376 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001377 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001378 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001379 mContext.registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380 }
1381
1382 @Override
1383 public void onReceive(Context context, Intent intent) {
1384 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001385 String action = intent.getAction();
1386 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001387 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
1388 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
1389 for (String packageName : pkgList) {
1390 if (lookForPackageLocked(packageName)) {
1391 setResultCode(Activity.RESULT_OK);
1392 return;
1393 }
1394 }
1395 return;
1396 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001397 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001398 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
1399 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
1400 if (userHandle >= 0) {
1401 removeUserLocked(userHandle);
1402 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001403 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08001404 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
1405 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
1406 // This package is being updated; don't kill its alarms.
1407 return;
1408 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001409 Uri data = intent.getData();
1410 if (data != null) {
1411 String pkg = data.getSchemeSpecificPart();
1412 if (pkg != null) {
1413 pkgList = new String[]{pkg};
1414 }
1415 }
1416 }
1417 if (pkgList != null && (pkgList.length > 0)) {
1418 for (String pkg : pkgList) {
1419 removeLocked(pkg);
1420 mBroadcastStats.remove(pkg);
1421 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422 }
1423 }
1424 }
1425 }
1426
1427 private final BroadcastStats getStatsLocked(PendingIntent pi) {
1428 String pkg = pi.getTargetPackage();
1429 BroadcastStats bs = mBroadcastStats.get(pkg);
1430 if (bs == null) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001431 bs = new BroadcastStats(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001432 mBroadcastStats.put(pkg, bs);
1433 }
1434 return bs;
1435 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 class ResultReceiver implements PendingIntent.OnFinished {
1438 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
1439 String resultData, Bundle resultExtras) {
1440 synchronized (mLock) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001441 InFlight inflight = null;
1442 for (int i=0; i<mInFlight.size(); i++) {
1443 if (mInFlight.get(i).mPendingIntent == pi) {
1444 inflight = mInFlight.remove(i);
1445 break;
1446 }
1447 }
1448 if (inflight != null) {
1449 final long nowELAPSED = SystemClock.elapsedRealtime();
1450 BroadcastStats bs = inflight.mBroadcastStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451 bs.nesting--;
1452 if (bs.nesting <= 0) {
1453 bs.nesting = 0;
Dianne Hackborn81038902012-11-26 17:04:09 -08001454 bs.aggregateTime += nowELAPSED - bs.startTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001456 FilterStats fs = inflight.mFilterStats;
1457 fs.nesting--;
1458 if (fs.nesting <= 0) {
1459 fs.nesting = 0;
1460 fs.aggregateTime += nowELAPSED - fs.startTime;
1461 }
1462 } else {
1463 mLog.w("No in-flight alarm for " + pi + " " + intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 }
1465 mBroadcastRefCount--;
1466 if (mBroadcastRefCount == 0) {
1467 mWakeLock.release();
Dianne Hackborn81038902012-11-26 17:04:09 -08001468 if (mInFlight.size() > 0) {
1469 mLog.w("Finished all broadcasts with " + mInFlight.size()
1470 + " remaining inflights");
1471 for (int i=0; i<mInFlight.size(); i++) {
1472 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
1473 }
1474 mInFlight.clear();
1475 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07001476 } else {
1477 // the next of our alarms is now in flight. reattribute the wakelock.
Dianne Hackborn81038902012-11-26 17:04:09 -08001478 if (mInFlight.size() > 0) {
David Christieebe51fc2013-07-26 13:23:29 -07001479 InFlight inFlight = mInFlight.get(0);
1480 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource);
Christopher Tatec4a07d12012-04-06 14:19:13 -07001481 } else {
1482 // should never happen
Dianne Hackborn81038902012-11-26 17:04:09 -08001483 mLog.w("Alarm wakelock still held but sent queue empty");
Christopher Tatec4a07d12012-04-06 14:19:13 -07001484 mWakeLock.setWorkSource(null);
1485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 }
1487 }
1488 }
1489 }
1490}