blob: 3cdf170494d4e7585caa6556102d451193603747 [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;
Adam Lesinski182f73f2013-12-05 16:48:06 -080034import android.os.IBinder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.os.Message;
36import android.os.PowerManager;
37import android.os.SystemClock;
38import android.os.SystemProperties;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070039import android.os.UserHandle;
Christopher Tatec4a07d12012-04-06 14:19:13 -070040import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.text.TextUtils;
Dianne Hackborn81038902012-11-26 17:04:09 -080042import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -080043import android.util.Slog;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070044import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045
Christopher Tate4cb338d2013-07-26 13:11:31 -070046import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import java.io.FileDescriptor;
48import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070049import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -080051import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import java.util.Calendar;
53import java.util.Collections;
54import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -050055import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -070057import java.util.LinkedList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import java.util.Map;
59import java.util.TimeZone;
60
Christopher Tatee0a22b32013-07-11 14:43:13 -070061import static android.app.AlarmManager.RTC_WAKEUP;
62import static android.app.AlarmManager.RTC;
63import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
64import static android.app.AlarmManager.ELAPSED_REALTIME;
65
Dianne Hackborn81038902012-11-26 17:04:09 -080066import com.android.internal.util.LocalLog;
67
Adam Lesinski182f73f2013-12-05 16:48:06 -080068class AlarmManagerService extends SystemService {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069 // The threshold for how long an alarm can be late before we print a
70 // warning message. The time duration is in milliseconds.
71 private static final long LATE_ALARM_THRESHOLD = 10 * 1000;
Christopher Tatee0a22b32013-07-11 14:43:13 -070072
73 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
74 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -080075 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -070076 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -080077 static final int TIME_CHANGED_MASK = 1 << 16;
78 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -080079
Christopher Tatee0a22b32013-07-11 14:43:13 -070080 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -080081 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -080082
Adam Lesinski182f73f2013-12-05 16:48:06 -080083 static final String TAG = "AlarmManager";
84 static final String ClockReceiver_TAG = "ClockReceiver";
85 static final boolean localLOGV = false;
86 static final boolean DEBUG_BATCH = localLOGV || false;
87 static final boolean DEBUG_VALIDATE = localLOGV || false;
88 static final int ALARM_EVENT = 1;
89 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090
Adam Lesinski182f73f2013-12-05 16:48:06 -080091 static final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -080093 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094
Adam Lesinski182f73f2013-12-05 16:48:06 -080095 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -070096
Adam Lesinski182f73f2013-12-05 16:48:06 -080097 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -080098
Adam Lesinski182f73f2013-12-05 16:48:06 -080099 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800100
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800101 long mNativeData;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700102 private long mNextWakeup;
103 private long mNextNonWakeup;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800104 int mBroadcastRefCount = 0;
105 PowerManager.WakeLock mWakeLock;
106 ArrayList<InFlight> mInFlight = new ArrayList<InFlight>();
107 final AlarmHandler mHandler = new AlarmHandler();
108 ClockReceiver mClockReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109 private UninstallReceiver mUninstallReceiver;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800110 final ResultReceiver mResultReceiver = new ResultReceiver();
111 PendingIntent mTimeTickSender;
112 PendingIntent mDateChangeSender;
Dianne Hackborn81038902012-11-26 17:04:09 -0800113
Christopher Tate18a75f12013-07-01 18:18:59 -0700114 class WakeupEvent {
115 public long when;
116 public int uid;
117 public String action;
118
119 public WakeupEvent(long theTime, int theUid, String theAction) {
120 when = theTime;
121 uid = theUid;
122 action = theAction;
123 }
124 }
125
Adam Lesinski182f73f2013-12-05 16:48:06 -0800126 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
127 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700128
Christopher Tatee0a22b32013-07-11 14:43:13 -0700129 static final class Batch {
130 long start; // These endpoints are always in ELAPSED
131 long end;
132 boolean standalone; // certain "batches" don't participate in coalescing
133
134 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
135
136 Batch() {
137 start = 0;
138 end = Long.MAX_VALUE;
139 }
140
141 Batch(Alarm seed) {
142 start = seed.whenElapsed;
143 end = seed.maxWhen;
144 alarms.add(seed);
145 }
146
147 int size() {
148 return alarms.size();
149 }
150
151 Alarm get(int index) {
152 return alarms.get(index);
153 }
154
155 boolean canHold(long whenElapsed, long maxWhen) {
156 return (end >= whenElapsed) && (start <= maxWhen);
157 }
158
159 boolean add(Alarm alarm) {
160 boolean newStart = false;
161 // narrows the batch if necessary; presumes that canHold(alarm) is true
162 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
163 if (index < 0) {
164 index = 0 - index - 1;
165 }
166 alarms.add(index, alarm);
167 if (DEBUG_BATCH) {
168 Slog.v(TAG, "Adding " + alarm + " to " + this);
169 }
170 if (alarm.whenElapsed > start) {
171 start = alarm.whenElapsed;
172 newStart = true;
173 }
174 if (alarm.maxWhen < end) {
175 end = alarm.maxWhen;
176 }
177
178 if (DEBUG_BATCH) {
179 Slog.v(TAG, " => now " + this);
180 }
181 return newStart;
182 }
183
184 boolean remove(final PendingIntent operation) {
185 boolean didRemove = false;
186 long newStart = 0; // recalculate endpoints as we go
187 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700188 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700189 Alarm alarm = alarms.get(i);
190 if (alarm.operation.equals(operation)) {
191 alarms.remove(i);
192 didRemove = true;
193 } else {
194 if (alarm.whenElapsed > newStart) {
195 newStart = alarm.whenElapsed;
196 }
197 if (alarm.maxWhen < newEnd) {
198 newEnd = alarm.maxWhen;
199 }
200 i++;
201 }
202 }
203 if (didRemove) {
204 // commit the new batch bounds
205 start = newStart;
206 end = newEnd;
207 }
208 return didRemove;
209 }
210
211 boolean remove(final String packageName) {
212 boolean didRemove = false;
213 long newStart = 0; // recalculate endpoints as we go
214 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700215 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700216 Alarm alarm = alarms.get(i);
217 if (alarm.operation.getTargetPackage().equals(packageName)) {
218 alarms.remove(i);
219 didRemove = true;
220 } else {
221 if (alarm.whenElapsed > newStart) {
222 newStart = alarm.whenElapsed;
223 }
224 if (alarm.maxWhen < newEnd) {
225 newEnd = alarm.maxWhen;
226 }
227 i++;
228 }
229 }
230 if (didRemove) {
231 // commit the new batch bounds
232 start = newStart;
233 end = newEnd;
234 }
235 return didRemove;
236 }
237
238 boolean remove(final int userHandle) {
239 boolean didRemove = false;
240 long newStart = 0; // recalculate endpoints as we go
241 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700242 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700243 Alarm alarm = alarms.get(i);
244 if (UserHandle.getUserId(alarm.operation.getCreatorUid()) == userHandle) {
245 alarms.remove(i);
246 didRemove = true;
247 } else {
248 if (alarm.whenElapsed > newStart) {
249 newStart = alarm.whenElapsed;
250 }
251 if (alarm.maxWhen < newEnd) {
252 newEnd = alarm.maxWhen;
253 }
254 i++;
255 }
256 }
257 if (didRemove) {
258 // commit the new batch bounds
259 start = newStart;
260 end = newEnd;
261 }
262 return didRemove;
263 }
264
265 boolean hasPackage(final String packageName) {
266 final int N = alarms.size();
267 for (int i = 0; i < N; i++) {
268 Alarm a = alarms.get(i);
269 if (a.operation.getTargetPackage().equals(packageName)) {
270 return true;
271 }
272 }
273 return false;
274 }
275
276 boolean hasWakeups() {
277 final int N = alarms.size();
278 for (int i = 0; i < N; i++) {
279 Alarm a = alarms.get(i);
280 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
281 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
282 return true;
283 }
284 }
285 return false;
286 }
287
288 @Override
289 public String toString() {
290 StringBuilder b = new StringBuilder(40);
291 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
292 b.append(" num="); b.append(size());
293 b.append(" start="); b.append(start);
294 b.append(" end="); b.append(end);
295 if (standalone) {
296 b.append(" STANDALONE");
297 }
298 b.append('}');
299 return b.toString();
300 }
301 }
302
303 static class BatchTimeOrder implements Comparator<Batch> {
304 public int compare(Batch b1, Batch b2) {
305 long when1 = b1.start;
306 long when2 = b2.start;
307 if (when1 - when2 > 0) {
308 return 1;
309 }
310 if (when1 - when2 < 0) {
311 return -1;
312 }
313 return 0;
314 }
315 }
316
317 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800318 static final long MIN_FUZZABLE_INTERVAL = 10000;
319 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
320 final ArrayList<Batch> mAlarmBatches = new ArrayList<Batch>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700321
322 static long convertToElapsed(long when, int type) {
323 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
324 if (isRtc) {
325 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
326 }
327 return when;
328 }
329
330 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
331 // calculate the end of our nominal delivery window for the alarm.
332 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
333 // Current heuristic: batchable window is 75% of either the recurrence interval
334 // [for a periodic alarm] or of the time from now to the desired delivery time,
335 // with a minimum delay/interval of 10 seconds, under which we will simply not
336 // defer the alarm.
337 long futurity = (interval == 0)
338 ? (triggerAtTime - now)
339 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700340 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700341 futurity = 0;
342 }
343 return triggerAtTime + (long)(.75 * futurity);
344 }
345
346 // returns true if the batch was added at the head
347 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
348 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
349 if (index < 0) {
350 index = 0 - index - 1;
351 }
352 list.add(index, newBatch);
353 return (index == 0);
354 }
355
Christopher Tate385e4982013-07-23 18:22:29 -0700356 // Return the index of the matching batch, or -1 if none found.
357 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700358 final int N = mAlarmBatches.size();
359 for (int i = 0; i < N; i++) {
360 Batch b = mAlarmBatches.get(i);
361 if (!b.standalone && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700362 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700363 }
364 }
Christopher Tate385e4982013-07-23 18:22:29 -0700365 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700366 }
367
368 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
369 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700370 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700371 rebatchAllAlarmsLocked(true);
372 }
373 }
374
375 void rebatchAllAlarmsLocked(boolean doValidate) {
376 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
377 mAlarmBatches.clear();
378 final long nowElapsed = SystemClock.elapsedRealtime();
379 final int oldBatches = oldSet.size();
380 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
381 Batch batch = oldSet.get(batchNum);
382 final int N = batch.size();
383 for (int i = 0; i < N; i++) {
384 Alarm a = batch.get(i);
385 long whenElapsed = convertToElapsed(a.when, a.type);
Christopher Tate3e04b472013-10-21 17:51:31 -0700386 final long maxElapsed;
387 if (a.whenElapsed == a.maxWhen) {
388 // Exact
389 maxElapsed = whenElapsed;
390 } else {
391 // Not exact. Preserve any explicit window, otherwise recalculate
392 // the window based on the alarm's new futurity. Note that this
393 // reflects a policy of preferring timely to deferred delivery.
394 maxElapsed = (a.windowLength > 0)
395 ? (whenElapsed + a.windowLength)
396 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
397 }
398 setImplLocked(a.type, a.when, whenElapsed, a.windowLength, maxElapsed,
David Christieebe51fc2013-07-26 13:23:29 -0700399 a.repeatInterval, a.operation, batch.standalone, doValidate, a.workSource);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700400 }
401 }
402 }
403
Adam Lesinski182f73f2013-12-05 16:48:06 -0800404 static final class InFlight extends Intent {
Dianne Hackborn81038902012-11-26 17:04:09 -0800405 final PendingIntent mPendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700406 final WorkSource mWorkSource;
Dianne Hackborn81038902012-11-26 17:04:09 -0800407 final Pair<String, ComponentName> mTarget;
408 final BroadcastStats mBroadcastStats;
409 final FilterStats mFilterStats;
410
David Christieebe51fc2013-07-26 13:23:29 -0700411 InFlight(AlarmManagerService service, PendingIntent pendingIntent, WorkSource workSource) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800412 mPendingIntent = pendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700413 mWorkSource = workSource;
Dianne Hackborn81038902012-11-26 17:04:09 -0800414 Intent intent = pendingIntent.getIntent();
415 mTarget = intent != null
416 ? new Pair<String, ComponentName>(intent.getAction(), intent.getComponent())
417 : null;
418 mBroadcastStats = service.getStatsLocked(pendingIntent);
419 FilterStats fs = mBroadcastStats.filterStats.get(mTarget);
420 if (fs == null) {
421 fs = new FilterStats(mBroadcastStats, mTarget);
422 mBroadcastStats.filterStats.put(mTarget, fs);
423 }
424 mFilterStats = fs;
425 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800426 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800427
Adam Lesinski182f73f2013-12-05 16:48:06 -0800428 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -0800429 final BroadcastStats mBroadcastStats;
430 final Pair<String, ComponentName> mTarget;
431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800432 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800433 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800434 int numWakeup;
435 long startTime;
436 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -0800437
438 FilterStats(BroadcastStats broadcastStats, Pair<String, ComponentName> target) {
439 mBroadcastStats = broadcastStats;
440 mTarget = target;
441 }
442 }
443
Adam Lesinski182f73f2013-12-05 16:48:06 -0800444 static final class BroadcastStats {
Dianne Hackborn81038902012-11-26 17:04:09 -0800445 final String mPackageName;
446
447 long aggregateTime;
448 int count;
449 int numWakeup;
450 long startTime;
451 int nesting;
452 final HashMap<Pair<String, ComponentName>, FilterStats> filterStats
453 = new HashMap<Pair<String, ComponentName>, FilterStats>();
454
455 BroadcastStats(String packageName) {
456 mPackageName = packageName;
457 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800458 }
459
Adam Lesinski182f73f2013-12-05 16:48:06 -0800460 final HashMap<String, BroadcastStats> mBroadcastStats
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800461 = new HashMap<String, BroadcastStats>();
462
Adam Lesinski182f73f2013-12-05 16:48:06 -0800463 @Override
464 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800465 mNativeData = init();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700466 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800467
468 // We have to set current TimeZone info to kernel
469 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -0800470 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800471
Adam Lesinski182f73f2013-12-05 16:48:06 -0800472 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800473 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
474
Adam Lesinski182f73f2013-12-05 16:48:06 -0800475 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800476 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700477 Intent.FLAG_RECEIVER_REGISTERED_ONLY
478 | Intent.FLAG_RECEIVER_FOREGROUND), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700479 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800480 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
481 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800482 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700483 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484
485 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -0800486 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800487 mClockReceiver.scheduleTimeTickEvent();
488 mClockReceiver.scheduleDateChangedEvent();
489 mUninstallReceiver = new UninstallReceiver();
490
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800491 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800492 AlarmThread waitThread = new AlarmThread();
493 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800495 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800496 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800497
498 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800500
501 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800502 protected void finalize() throws Throwable {
503 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800504 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505 } finally {
506 super.finalize();
507 }
508 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700509
Adam Lesinski182f73f2013-12-05 16:48:06 -0800510 void setTimeZoneImpl(String tz) {
511 if (TextUtils.isEmpty(tz)) {
512 return;
David Christieebe51fc2013-07-26 13:23:29 -0700513 }
514
Adam Lesinski182f73f2013-12-05 16:48:06 -0800515 TimeZone zone = TimeZone.getTimeZone(tz);
516 // Prevent reentrant calls from stepping on each other when writing
517 // the time zone property
518 boolean timeZoneWasChanged = false;
519 synchronized (this) {
520 String current = SystemProperties.get(TIMEZONE_PROPERTY);
521 if (current == null || !current.equals(zone.getID())) {
522 if (localLOGV) {
523 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
524 }
525 timeZoneWasChanged = true;
526 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
527 }
528
529 // Update the kernel timezone information
530 // Kernel tracks time offsets as 'minutes west of GMT'
531 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800532 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -0800533 }
534
535 TimeZone.setDefault(null);
536
537 if (timeZoneWasChanged) {
538 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
539 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
540 intent.putExtra("time-zone", zone.getID());
541 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
542 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800543 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700544
Adam Lesinski182f73f2013-12-05 16:48:06 -0800545 void removeImpl(PendingIntent operation) {
546 if (operation == null) {
547 return;
548 }
549 synchronized (mLock) {
550 removeLocked(operation);
551 }
552 }
553
554 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
David Christieebe51fc2013-07-26 13:23:29 -0700555 PendingIntent operation, boolean isStandalone, WorkSource workSource) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800556 if (operation == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800557 Slog.w(TAG, "set/setRepeating ignored because there is no intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800558 return;
559 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700560
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700561 // Sanity check the window length. This will catch people mistakenly
562 // trying to pass an end-of-window timestamp rather than a duration.
563 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
564 Slog.w(TAG, "Window length " + windowLength
565 + "ms suspiciously long; limiting to 1 hour");
566 windowLength = AlarmManager.INTERVAL_HOUR;
567 }
568
Christopher Tatee0a22b32013-07-11 14:43:13 -0700569 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
570 throw new IllegalArgumentException("Invalid alarm type " + type);
571 }
572
Christopher Tate5f221e82013-07-30 17:13:15 -0700573 if (triggerAtTime < 0) {
574 final long who = Binder.getCallingUid();
575 final long what = Binder.getCallingPid();
576 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + who
577 + " pid=" + what);
578 triggerAtTime = 0;
579 }
580
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700581 final long nowElapsed = SystemClock.elapsedRealtime();
582 final long triggerElapsed = convertToElapsed(triggerAtTime, type);
583 final long maxElapsed;
584 if (windowLength == AlarmManager.WINDOW_EXACT) {
585 maxElapsed = triggerElapsed;
586 } else if (windowLength < 0) {
587 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
588 } else {
589 maxElapsed = triggerElapsed + windowLength;
590 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800592 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700593 if (DEBUG_BATCH) {
594 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700595 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -0700596 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
597 + " interval=" + interval + " standalone=" + isStandalone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800598 }
Christopher Tate3e04b472013-10-21 17:51:31 -0700599 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
David Christieebe51fc2013-07-26 13:23:29 -0700600 interval, operation, isStandalone, true, workSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800601 }
602 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800603
Christopher Tate3e04b472013-10-21 17:51:31 -0700604 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
605 long maxWhen, long interval, PendingIntent operation, boolean isStandalone,
606 boolean doValidate, WorkSource workSource) {
607 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
608 operation, workSource);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700609 removeLocked(operation);
Christopher Tateb8849c12011-02-08 13:39:01 -0800610
Christopher Tate385e4982013-07-23 18:22:29 -0700611 int whichBatch = (isStandalone) ? -1 : attemptCoalesceLocked(whenElapsed, maxWhen);
612 if (whichBatch < 0) {
613 Batch batch = new Batch(a);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700614 batch.standalone = isStandalone;
Christopher Tate7d57ed82013-10-25 20:18:03 -0700615 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800616 } else {
Christopher Tate385e4982013-07-23 18:22:29 -0700617 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -0700618 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700619 // The start time of this batch advanced, so batch ordering may
620 // have just been broken. Move it to where it now belongs.
621 mAlarmBatches.remove(whichBatch);
622 addBatchLocked(mAlarmBatches, batch);
623 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624 }
625
Christopher Tate4cb338d2013-07-26 13:11:31 -0700626 if (DEBUG_VALIDATE) {
Christopher Tate5f221e82013-07-30 17:13:15 -0700627 if (doValidate && !validateConsistencyLocked()) {
628 Slog.v(TAG, "Tipping-point operation: type=" + type + " when=" + when
629 + " when(hex)=" + Long.toHexString(when)
630 + " whenElapsed=" + whenElapsed + " maxWhen=" + maxWhen
631 + " interval=" + interval + " op=" + operation
632 + " standalone=" + isStandalone);
Christopher Tate4cb338d2013-07-26 13:11:31 -0700633 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -0700634 }
635 }
636
Christopher Tate7d57ed82013-10-25 20:18:03 -0700637 rescheduleKernelAlarmsLocked();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700638 }
639
Adam Lesinski182f73f2013-12-05 16:48:06 -0800640 private final IBinder mService = new IAlarmManager.Stub() {
641 @Override
642 public void set(int type, long triggerAtTime, long windowLength, long interval,
643 PendingIntent operation, WorkSource workSource) {
644 if (workSource != null) {
645 getContext().enforceCallingPermission(
646 android.Manifest.permission.UPDATE_DEVICE_STATS,
647 "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -0700648 }
649
Adam Lesinski182f73f2013-12-05 16:48:06 -0800650 setImpl(type, triggerAtTime, windowLength, interval, operation,
651 false, workSource);
652 }
Christopher Tate89779822012-08-31 14:40:03 -0700653
Adam Lesinski182f73f2013-12-05 16:48:06 -0800654 @Override
655 public void setTime(long millis) {
656 getContext().enforceCallingOrSelfPermission(
657 "android.permission.SET_TIME",
658 "setTime");
659
660 SystemClock.setCurrentTimeMillis(millis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800662
663 @Override
664 public void setTimeZone(String tz) {
665 getContext().enforceCallingOrSelfPermission(
666 "android.permission.SET_TIME_ZONE",
667 "setTimeZone");
668
669 final long oldId = Binder.clearCallingIdentity();
670 try {
671 setTimeZoneImpl(tz);
672 } finally {
673 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674 }
675 }
Christopher Tate4cb338d2013-07-26 13:11:31 -0700676
Adam Lesinski182f73f2013-12-05 16:48:06 -0800677 @Override
678 public void remove(PendingIntent operation) {
679 removeImpl(operation);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 }
Christopher Tate4cb338d2013-07-26 13:11:31 -0700682
Adam Lesinski182f73f2013-12-05 16:48:06 -0800683 @Override
684 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
685 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
686 != PackageManager.PERMISSION_GRANTED) {
687 pw.println("Permission Denial: can't dump AlarmManager from from pid="
688 + Binder.getCallingPid()
689 + ", uid=" + Binder.getCallingUid());
690 return;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700691 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700692
Adam Lesinski182f73f2013-12-05 16:48:06 -0800693 dumpImpl(pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700694 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800695 };
Christopher Tate4cb338d2013-07-26 13:11:31 -0700696
Adam Lesinski182f73f2013-12-05 16:48:06 -0800697 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698 synchronized (mLock) {
699 pw.println("Current Alarm Manager state:");
Christopher Tatee0a22b32013-07-11 14:43:13 -0700700 final long nowRTC = System.currentTimeMillis();
701 final long nowELAPSED = SystemClock.elapsedRealtime();
702 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
703
704 pw.print("nowRTC="); pw.print(nowRTC);
705 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
706 pw.print(" nowELAPSED="); pw.println(nowELAPSED);
707
708 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
709 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
710 pw.print("Next alarm: "); pw.print(mNextNonWakeup);
711 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
712 pw.print("Next wakeup: "); pw.print(mNextWakeup);
713 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
714
715 if (mAlarmBatches.size() > 0) {
716 pw.println();
717 pw.print("Pending alarm batches: ");
718 pw.println(mAlarmBatches.size());
719 for (Batch b : mAlarmBatches) {
720 pw.print(b); pw.println(':');
721 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC);
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700722 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800724
725 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700726 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -0800727 pw.println();
728
729 if (mLog.dump(pw, " Recent problems", " ")) {
730 pw.println();
731 }
732
733 final FilterStats[] topFilters = new FilterStats[10];
734 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
735 @Override
736 public int compare(FilterStats lhs, FilterStats rhs) {
737 if (lhs.aggregateTime < rhs.aggregateTime) {
738 return 1;
739 } else if (lhs.aggregateTime > rhs.aggregateTime) {
740 return -1;
741 }
742 return 0;
743 }
744 };
745 int len = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800746 for (Map.Entry<String, BroadcastStats> be : mBroadcastStats.entrySet()) {
747 BroadcastStats bs = be.getValue();
Dianne Hackborn81038902012-11-26 17:04:09 -0800748 for (Map.Entry<Pair<String, ComponentName>, FilterStats> fe
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800749 : bs.filterStats.entrySet()) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800750 FilterStats fs = fe.getValue();
751 int pos = len > 0
752 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
753 if (pos < 0) {
754 pos = -pos - 1;
755 }
756 if (pos < topFilters.length) {
757 int copylen = topFilters.length - pos - 1;
758 if (copylen > 0) {
759 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
760 }
761 topFilters[pos] = fs;
762 if (len < topFilters.length) {
763 len++;
764 }
765 }
766 }
767 }
768 if (len > 0) {
769 pw.println(" Top Alarms:");
770 for (int i=0; i<len; i++) {
771 FilterStats fs = topFilters[i];
772 pw.print(" ");
773 if (fs.nesting > 0) pw.print("*ACTIVE* ");
774 TimeUtils.formatDuration(fs.aggregateTime, pw);
775 pw.print(" running, "); pw.print(fs.numWakeup);
776 pw.print(" wakeups, "); pw.print(fs.count);
777 pw.print(" alarms: "); pw.print(fs.mBroadcastStats.mPackageName);
778 pw.println();
779 pw.print(" ");
780 if (fs.mTarget.first != null) {
781 pw.print(" act="); pw.print(fs.mTarget.first);
782 }
783 if (fs.mTarget.second != null) {
784 pw.print(" cmp="); pw.print(fs.mTarget.second.toShortString());
785 }
786 pw.println();
787 }
788 }
789
790 pw.println(" ");
791 pw.println(" Alarm Stats:");
792 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
793 for (Map.Entry<String, BroadcastStats> be : mBroadcastStats.entrySet()) {
794 BroadcastStats bs = be.getValue();
795 pw.print(" ");
796 if (bs.nesting > 0) pw.print("*ACTIVE* ");
797 pw.print(be.getKey());
798 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
799 pw.print(" running, "); pw.print(bs.numWakeup);
800 pw.println(" wakeups:");
801 tmpFilters.clear();
802 for (Map.Entry<Pair<String, ComponentName>, FilterStats> fe
803 : bs.filterStats.entrySet()) {
804 tmpFilters.add(fe.getValue());
805 }
806 Collections.sort(tmpFilters, comparator);
807 for (int i=0; i<tmpFilters.size(); i++) {
808 FilterStats fs = tmpFilters.get(i);
809 pw.print(" ");
810 if (fs.nesting > 0) pw.print("*ACTIVE* ");
811 TimeUtils.formatDuration(fs.aggregateTime, pw);
812 pw.print(" "); pw.print(fs.numWakeup);
813 pw.print(" wakes " ); pw.print(fs.count);
814 pw.print(" alarms:");
815 if (fs.mTarget.first != null) {
816 pw.print(" act="); pw.print(fs.mTarget.first);
817 }
818 if (fs.mTarget.second != null) {
819 pw.print(" cmp="); pw.print(fs.mTarget.second.toShortString());
820 }
821 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800822 }
823 }
Christopher Tate18a75f12013-07-01 18:18:59 -0700824
825 if (WAKEUP_STATS) {
826 pw.println();
827 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -0700828 long last = -1;
829 for (WakeupEvent event : mRecentWakeups) {
830 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
831 pw.print('|');
832 if (last < 0) {
833 pw.print('0');
834 } else {
835 pw.print(event.when - last);
836 }
837 last = event.when;
838 pw.print('|'); pw.print(event.uid);
839 pw.print('|'); pw.print(event.action);
840 pw.println();
841 }
842 pw.println();
843 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 }
845 }
846
Adam Lesinski182f73f2013-12-05 16:48:06 -0800847 private void logBatchesLocked() {
848 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
849 PrintWriter pw = new PrintWriter(bs);
850 final long nowRTC = System.currentTimeMillis();
851 final long nowELAPSED = SystemClock.elapsedRealtime();
852 final int NZ = mAlarmBatches.size();
853 for (int iz = 0; iz < NZ; iz++) {
854 Batch bz = mAlarmBatches.get(iz);
855 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
856 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC);
857 pw.flush();
858 Slog.v(TAG, bs.toString());
859 bs.reset();
860 }
861 }
862
863 private boolean validateConsistencyLocked() {
864 if (DEBUG_VALIDATE) {
865 long lastTime = Long.MIN_VALUE;
866 final int N = mAlarmBatches.size();
867 for (int i = 0; i < N; i++) {
868 Batch b = mAlarmBatches.get(i);
869 if (b.start >= lastTime) {
870 // duplicate start times are okay because of standalone batches
871 lastTime = b.start;
872 } else {
873 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
874 logBatchesLocked();
875 return false;
876 }
877 }
878 }
879 return true;
880 }
881
882 private Batch findFirstWakeupBatchLocked() {
883 final int N = mAlarmBatches.size();
884 for (int i = 0; i < N; i++) {
885 Batch b = mAlarmBatches.get(i);
886 if (b.hasWakeups()) {
887 return b;
888 }
889 }
890 return null;
891 }
892
893 void rescheduleKernelAlarmsLocked() {
894 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
895 // prior to that which contains no wakeups, we schedule that as well.
896 if (mAlarmBatches.size() > 0) {
897 final Batch firstWakeup = findFirstWakeupBatchLocked();
898 final Batch firstBatch = mAlarmBatches.get(0);
899 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
900 mNextWakeup = firstWakeup.start;
901 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
902 }
903 if (firstBatch != firstWakeup && mNextNonWakeup != firstBatch.start) {
904 mNextNonWakeup = firstBatch.start;
905 setLocked(ELAPSED_REALTIME, firstBatch.start);
906 }
907 }
908 }
909
910 private void removeLocked(PendingIntent operation) {
911 boolean didRemove = false;
912 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
913 Batch b = mAlarmBatches.get(i);
914 didRemove |= b.remove(operation);
915 if (b.size() == 0) {
916 mAlarmBatches.remove(i);
917 }
918 }
919
920 if (didRemove) {
921 if (DEBUG_BATCH) {
922 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
923 }
924 rebatchAllAlarmsLocked(true);
925 rescheduleKernelAlarmsLocked();
926 }
927 }
928
929 void removeLocked(String packageName) {
930 boolean didRemove = false;
931 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
932 Batch b = mAlarmBatches.get(i);
933 didRemove |= b.remove(packageName);
934 if (b.size() == 0) {
935 mAlarmBatches.remove(i);
936 }
937 }
938
939 if (didRemove) {
940 if (DEBUG_BATCH) {
941 Slog.v(TAG, "remove(package) changed bounds; rebatching");
942 }
943 rebatchAllAlarmsLocked(true);
944 rescheduleKernelAlarmsLocked();
945 }
946 }
947
948 void removeUserLocked(int userHandle) {
949 boolean didRemove = false;
950 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
951 Batch b = mAlarmBatches.get(i);
952 didRemove |= b.remove(userHandle);
953 if (b.size() == 0) {
954 mAlarmBatches.remove(i);
955 }
956 }
957
958 if (didRemove) {
959 if (DEBUG_BATCH) {
960 Slog.v(TAG, "remove(user) changed bounds; rebatching");
961 }
962 rebatchAllAlarmsLocked(true);
963 rescheduleKernelAlarmsLocked();
964 }
965 }
966
967 boolean lookForPackageLocked(String packageName) {
968 for (int i = 0; i < mAlarmBatches.size(); i++) {
969 Batch b = mAlarmBatches.get(i);
970 if (b.hasPackage(packageName)) {
971 return true;
972 }
973 }
974 return false;
975 }
976
977 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800978 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800979 // The kernel never triggers alarms with negative wakeup times
980 // so we ensure they are positive.
981 long alarmSeconds, alarmNanoseconds;
982 if (when < 0) {
983 alarmSeconds = 0;
984 alarmNanoseconds = 0;
985 } else {
986 alarmSeconds = when / 1000;
987 alarmNanoseconds = (when % 1000) * 1000 * 1000;
988 }
989
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800990 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800991 } else {
992 Message msg = Message.obtain();
993 msg.what = ALARM_EVENT;
994
995 mHandler.removeMessages(ALARM_EVENT);
996 mHandler.sendMessageAtTime(msg, when);
997 }
998 }
999
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001000 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
1001 String prefix, String label, long now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002 for (int i=list.size()-1; i>=0; i--) {
1003 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001004 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1005 pw.print(": "); pw.println(a);
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001006 a.dump(pw, prefix + " ", now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 }
1008 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001009
1010 private static final String labelForType(int type) {
1011 switch (type) {
1012 case RTC: return "RTC";
1013 case RTC_WAKEUP : return "RTC_WAKEUP";
1014 case ELAPSED_REALTIME : return "ELAPSED";
1015 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
1016 default:
1017 break;
1018 }
1019 return "--unknown--";
1020 }
1021
1022 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
1023 String prefix, long nowELAPSED, long nowRTC) {
1024 for (int i=list.size()-1; i>=0; i--) {
1025 Alarm a = list.get(i);
1026 final String label = labelForType(a.type);
1027 long now = (a.type <= RTC) ? nowRTC : nowELAPSED;
1028 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1029 pw.print(": "); pw.println(a);
1030 a.dump(pw, prefix + " ", now);
1031 }
1032 }
1033
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001034 private native long init();
1035 private native void close(long nativeData);
1036 private native void set(long nativeData, int type, long seconds, long nanoseconds);
1037 private native int waitForAlarm(long nativeData);
1038 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039
Adam Lesinski182f73f2013-12-05 16:48:06 -08001040 void triggerAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED, long nowRTC) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001041 // batches are temporally sorted, so we need only pull from the
1042 // start of the list until we either empty it or hit a batch
1043 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07001044 while (mAlarmBatches.size() > 0) {
1045 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001046 if (batch.start > nowELAPSED) {
1047 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 break;
1049 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050
Christopher Tatee0a22b32013-07-11 14:43:13 -07001051 // We will (re)schedule some alarms now; don't let that interfere
1052 // with delivery of this current batch
1053 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001054
Christopher Tatee0a22b32013-07-11 14:43:13 -07001055 final int N = batch.size();
1056 for (int i = 0; i < N; i++) {
1057 Alarm alarm = batch.get(i);
1058 alarm.count = 1;
1059 triggerList.add(alarm);
1060
1061 // Recurring alarms may have passed several alarm intervals while the
1062 // phone was asleep or off, so pass a trigger count when sending them.
1063 if (alarm.repeatInterval > 0) {
1064 // this adjustment will be zero if we're late by
1065 // less than one full repeat interval
1066 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
1067
1068 // Also schedule its next recurrence
1069 final long delta = alarm.count * alarm.repeatInterval;
1070 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07001071 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07001072 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
David Christieebe51fc2013-07-26 13:23:29 -07001073 alarm.repeatInterval, alarm.operation, batch.standalone, true,
1074 alarm.workSource);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001075 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076
Dianne Hackborn390517b2013-05-30 15:03:32 -07001077 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 /**
1082 * This Comparator sorts Alarms into increasing time order.
1083 */
1084 public static class IncreasingTimeOrder implements Comparator<Alarm> {
1085 public int compare(Alarm a1, Alarm a2) {
1086 long when1 = a1.when;
1087 long when2 = a2.when;
1088 if (when1 - when2 > 0) {
1089 return 1;
1090 }
1091 if (when1 - when2 < 0) {
1092 return -1;
1093 }
1094 return 0;
1095 }
1096 }
1097
1098 private static class Alarm {
1099 public int type;
1100 public int count;
1101 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07001102 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001103 public long whenElapsed; // 'when' in the elapsed time base
1104 public long maxWhen; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 public long repeatInterval;
1106 public PendingIntent operation;
David Christieebe51fc2013-07-26 13:23:29 -07001107 public WorkSource workSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108
Christopher Tate3e04b472013-10-21 17:51:31 -07001109 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
David Christieebe51fc2013-07-26 13:23:29 -07001110 long _interval, PendingIntent _op, WorkSource _ws) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001111 type = _type;
1112 when = _when;
1113 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07001114 windowLength = _windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001115 maxWhen = _maxWhen;
1116 repeatInterval = _interval;
1117 operation = _op;
David Christieebe51fc2013-07-26 13:23:29 -07001118 workSource = _ws;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 @Override
1122 public String toString()
1123 {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001124 StringBuilder sb = new StringBuilder(128);
1125 sb.append("Alarm{");
1126 sb.append(Integer.toHexString(System.identityHashCode(this)));
1127 sb.append(" type ");
1128 sb.append(type);
1129 sb.append(" ");
1130 sb.append(operation.getTargetPackage());
1131 sb.append('}');
1132 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 }
1134
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001135 public void dump(PrintWriter pw, String prefix, long now) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001136 pw.print(prefix); pw.print("type="); pw.print(type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001137 pw.print(" whenElapsed="); pw.print(whenElapsed);
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001138 pw.print(" when="); TimeUtils.formatDuration(when, now, pw);
Christopher Tate3e04b472013-10-21 17:51:31 -07001139 pw.print(" window="); pw.print(windowLength);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001140 pw.print(" repeatInterval="); pw.print(repeatInterval);
1141 pw.print(" count="); pw.println(count);
1142 pw.print(prefix); pw.print("operation="); pw.println(operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001143 }
1144 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001145
Christopher Tatee0a22b32013-07-11 14:43:13 -07001146 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
1147 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07001148 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
1149 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001150 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07001151 break;
1152 }
1153
Christopher Tatee0a22b32013-07-11 14:43:13 -07001154 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07001155 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
1156 Alarm a = b.alarms.get(nextAlarm);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001157 WakeupEvent e = new WakeupEvent(nowRTC,
1158 a.operation.getCreatorUid(),
1159 a.operation.getIntent().getAction());
1160 mRecentWakeups.add(e);
1161 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001162 }
1163 }
1164
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001165 private class AlarmThread extends Thread
1166 {
1167 public AlarmThread()
1168 {
1169 super("AlarmManager");
1170 }
1171
1172 public void run()
1173 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07001174 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
1175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 while (true)
1177 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001178 int result = waitForAlarm(mNativeData);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001179
1180 triggerList.clear();
1181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 if ((result & TIME_CHANGED_MASK) != 0) {
Christopher Tate385e4982013-07-23 18:22:29 -07001183 if (DEBUG_BATCH) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001184 Slog.v(TAG, "Time changed notification from kernel; rebatching");
Christopher Tate385e4982013-07-23 18:22:29 -07001185 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001186 removeImpl(mTimeTickSender);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001187 rebatchAllAlarms();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188 mClockReceiver.scheduleTimeTickEvent();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001189 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
Dianne Hackborn89ba6752011-01-23 16:51:16 -08001190 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1191 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001192 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193 }
1194
1195 synchronized (mLock) {
1196 final long nowRTC = System.currentTimeMillis();
1197 final long nowELAPSED = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001198 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199 TAG, "Checking for alarms... rtc=" + nowRTC
1200 + ", elapsed=" + nowELAPSED);
1201
Christopher Tate18a75f12013-07-01 18:18:59 -07001202 if (WAKEUP_STATS) {
1203 if ((result & IS_WAKEUP_MASK) != 0) {
1204 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
1205 int n = 0;
1206 for (WakeupEvent event : mRecentWakeups) {
1207 if (event.when > newEarliest) break;
1208 n++; // number of now-stale entries at the list head
1209 }
1210 for (int i = 0; i < n; i++) {
1211 mRecentWakeups.remove();
1212 }
1213
Christopher Tatee0a22b32013-07-11 14:43:13 -07001214 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Christopher Tate18a75f12013-07-01 18:18:59 -07001215 }
1216 }
1217
Christopher Tatee0a22b32013-07-11 14:43:13 -07001218 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
1219 rescheduleKernelAlarmsLocked();
1220
1221 // now deliver the alarm intents
Dianne Hackborn390517b2013-05-30 15:03:32 -07001222 for (int i=0; i<triggerList.size(); i++) {
1223 Alarm alarm = triggerList.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001224 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001225 if (localLOGV) Slog.v(TAG, "sending alarm " + alarm);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001226 alarm.operation.send(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001227 mBackgroundIntent.putExtra(
1228 Intent.EXTRA_ALARM_COUNT, alarm.count),
1229 mResultReceiver, mHandler);
1230
Christopher Tatec4a07d12012-04-06 14:19:13 -07001231 // we have an active broadcast so stay awake.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 if (mBroadcastRefCount == 0) {
David Christieebe51fc2013-07-26 13:23:29 -07001233 setWakelockWorkSource(alarm.operation, alarm.workSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234 mWakeLock.acquire();
1235 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001236 final InFlight inflight = new InFlight(AlarmManagerService.this,
David Christieebe51fc2013-07-26 13:23:29 -07001237 alarm.operation, alarm.workSource);
Dianne Hackborn81038902012-11-26 17:04:09 -08001238 mInFlight.add(inflight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239 mBroadcastRefCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08001240
1241 final BroadcastStats bs = inflight.mBroadcastStats;
1242 bs.count++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001243 if (bs.nesting == 0) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001244 bs.nesting = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 bs.startTime = nowELAPSED;
1246 } else {
1247 bs.nesting++;
1248 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001249 final FilterStats fs = inflight.mFilterStats;
1250 fs.count++;
1251 if (fs.nesting == 0) {
1252 fs.nesting = 1;
1253 fs.startTime = nowELAPSED;
1254 } else {
1255 fs.nesting++;
1256 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001257 if (alarm.type == ELAPSED_REALTIME_WAKEUP
1258 || alarm.type == RTC_WAKEUP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001259 bs.numWakeup++;
Dianne Hackborn81038902012-11-26 17:04:09 -08001260 fs.numWakeup++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 ActivityManagerNative.noteWakeupAlarm(
1262 alarm.operation);
1263 }
1264 } catch (PendingIntent.CanceledException e) {
1265 if (alarm.repeatInterval > 0) {
1266 // This IntentSender is no longer valid, but this
1267 // is a repeating alarm, so toss the hoser.
Adam Lesinski182f73f2013-12-05 16:48:06 -08001268 removeImpl(alarm.operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 }
1270 } catch (RuntimeException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001271 Slog.w(TAG, "Failure sending alarm.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001272 }
1273 }
1274 }
1275 }
1276 }
1277 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07001278
David Christieebe51fc2013-07-26 13:23:29 -07001279 /**
1280 * Attribute blame for a WakeLock.
1281 * @param pi PendingIntent to attribute blame to if ws is null.
1282 * @param ws WorkSource to attribute blame.
1283 */
1284 void setWakelockWorkSource(PendingIntent pi, WorkSource ws) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07001285 try {
David Christieebe51fc2013-07-26 13:23:29 -07001286 if (ws != null) {
1287 mWakeLock.setWorkSource(ws);
1288 return;
1289 }
1290
Christopher Tatec4a07d12012-04-06 14:19:13 -07001291 final int uid = ActivityManagerNative.getDefault()
1292 .getUidForIntentSender(pi.getTarget());
1293 if (uid >= 0) {
1294 mWakeLock.setWorkSource(new WorkSource(uid));
1295 return;
1296 }
1297 } catch (Exception e) {
1298 }
1299
1300 // Something went wrong; fall back to attributing the lock to the OS
1301 mWakeLock.setWorkSource(null);
1302 }
1303
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 private class AlarmHandler extends Handler {
1305 public static final int ALARM_EVENT = 1;
1306 public static final int MINUTE_CHANGE_EVENT = 2;
1307 public static final int DATE_CHANGE_EVENT = 3;
1308
1309 public AlarmHandler() {
1310 }
1311
1312 public void handleMessage(Message msg) {
1313 if (msg.what == ALARM_EVENT) {
1314 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
1315 synchronized (mLock) {
1316 final long nowRTC = System.currentTimeMillis();
Christopher Tatee0a22b32013-07-11 14:43:13 -07001317 final long nowELAPSED = SystemClock.elapsedRealtime();
1318 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 }
1320
1321 // now trigger the alarms without the lock held
Dianne Hackborn390517b2013-05-30 15:03:32 -07001322 for (int i=0; i<triggerList.size(); i++) {
1323 Alarm alarm = triggerList.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 try {
1325 alarm.operation.send();
1326 } catch (PendingIntent.CanceledException e) {
1327 if (alarm.repeatInterval > 0) {
1328 // This IntentSender is no longer valid, but this
1329 // is a repeating alarm, so toss the hoser.
Adam Lesinski182f73f2013-12-05 16:48:06 -08001330 removeImpl(alarm.operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 }
1332 }
1333 }
1334 }
1335 }
1336 }
1337
1338 class ClockReceiver extends BroadcastReceiver {
1339 public ClockReceiver() {
1340 IntentFilter filter = new IntentFilter();
1341 filter.addAction(Intent.ACTION_TIME_TICK);
1342 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001343 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 }
1345
1346 @Override
1347 public void onReceive(Context context, Intent intent) {
1348 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001349 if (DEBUG_BATCH) {
1350 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
1351 }
1352 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001353 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
1354 // Since the kernel does not keep track of DST, we need to
1355 // reset the TZ information at the beginning of each day
1356 // based off of the current Zone gmt offset + userspace tracked
1357 // daylight savings information.
1358 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02001359 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001360 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07001361 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362 }
1363 }
1364
1365 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07001366 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09001367 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07001368
1369 // Schedule this event for the amount of time that it would take to get to
1370 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09001371 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07001372
David Christieebe51fc2013-07-26 13:23:29 -07001373 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08001374 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
David Christieebe51fc2013-07-26 13:23:29 -07001375 0, mTimeTickSender, true, workSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 }
Christopher Tate385e4982013-07-23 18:22:29 -07001377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 public void scheduleDateChangedEvent() {
1379 Calendar calendar = Calendar.getInstance();
1380 calendar.setTimeInMillis(System.currentTimeMillis());
1381 calendar.set(Calendar.HOUR, 0);
1382 calendar.set(Calendar.MINUTE, 0);
1383 calendar.set(Calendar.SECOND, 0);
1384 calendar.set(Calendar.MILLISECOND, 0);
1385 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07001386
1387 final WorkSource workSource = null; // Let system take blame for date change events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08001388 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, true, workSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 }
1390 }
1391
1392 class UninstallReceiver extends BroadcastReceiver {
1393 public UninstallReceiver() {
1394 IntentFilter filter = new IntentFilter();
1395 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1396 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001397 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08001399 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001400 // Register for events related to sdcard installation.
1401 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001402 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001403 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001404 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 }
1406
1407 @Override
1408 public void onReceive(Context context, Intent intent) {
1409 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001410 String action = intent.getAction();
1411 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001412 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
1413 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
1414 for (String packageName : pkgList) {
1415 if (lookForPackageLocked(packageName)) {
1416 setResultCode(Activity.RESULT_OK);
1417 return;
1418 }
1419 }
1420 return;
1421 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001422 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001423 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
1424 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
1425 if (userHandle >= 0) {
1426 removeUserLocked(userHandle);
1427 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001428 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08001429 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
1430 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
1431 // This package is being updated; don't kill its alarms.
1432 return;
1433 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001434 Uri data = intent.getData();
1435 if (data != null) {
1436 String pkg = data.getSchemeSpecificPart();
1437 if (pkg != null) {
1438 pkgList = new String[]{pkg};
1439 }
1440 }
1441 }
1442 if (pkgList != null && (pkgList.length > 0)) {
1443 for (String pkg : pkgList) {
1444 removeLocked(pkg);
1445 mBroadcastStats.remove(pkg);
1446 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 }
1448 }
1449 }
1450 }
1451
1452 private final BroadcastStats getStatsLocked(PendingIntent pi) {
1453 String pkg = pi.getTargetPackage();
1454 BroadcastStats bs = mBroadcastStats.get(pkg);
1455 if (bs == null) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001456 bs = new BroadcastStats(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001457 mBroadcastStats.put(pkg, bs);
1458 }
1459 return bs;
1460 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 class ResultReceiver implements PendingIntent.OnFinished {
1463 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
1464 String resultData, Bundle resultExtras) {
1465 synchronized (mLock) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001466 InFlight inflight = null;
1467 for (int i=0; i<mInFlight.size(); i++) {
1468 if (mInFlight.get(i).mPendingIntent == pi) {
1469 inflight = mInFlight.remove(i);
1470 break;
1471 }
1472 }
1473 if (inflight != null) {
1474 final long nowELAPSED = SystemClock.elapsedRealtime();
1475 BroadcastStats bs = inflight.mBroadcastStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 bs.nesting--;
1477 if (bs.nesting <= 0) {
1478 bs.nesting = 0;
Dianne Hackborn81038902012-11-26 17:04:09 -08001479 bs.aggregateTime += nowELAPSED - bs.startTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001480 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001481 FilterStats fs = inflight.mFilterStats;
1482 fs.nesting--;
1483 if (fs.nesting <= 0) {
1484 fs.nesting = 0;
1485 fs.aggregateTime += nowELAPSED - fs.startTime;
1486 }
1487 } else {
1488 mLog.w("No in-flight alarm for " + pi + " " + intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 }
1490 mBroadcastRefCount--;
1491 if (mBroadcastRefCount == 0) {
1492 mWakeLock.release();
Dianne Hackborn81038902012-11-26 17:04:09 -08001493 if (mInFlight.size() > 0) {
1494 mLog.w("Finished all broadcasts with " + mInFlight.size()
1495 + " remaining inflights");
1496 for (int i=0; i<mInFlight.size(); i++) {
1497 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
1498 }
1499 mInFlight.clear();
1500 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07001501 } else {
1502 // the next of our alarms is now in flight. reattribute the wakelock.
Dianne Hackborn81038902012-11-26 17:04:09 -08001503 if (mInFlight.size() > 0) {
David Christieebe51fc2013-07-26 13:23:29 -07001504 InFlight inFlight = mInFlight.get(0);
1505 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource);
Christopher Tatec4a07d12012-04-06 14:19:13 -07001506 } else {
1507 // should never happen
Dianne Hackborn81038902012-11-26 17:04:09 -08001508 mLog.w("Alarm wakelock still held but sent queue empty");
Christopher Tatec4a07d12012-04-06 14:19:13 -07001509 mWakeLock.setWorkSource(null);
1510 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 }
1512 }
1513 }
1514 }
1515}