blob: c14ed8b24abf0175811161788b0fdc05d096d656 [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
Jeff Brownb880d882014-02-10 19:47:07 -0800322 public AlarmManagerService(Context context) {
323 super(context);
324 }
325
Christopher Tatee0a22b32013-07-11 14:43:13 -0700326 static long convertToElapsed(long when, int type) {
327 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
328 if (isRtc) {
329 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
330 }
331 return when;
332 }
333
334 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
335 // calculate the end of our nominal delivery window for the alarm.
336 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
337 // Current heuristic: batchable window is 75% of either the recurrence interval
338 // [for a periodic alarm] or of the time from now to the desired delivery time,
339 // with a minimum delay/interval of 10 seconds, under which we will simply not
340 // defer the alarm.
341 long futurity = (interval == 0)
342 ? (triggerAtTime - now)
343 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700344 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700345 futurity = 0;
346 }
347 return triggerAtTime + (long)(.75 * futurity);
348 }
349
350 // returns true if the batch was added at the head
351 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
352 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
353 if (index < 0) {
354 index = 0 - index - 1;
355 }
356 list.add(index, newBatch);
357 return (index == 0);
358 }
359
Christopher Tate385e4982013-07-23 18:22:29 -0700360 // Return the index of the matching batch, or -1 if none found.
361 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700362 final int N = mAlarmBatches.size();
363 for (int i = 0; i < N; i++) {
364 Batch b = mAlarmBatches.get(i);
365 if (!b.standalone && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700366 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700367 }
368 }
Christopher Tate385e4982013-07-23 18:22:29 -0700369 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700370 }
371
372 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
373 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700374 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700375 rebatchAllAlarmsLocked(true);
376 }
377 }
378
379 void rebatchAllAlarmsLocked(boolean doValidate) {
380 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
381 mAlarmBatches.clear();
382 final long nowElapsed = SystemClock.elapsedRealtime();
383 final int oldBatches = oldSet.size();
384 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
385 Batch batch = oldSet.get(batchNum);
386 final int N = batch.size();
387 for (int i = 0; i < N; i++) {
388 Alarm a = batch.get(i);
389 long whenElapsed = convertToElapsed(a.when, a.type);
Christopher Tate3e04b472013-10-21 17:51:31 -0700390 final long maxElapsed;
391 if (a.whenElapsed == a.maxWhen) {
392 // Exact
393 maxElapsed = whenElapsed;
394 } else {
395 // Not exact. Preserve any explicit window, otherwise recalculate
396 // the window based on the alarm's new futurity. Note that this
397 // reflects a policy of preferring timely to deferred delivery.
398 maxElapsed = (a.windowLength > 0)
399 ? (whenElapsed + a.windowLength)
400 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
401 }
402 setImplLocked(a.type, a.when, whenElapsed, a.windowLength, maxElapsed,
David Christieebe51fc2013-07-26 13:23:29 -0700403 a.repeatInterval, a.operation, batch.standalone, doValidate, a.workSource);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700404 }
405 }
406 }
407
Adam Lesinski182f73f2013-12-05 16:48:06 -0800408 static final class InFlight extends Intent {
Dianne Hackborn81038902012-11-26 17:04:09 -0800409 final PendingIntent mPendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700410 final WorkSource mWorkSource;
Dianne Hackborn81038902012-11-26 17:04:09 -0800411 final Pair<String, ComponentName> mTarget;
412 final BroadcastStats mBroadcastStats;
413 final FilterStats mFilterStats;
414
David Christieebe51fc2013-07-26 13:23:29 -0700415 InFlight(AlarmManagerService service, PendingIntent pendingIntent, WorkSource workSource) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800416 mPendingIntent = pendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700417 mWorkSource = workSource;
Dianne Hackborn81038902012-11-26 17:04:09 -0800418 Intent intent = pendingIntent.getIntent();
419 mTarget = intent != null
420 ? new Pair<String, ComponentName>(intent.getAction(), intent.getComponent())
421 : null;
422 mBroadcastStats = service.getStatsLocked(pendingIntent);
423 FilterStats fs = mBroadcastStats.filterStats.get(mTarget);
424 if (fs == null) {
425 fs = new FilterStats(mBroadcastStats, mTarget);
426 mBroadcastStats.filterStats.put(mTarget, fs);
427 }
428 mFilterStats = fs;
429 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800431
Adam Lesinski182f73f2013-12-05 16:48:06 -0800432 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -0800433 final BroadcastStats mBroadcastStats;
434 final Pair<String, ComponentName> mTarget;
435
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800437 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800438 int numWakeup;
439 long startTime;
440 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -0800441
442 FilterStats(BroadcastStats broadcastStats, Pair<String, ComponentName> target) {
443 mBroadcastStats = broadcastStats;
444 mTarget = target;
445 }
446 }
447
Adam Lesinski182f73f2013-12-05 16:48:06 -0800448 static final class BroadcastStats {
Dianne Hackborn81038902012-11-26 17:04:09 -0800449 final String mPackageName;
450
451 long aggregateTime;
452 int count;
453 int numWakeup;
454 long startTime;
455 int nesting;
456 final HashMap<Pair<String, ComponentName>, FilterStats> filterStats
457 = new HashMap<Pair<String, ComponentName>, FilterStats>();
458
459 BroadcastStats(String packageName) {
460 mPackageName = packageName;
461 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800462 }
463
Adam Lesinski182f73f2013-12-05 16:48:06 -0800464 final HashMap<String, BroadcastStats> mBroadcastStats
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800465 = new HashMap<String, BroadcastStats>();
466
Adam Lesinski182f73f2013-12-05 16:48:06 -0800467 @Override
468 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800469 mNativeData = init();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700470 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800471
472 // We have to set current TimeZone info to kernel
473 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -0800474 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800475
Adam Lesinski182f73f2013-12-05 16:48:06 -0800476 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800477 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
478
Adam Lesinski182f73f2013-12-05 16:48:06 -0800479 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700481 Intent.FLAG_RECEIVER_REGISTERED_ONLY
482 | Intent.FLAG_RECEIVER_FOREGROUND), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700483 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800484 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
485 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800486 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700487 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800488
489 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -0800490 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800491 mClockReceiver.scheduleTimeTickEvent();
492 mClockReceiver.scheduleDateChangedEvent();
493 mUninstallReceiver = new UninstallReceiver();
494
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800495 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800496 AlarmThread waitThread = new AlarmThread();
497 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800498 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800499 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800500 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800501
502 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800503 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800504
505 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506 protected void finalize() throws Throwable {
507 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800508 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800509 } finally {
510 super.finalize();
511 }
512 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700513
Adam Lesinski182f73f2013-12-05 16:48:06 -0800514 void setTimeZoneImpl(String tz) {
515 if (TextUtils.isEmpty(tz)) {
516 return;
David Christieebe51fc2013-07-26 13:23:29 -0700517 }
518
Adam Lesinski182f73f2013-12-05 16:48:06 -0800519 TimeZone zone = TimeZone.getTimeZone(tz);
520 // Prevent reentrant calls from stepping on each other when writing
521 // the time zone property
522 boolean timeZoneWasChanged = false;
523 synchronized (this) {
524 String current = SystemProperties.get(TIMEZONE_PROPERTY);
525 if (current == null || !current.equals(zone.getID())) {
526 if (localLOGV) {
527 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
528 }
529 timeZoneWasChanged = true;
530 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
531 }
532
533 // Update the kernel timezone information
534 // Kernel tracks time offsets as 'minutes west of GMT'
535 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800536 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -0800537 }
538
539 TimeZone.setDefault(null);
540
541 if (timeZoneWasChanged) {
542 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
543 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
544 intent.putExtra("time-zone", zone.getID());
545 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
546 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800547 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700548
Adam Lesinski182f73f2013-12-05 16:48:06 -0800549 void removeImpl(PendingIntent operation) {
550 if (operation == null) {
551 return;
552 }
553 synchronized (mLock) {
554 removeLocked(operation);
555 }
556 }
557
558 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
David Christieebe51fc2013-07-26 13:23:29 -0700559 PendingIntent operation, boolean isStandalone, WorkSource workSource) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560 if (operation == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800561 Slog.w(TAG, "set/setRepeating ignored because there is no intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562 return;
563 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700564
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700565 // Sanity check the window length. This will catch people mistakenly
566 // trying to pass an end-of-window timestamp rather than a duration.
567 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
568 Slog.w(TAG, "Window length " + windowLength
569 + "ms suspiciously long; limiting to 1 hour");
570 windowLength = AlarmManager.INTERVAL_HOUR;
571 }
572
Christopher Tatee0a22b32013-07-11 14:43:13 -0700573 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
574 throw new IllegalArgumentException("Invalid alarm type " + type);
575 }
576
Christopher Tate5f221e82013-07-30 17:13:15 -0700577 if (triggerAtTime < 0) {
578 final long who = Binder.getCallingUid();
579 final long what = Binder.getCallingPid();
580 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + who
581 + " pid=" + what);
582 triggerAtTime = 0;
583 }
584
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700585 final long nowElapsed = SystemClock.elapsedRealtime();
586 final long triggerElapsed = convertToElapsed(triggerAtTime, type);
587 final long maxElapsed;
588 if (windowLength == AlarmManager.WINDOW_EXACT) {
589 maxElapsed = triggerElapsed;
590 } else if (windowLength < 0) {
591 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
592 } else {
593 maxElapsed = triggerElapsed + windowLength;
594 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800596 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700597 if (DEBUG_BATCH) {
598 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700599 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -0700600 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
601 + " interval=" + interval + " standalone=" + isStandalone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800602 }
Christopher Tate3e04b472013-10-21 17:51:31 -0700603 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
David Christieebe51fc2013-07-26 13:23:29 -0700604 interval, operation, isStandalone, true, workSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605 }
606 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607
Christopher Tate3e04b472013-10-21 17:51:31 -0700608 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
609 long maxWhen, long interval, PendingIntent operation, boolean isStandalone,
610 boolean doValidate, WorkSource workSource) {
611 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
612 operation, workSource);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700613 removeLocked(operation);
Christopher Tateb8849c12011-02-08 13:39:01 -0800614
Christopher Tate385e4982013-07-23 18:22:29 -0700615 int whichBatch = (isStandalone) ? -1 : attemptCoalesceLocked(whenElapsed, maxWhen);
616 if (whichBatch < 0) {
617 Batch batch = new Batch(a);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700618 batch.standalone = isStandalone;
Christopher Tate7d57ed82013-10-25 20:18:03 -0700619 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800620 } else {
Christopher Tate385e4982013-07-23 18:22:29 -0700621 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -0700622 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700623 // The start time of this batch advanced, so batch ordering may
624 // have just been broken. Move it to where it now belongs.
625 mAlarmBatches.remove(whichBatch);
626 addBatchLocked(mAlarmBatches, batch);
627 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800628 }
629
Christopher Tate4cb338d2013-07-26 13:11:31 -0700630 if (DEBUG_VALIDATE) {
Christopher Tate5f221e82013-07-30 17:13:15 -0700631 if (doValidate && !validateConsistencyLocked()) {
632 Slog.v(TAG, "Tipping-point operation: type=" + type + " when=" + when
633 + " when(hex)=" + Long.toHexString(when)
634 + " whenElapsed=" + whenElapsed + " maxWhen=" + maxWhen
635 + " interval=" + interval + " op=" + operation
636 + " standalone=" + isStandalone);
Christopher Tate4cb338d2013-07-26 13:11:31 -0700637 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -0700638 }
639 }
640
Christopher Tate7d57ed82013-10-25 20:18:03 -0700641 rescheduleKernelAlarmsLocked();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700642 }
643
Adam Lesinski182f73f2013-12-05 16:48:06 -0800644 private final IBinder mService = new IAlarmManager.Stub() {
645 @Override
646 public void set(int type, long triggerAtTime, long windowLength, long interval,
647 PendingIntent operation, WorkSource workSource) {
648 if (workSource != null) {
649 getContext().enforceCallingPermission(
650 android.Manifest.permission.UPDATE_DEVICE_STATS,
651 "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -0700652 }
653
Adam Lesinski182f73f2013-12-05 16:48:06 -0800654 setImpl(type, triggerAtTime, windowLength, interval, operation,
655 false, workSource);
656 }
Christopher Tate89779822012-08-31 14:40:03 -0700657
Adam Lesinski182f73f2013-12-05 16:48:06 -0800658 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -0800659 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800660 getContext().enforceCallingOrSelfPermission(
661 "android.permission.SET_TIME",
662 "setTime");
663
Greg Hackmann0cab8962014-02-21 16:35:52 -0800664 if (mNativeData == 0) {
665 Slog.w(TAG, "Not setting time since no alarm driver is available.");
666 return false;
Christopher Tate89779822012-08-31 14:40:03 -0700667 }
Greg Hackmann0cab8962014-02-21 16:35:52 -0800668
669 synchronized (mLock) {
670 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800673
674 @Override
675 public void setTimeZone(String tz) {
676 getContext().enforceCallingOrSelfPermission(
677 "android.permission.SET_TIME_ZONE",
678 "setTimeZone");
679
680 final long oldId = Binder.clearCallingIdentity();
681 try {
682 setTimeZoneImpl(tz);
683 } finally {
684 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 }
686 }
Christopher Tate4cb338d2013-07-26 13:11:31 -0700687
Adam Lesinski182f73f2013-12-05 16:48:06 -0800688 @Override
689 public void remove(PendingIntent operation) {
690 removeImpl(operation);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 }
Christopher Tate4cb338d2013-07-26 13:11:31 -0700693
Adam Lesinski182f73f2013-12-05 16:48:06 -0800694 @Override
695 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
696 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
697 != PackageManager.PERMISSION_GRANTED) {
698 pw.println("Permission Denial: can't dump AlarmManager from from pid="
699 + Binder.getCallingPid()
700 + ", uid=" + Binder.getCallingUid());
701 return;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700702 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700703
Adam Lesinski182f73f2013-12-05 16:48:06 -0800704 dumpImpl(pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700705 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800706 };
Christopher Tate4cb338d2013-07-26 13:11:31 -0700707
Adam Lesinski182f73f2013-12-05 16:48:06 -0800708 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709 synchronized (mLock) {
710 pw.println("Current Alarm Manager state:");
Christopher Tatee0a22b32013-07-11 14:43:13 -0700711 final long nowRTC = System.currentTimeMillis();
712 final long nowELAPSED = SystemClock.elapsedRealtime();
713 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
714
715 pw.print("nowRTC="); pw.print(nowRTC);
716 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
717 pw.print(" nowELAPSED="); pw.println(nowELAPSED);
718
719 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
720 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
721 pw.print("Next alarm: "); pw.print(mNextNonWakeup);
722 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
723 pw.print("Next wakeup: "); pw.print(mNextWakeup);
724 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
725
726 if (mAlarmBatches.size() > 0) {
727 pw.println();
728 pw.print("Pending alarm batches: ");
729 pw.println(mAlarmBatches.size());
730 for (Batch b : mAlarmBatches) {
731 pw.print(b); pw.println(':');
732 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC);
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700733 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800735
736 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700737 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -0800738 pw.println();
739
740 if (mLog.dump(pw, " Recent problems", " ")) {
741 pw.println();
742 }
743
744 final FilterStats[] topFilters = new FilterStats[10];
745 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
746 @Override
747 public int compare(FilterStats lhs, FilterStats rhs) {
748 if (lhs.aggregateTime < rhs.aggregateTime) {
749 return 1;
750 } else if (lhs.aggregateTime > rhs.aggregateTime) {
751 return -1;
752 }
753 return 0;
754 }
755 };
756 int len = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800757 for (Map.Entry<String, BroadcastStats> be : mBroadcastStats.entrySet()) {
758 BroadcastStats bs = be.getValue();
Dianne Hackborn81038902012-11-26 17:04:09 -0800759 for (Map.Entry<Pair<String, ComponentName>, FilterStats> fe
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 : bs.filterStats.entrySet()) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800761 FilterStats fs = fe.getValue();
762 int pos = len > 0
763 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
764 if (pos < 0) {
765 pos = -pos - 1;
766 }
767 if (pos < topFilters.length) {
768 int copylen = topFilters.length - pos - 1;
769 if (copylen > 0) {
770 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
771 }
772 topFilters[pos] = fs;
773 if (len < topFilters.length) {
774 len++;
775 }
776 }
777 }
778 }
779 if (len > 0) {
780 pw.println(" Top Alarms:");
781 for (int i=0; i<len; i++) {
782 FilterStats fs = topFilters[i];
783 pw.print(" ");
784 if (fs.nesting > 0) pw.print("*ACTIVE* ");
785 TimeUtils.formatDuration(fs.aggregateTime, pw);
786 pw.print(" running, "); pw.print(fs.numWakeup);
787 pw.print(" wakeups, "); pw.print(fs.count);
788 pw.print(" alarms: "); pw.print(fs.mBroadcastStats.mPackageName);
789 pw.println();
790 pw.print(" ");
791 if (fs.mTarget.first != null) {
792 pw.print(" act="); pw.print(fs.mTarget.first);
793 }
794 if (fs.mTarget.second != null) {
795 pw.print(" cmp="); pw.print(fs.mTarget.second.toShortString());
796 }
797 pw.println();
798 }
799 }
800
801 pw.println(" ");
802 pw.println(" Alarm Stats:");
803 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
804 for (Map.Entry<String, BroadcastStats> be : mBroadcastStats.entrySet()) {
805 BroadcastStats bs = be.getValue();
806 pw.print(" ");
807 if (bs.nesting > 0) pw.print("*ACTIVE* ");
808 pw.print(be.getKey());
809 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
810 pw.print(" running, "); pw.print(bs.numWakeup);
811 pw.println(" wakeups:");
812 tmpFilters.clear();
813 for (Map.Entry<Pair<String, ComponentName>, FilterStats> fe
814 : bs.filterStats.entrySet()) {
815 tmpFilters.add(fe.getValue());
816 }
817 Collections.sort(tmpFilters, comparator);
818 for (int i=0; i<tmpFilters.size(); i++) {
819 FilterStats fs = tmpFilters.get(i);
820 pw.print(" ");
821 if (fs.nesting > 0) pw.print("*ACTIVE* ");
822 TimeUtils.formatDuration(fs.aggregateTime, pw);
823 pw.print(" "); pw.print(fs.numWakeup);
824 pw.print(" wakes " ); pw.print(fs.count);
825 pw.print(" alarms:");
826 if (fs.mTarget.first != null) {
827 pw.print(" act="); pw.print(fs.mTarget.first);
828 }
829 if (fs.mTarget.second != null) {
830 pw.print(" cmp="); pw.print(fs.mTarget.second.toShortString());
831 }
832 pw.println();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 }
834 }
Christopher Tate18a75f12013-07-01 18:18:59 -0700835
836 if (WAKEUP_STATS) {
837 pw.println();
838 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -0700839 long last = -1;
840 for (WakeupEvent event : mRecentWakeups) {
841 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
842 pw.print('|');
843 if (last < 0) {
844 pw.print('0');
845 } else {
846 pw.print(event.when - last);
847 }
848 last = event.when;
849 pw.print('|'); pw.print(event.uid);
850 pw.print('|'); pw.print(event.action);
851 pw.println();
852 }
853 pw.println();
854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 }
856 }
857
Adam Lesinski182f73f2013-12-05 16:48:06 -0800858 private void logBatchesLocked() {
859 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
860 PrintWriter pw = new PrintWriter(bs);
861 final long nowRTC = System.currentTimeMillis();
862 final long nowELAPSED = SystemClock.elapsedRealtime();
863 final int NZ = mAlarmBatches.size();
864 for (int iz = 0; iz < NZ; iz++) {
865 Batch bz = mAlarmBatches.get(iz);
866 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
867 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC);
868 pw.flush();
869 Slog.v(TAG, bs.toString());
870 bs.reset();
871 }
872 }
873
874 private boolean validateConsistencyLocked() {
875 if (DEBUG_VALIDATE) {
876 long lastTime = Long.MIN_VALUE;
877 final int N = mAlarmBatches.size();
878 for (int i = 0; i < N; i++) {
879 Batch b = mAlarmBatches.get(i);
880 if (b.start >= lastTime) {
881 // duplicate start times are okay because of standalone batches
882 lastTime = b.start;
883 } else {
884 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
885 logBatchesLocked();
886 return false;
887 }
888 }
889 }
890 return true;
891 }
892
893 private Batch findFirstWakeupBatchLocked() {
894 final int N = mAlarmBatches.size();
895 for (int i = 0; i < N; i++) {
896 Batch b = mAlarmBatches.get(i);
897 if (b.hasWakeups()) {
898 return b;
899 }
900 }
901 return null;
902 }
903
904 void rescheduleKernelAlarmsLocked() {
905 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
906 // prior to that which contains no wakeups, we schedule that as well.
907 if (mAlarmBatches.size() > 0) {
908 final Batch firstWakeup = findFirstWakeupBatchLocked();
909 final Batch firstBatch = mAlarmBatches.get(0);
910 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
911 mNextWakeup = firstWakeup.start;
912 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
913 }
914 if (firstBatch != firstWakeup && mNextNonWakeup != firstBatch.start) {
915 mNextNonWakeup = firstBatch.start;
916 setLocked(ELAPSED_REALTIME, firstBatch.start);
917 }
918 }
919 }
920
921 private void removeLocked(PendingIntent operation) {
922 boolean didRemove = false;
923 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
924 Batch b = mAlarmBatches.get(i);
925 didRemove |= b.remove(operation);
926 if (b.size() == 0) {
927 mAlarmBatches.remove(i);
928 }
929 }
930
931 if (didRemove) {
932 if (DEBUG_BATCH) {
933 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
934 }
935 rebatchAllAlarmsLocked(true);
936 rescheduleKernelAlarmsLocked();
937 }
938 }
939
940 void removeLocked(String packageName) {
941 boolean didRemove = false;
942 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
943 Batch b = mAlarmBatches.get(i);
944 didRemove |= b.remove(packageName);
945 if (b.size() == 0) {
946 mAlarmBatches.remove(i);
947 }
948 }
949
950 if (didRemove) {
951 if (DEBUG_BATCH) {
952 Slog.v(TAG, "remove(package) changed bounds; rebatching");
953 }
954 rebatchAllAlarmsLocked(true);
955 rescheduleKernelAlarmsLocked();
956 }
957 }
958
959 void removeUserLocked(int userHandle) {
960 boolean didRemove = false;
961 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
962 Batch b = mAlarmBatches.get(i);
963 didRemove |= b.remove(userHandle);
964 if (b.size() == 0) {
965 mAlarmBatches.remove(i);
966 }
967 }
968
969 if (didRemove) {
970 if (DEBUG_BATCH) {
971 Slog.v(TAG, "remove(user) changed bounds; rebatching");
972 }
973 rebatchAllAlarmsLocked(true);
974 rescheduleKernelAlarmsLocked();
975 }
976 }
977
978 boolean lookForPackageLocked(String packageName) {
979 for (int i = 0; i < mAlarmBatches.size(); i++) {
980 Batch b = mAlarmBatches.get(i);
981 if (b.hasPackage(packageName)) {
982 return true;
983 }
984 }
985 return false;
986 }
987
988 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800989 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800990 // The kernel never triggers alarms with negative wakeup times
991 // so we ensure they are positive.
992 long alarmSeconds, alarmNanoseconds;
993 if (when < 0) {
994 alarmSeconds = 0;
995 alarmNanoseconds = 0;
996 } else {
997 alarmSeconds = when / 1000;
998 alarmNanoseconds = (when % 1000) * 1000 * 1000;
999 }
1000
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001001 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001002 } else {
1003 Message msg = Message.obtain();
1004 msg.what = ALARM_EVENT;
1005
1006 mHandler.removeMessages(ALARM_EVENT);
1007 mHandler.sendMessageAtTime(msg, when);
1008 }
1009 }
1010
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001011 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
1012 String prefix, String label, long now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 for (int i=list.size()-1; i>=0; i--) {
1014 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001015 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1016 pw.print(": "); pw.println(a);
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001017 a.dump(pw, prefix + " ", now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 }
1019 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001020
1021 private static final String labelForType(int type) {
1022 switch (type) {
1023 case RTC: return "RTC";
1024 case RTC_WAKEUP : return "RTC_WAKEUP";
1025 case ELAPSED_REALTIME : return "ELAPSED";
1026 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
1027 default:
1028 break;
1029 }
1030 return "--unknown--";
1031 }
1032
1033 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
1034 String prefix, long nowELAPSED, long nowRTC) {
1035 for (int i=list.size()-1; i>=0; i--) {
1036 Alarm a = list.get(i);
1037 final String label = labelForType(a.type);
1038 long now = (a.type <= RTC) ? nowRTC : nowELAPSED;
1039 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1040 pw.print(": "); pw.println(a);
1041 a.dump(pw, prefix + " ", now);
1042 }
1043 }
1044
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001045 private native long init();
1046 private native void close(long nativeData);
1047 private native void set(long nativeData, int type, long seconds, long nanoseconds);
1048 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08001049 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001050 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051
Adam Lesinski182f73f2013-12-05 16:48:06 -08001052 void triggerAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED, long nowRTC) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001053 // batches are temporally sorted, so we need only pull from the
1054 // start of the list until we either empty it or hit a batch
1055 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07001056 while (mAlarmBatches.size() > 0) {
1057 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001058 if (batch.start > nowELAPSED) {
1059 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 break;
1061 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062
Christopher Tatee0a22b32013-07-11 14:43:13 -07001063 // We will (re)schedule some alarms now; don't let that interfere
1064 // with delivery of this current batch
1065 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001066
Christopher Tatee0a22b32013-07-11 14:43:13 -07001067 final int N = batch.size();
1068 for (int i = 0; i < N; i++) {
1069 Alarm alarm = batch.get(i);
1070 alarm.count = 1;
1071 triggerList.add(alarm);
1072
1073 // Recurring alarms may have passed several alarm intervals while the
1074 // phone was asleep or off, so pass a trigger count when sending them.
1075 if (alarm.repeatInterval > 0) {
1076 // this adjustment will be zero if we're late by
1077 // less than one full repeat interval
1078 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
1079
1080 // Also schedule its next recurrence
1081 final long delta = alarm.count * alarm.repeatInterval;
1082 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07001083 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07001084 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
David Christieebe51fc2013-07-26 13:23:29 -07001085 alarm.repeatInterval, alarm.operation, batch.standalone, true,
1086 alarm.workSource);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001087 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088
Dianne Hackborn390517b2013-05-30 15:03:32 -07001089 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 /**
1094 * This Comparator sorts Alarms into increasing time order.
1095 */
1096 public static class IncreasingTimeOrder implements Comparator<Alarm> {
1097 public int compare(Alarm a1, Alarm a2) {
1098 long when1 = a1.when;
1099 long when2 = a2.when;
1100 if (when1 - when2 > 0) {
1101 return 1;
1102 }
1103 if (when1 - when2 < 0) {
1104 return -1;
1105 }
1106 return 0;
1107 }
1108 }
1109
1110 private static class Alarm {
1111 public int type;
1112 public int count;
1113 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07001114 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001115 public long whenElapsed; // 'when' in the elapsed time base
1116 public long maxWhen; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 public long repeatInterval;
1118 public PendingIntent operation;
David Christieebe51fc2013-07-26 13:23:29 -07001119 public WorkSource workSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120
Christopher Tate3e04b472013-10-21 17:51:31 -07001121 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
David Christieebe51fc2013-07-26 13:23:29 -07001122 long _interval, PendingIntent _op, WorkSource _ws) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001123 type = _type;
1124 when = _when;
1125 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07001126 windowLength = _windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001127 maxWhen = _maxWhen;
1128 repeatInterval = _interval;
1129 operation = _op;
David Christieebe51fc2013-07-26 13:23:29 -07001130 workSource = _ws;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001132
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 @Override
1134 public String toString()
1135 {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001136 StringBuilder sb = new StringBuilder(128);
1137 sb.append("Alarm{");
1138 sb.append(Integer.toHexString(System.identityHashCode(this)));
1139 sb.append(" type ");
1140 sb.append(type);
1141 sb.append(" ");
1142 sb.append(operation.getTargetPackage());
1143 sb.append('}');
1144 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001145 }
1146
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001147 public void dump(PrintWriter pw, String prefix, long now) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001148 pw.print(prefix); pw.print("type="); pw.print(type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001149 pw.print(" whenElapsed="); pw.print(whenElapsed);
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001150 pw.print(" when="); TimeUtils.formatDuration(when, now, pw);
Christopher Tate3e04b472013-10-21 17:51:31 -07001151 pw.print(" window="); pw.print(windowLength);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001152 pw.print(" repeatInterval="); pw.print(repeatInterval);
1153 pw.print(" count="); pw.println(count);
1154 pw.print(prefix); pw.print("operation="); pw.println(operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155 }
1156 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001157
Christopher Tatee0a22b32013-07-11 14:43:13 -07001158 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
1159 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07001160 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
1161 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001162 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07001163 break;
1164 }
1165
Christopher Tatee0a22b32013-07-11 14:43:13 -07001166 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07001167 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
1168 Alarm a = b.alarms.get(nextAlarm);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001169 WakeupEvent e = new WakeupEvent(nowRTC,
1170 a.operation.getCreatorUid(),
1171 a.operation.getIntent().getAction());
1172 mRecentWakeups.add(e);
1173 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001174 }
1175 }
1176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001177 private class AlarmThread extends Thread
1178 {
1179 public AlarmThread()
1180 {
1181 super("AlarmManager");
1182 }
1183
1184 public void run()
1185 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07001186 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
1187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188 while (true)
1189 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001190 int result = waitForAlarm(mNativeData);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001191
1192 triggerList.clear();
1193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001194 if ((result & TIME_CHANGED_MASK) != 0) {
Christopher Tate385e4982013-07-23 18:22:29 -07001195 if (DEBUG_BATCH) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001196 Slog.v(TAG, "Time changed notification from kernel; rebatching");
Christopher Tate385e4982013-07-23 18:22:29 -07001197 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001198 removeImpl(mTimeTickSender);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001199 rebatchAllAlarms();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 mClockReceiver.scheduleTimeTickEvent();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001201 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
Dianne Hackborn89ba6752011-01-23 16:51:16 -08001202 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1203 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001204 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205 }
1206
1207 synchronized (mLock) {
1208 final long nowRTC = System.currentTimeMillis();
1209 final long nowELAPSED = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001210 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001211 TAG, "Checking for alarms... rtc=" + nowRTC
1212 + ", elapsed=" + nowELAPSED);
1213
Christopher Tate18a75f12013-07-01 18:18:59 -07001214 if (WAKEUP_STATS) {
1215 if ((result & IS_WAKEUP_MASK) != 0) {
1216 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
1217 int n = 0;
1218 for (WakeupEvent event : mRecentWakeups) {
1219 if (event.when > newEarliest) break;
1220 n++; // number of now-stale entries at the list head
1221 }
1222 for (int i = 0; i < n; i++) {
1223 mRecentWakeups.remove();
1224 }
1225
Christopher Tatee0a22b32013-07-11 14:43:13 -07001226 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Christopher Tate18a75f12013-07-01 18:18:59 -07001227 }
1228 }
1229
Christopher Tatee0a22b32013-07-11 14:43:13 -07001230 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
1231 rescheduleKernelAlarmsLocked();
1232
1233 // now deliver the alarm intents
Dianne Hackborn390517b2013-05-30 15:03:32 -07001234 for (int i=0; i<triggerList.size(); i++) {
1235 Alarm alarm = triggerList.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001236 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001237 if (localLOGV) Slog.v(TAG, "sending alarm " + alarm);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001238 alarm.operation.send(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239 mBackgroundIntent.putExtra(
1240 Intent.EXTRA_ALARM_COUNT, alarm.count),
1241 mResultReceiver, mHandler);
1242
Christopher Tatec4a07d12012-04-06 14:19:13 -07001243 // we have an active broadcast so stay awake.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001244 if (mBroadcastRefCount == 0) {
David Christieebe51fc2013-07-26 13:23:29 -07001245 setWakelockWorkSource(alarm.operation, alarm.workSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 mWakeLock.acquire();
1247 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001248 final InFlight inflight = new InFlight(AlarmManagerService.this,
David Christieebe51fc2013-07-26 13:23:29 -07001249 alarm.operation, alarm.workSource);
Dianne Hackborn81038902012-11-26 17:04:09 -08001250 mInFlight.add(inflight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001251 mBroadcastRefCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08001252
1253 final BroadcastStats bs = inflight.mBroadcastStats;
1254 bs.count++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 if (bs.nesting == 0) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001256 bs.nesting = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257 bs.startTime = nowELAPSED;
1258 } else {
1259 bs.nesting++;
1260 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001261 final FilterStats fs = inflight.mFilterStats;
1262 fs.count++;
1263 if (fs.nesting == 0) {
1264 fs.nesting = 1;
1265 fs.startTime = nowELAPSED;
1266 } else {
1267 fs.nesting++;
1268 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001269 if (alarm.type == ELAPSED_REALTIME_WAKEUP
1270 || alarm.type == RTC_WAKEUP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271 bs.numWakeup++;
Dianne Hackborn81038902012-11-26 17:04:09 -08001272 fs.numWakeup++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273 ActivityManagerNative.noteWakeupAlarm(
1274 alarm.operation);
1275 }
1276 } catch (PendingIntent.CanceledException e) {
1277 if (alarm.repeatInterval > 0) {
1278 // This IntentSender is no longer valid, but this
1279 // is a repeating alarm, so toss the hoser.
Adam Lesinski182f73f2013-12-05 16:48:06 -08001280 removeImpl(alarm.operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 }
1282 } catch (RuntimeException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001283 Slog.w(TAG, "Failure sending alarm.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 }
1285 }
1286 }
1287 }
1288 }
1289 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07001290
David Christieebe51fc2013-07-26 13:23:29 -07001291 /**
1292 * Attribute blame for a WakeLock.
1293 * @param pi PendingIntent to attribute blame to if ws is null.
1294 * @param ws WorkSource to attribute blame.
1295 */
1296 void setWakelockWorkSource(PendingIntent pi, WorkSource ws) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07001297 try {
David Christieebe51fc2013-07-26 13:23:29 -07001298 if (ws != null) {
1299 mWakeLock.setWorkSource(ws);
1300 return;
1301 }
1302
Christopher Tatec4a07d12012-04-06 14:19:13 -07001303 final int uid = ActivityManagerNative.getDefault()
1304 .getUidForIntentSender(pi.getTarget());
1305 if (uid >= 0) {
1306 mWakeLock.setWorkSource(new WorkSource(uid));
1307 return;
1308 }
1309 } catch (Exception e) {
1310 }
1311
1312 // Something went wrong; fall back to attributing the lock to the OS
1313 mWakeLock.setWorkSource(null);
1314 }
1315
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 private class AlarmHandler extends Handler {
1317 public static final int ALARM_EVENT = 1;
1318 public static final int MINUTE_CHANGE_EVENT = 2;
1319 public static final int DATE_CHANGE_EVENT = 3;
1320
1321 public AlarmHandler() {
1322 }
1323
1324 public void handleMessage(Message msg) {
1325 if (msg.what == ALARM_EVENT) {
1326 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
1327 synchronized (mLock) {
1328 final long nowRTC = System.currentTimeMillis();
Christopher Tatee0a22b32013-07-11 14:43:13 -07001329 final long nowELAPSED = SystemClock.elapsedRealtime();
1330 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 }
1332
1333 // now trigger the alarms without the lock held
Dianne Hackborn390517b2013-05-30 15:03:32 -07001334 for (int i=0; i<triggerList.size(); i++) {
1335 Alarm alarm = triggerList.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001336 try {
1337 alarm.operation.send();
1338 } catch (PendingIntent.CanceledException e) {
1339 if (alarm.repeatInterval > 0) {
1340 // This IntentSender is no longer valid, but this
1341 // is a repeating alarm, so toss the hoser.
Adam Lesinski182f73f2013-12-05 16:48:06 -08001342 removeImpl(alarm.operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 }
1344 }
1345 }
1346 }
1347 }
1348 }
1349
1350 class ClockReceiver extends BroadcastReceiver {
1351 public ClockReceiver() {
1352 IntentFilter filter = new IntentFilter();
1353 filter.addAction(Intent.ACTION_TIME_TICK);
1354 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001355 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 }
1357
1358 @Override
1359 public void onReceive(Context context, Intent intent) {
1360 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001361 if (DEBUG_BATCH) {
1362 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
1363 }
1364 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
1366 // Since the kernel does not keep track of DST, we need to
1367 // reset the TZ information at the beginning of each day
1368 // based off of the current Zone gmt offset + userspace tracked
1369 // daylight savings information.
1370 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02001371 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001372 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07001373 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 }
1375 }
1376
1377 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07001378 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09001379 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07001380
1381 // Schedule this event for the amount of time that it would take to get to
1382 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09001383 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07001384
David Christieebe51fc2013-07-26 13:23:29 -07001385 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08001386 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
David Christieebe51fc2013-07-26 13:23:29 -07001387 0, mTimeTickSender, true, workSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 }
Christopher Tate385e4982013-07-23 18:22:29 -07001389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 public void scheduleDateChangedEvent() {
1391 Calendar calendar = Calendar.getInstance();
1392 calendar.setTimeInMillis(System.currentTimeMillis());
1393 calendar.set(Calendar.HOUR, 0);
1394 calendar.set(Calendar.MINUTE, 0);
1395 calendar.set(Calendar.SECOND, 0);
1396 calendar.set(Calendar.MILLISECOND, 0);
1397 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07001398
1399 final WorkSource workSource = null; // Let system take blame for date change events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08001400 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, true, workSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 }
1402 }
1403
1404 class UninstallReceiver extends BroadcastReceiver {
1405 public UninstallReceiver() {
1406 IntentFilter filter = new IntentFilter();
1407 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1408 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001409 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08001411 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001412 // Register for events related to sdcard installation.
1413 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001414 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001415 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001416 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 }
1418
1419 @Override
1420 public void onReceive(Context context, Intent intent) {
1421 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001422 String action = intent.getAction();
1423 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001424 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
1425 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
1426 for (String packageName : pkgList) {
1427 if (lookForPackageLocked(packageName)) {
1428 setResultCode(Activity.RESULT_OK);
1429 return;
1430 }
1431 }
1432 return;
1433 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001434 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001435 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
1436 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
1437 if (userHandle >= 0) {
1438 removeUserLocked(userHandle);
1439 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001440 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08001441 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
1442 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
1443 // This package is being updated; don't kill its alarms.
1444 return;
1445 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001446 Uri data = intent.getData();
1447 if (data != null) {
1448 String pkg = data.getSchemeSpecificPart();
1449 if (pkg != null) {
1450 pkgList = new String[]{pkg};
1451 }
1452 }
1453 }
1454 if (pkgList != null && (pkgList.length > 0)) {
1455 for (String pkg : pkgList) {
1456 removeLocked(pkg);
1457 mBroadcastStats.remove(pkg);
1458 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 }
1460 }
1461 }
1462 }
1463
1464 private final BroadcastStats getStatsLocked(PendingIntent pi) {
1465 String pkg = pi.getTargetPackage();
1466 BroadcastStats bs = mBroadcastStats.get(pkg);
1467 if (bs == null) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001468 bs = new BroadcastStats(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 mBroadcastStats.put(pkg, bs);
1470 }
1471 return bs;
1472 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 class ResultReceiver implements PendingIntent.OnFinished {
1475 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
1476 String resultData, Bundle resultExtras) {
1477 synchronized (mLock) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001478 InFlight inflight = null;
1479 for (int i=0; i<mInFlight.size(); i++) {
1480 if (mInFlight.get(i).mPendingIntent == pi) {
1481 inflight = mInFlight.remove(i);
1482 break;
1483 }
1484 }
1485 if (inflight != null) {
1486 final long nowELAPSED = SystemClock.elapsedRealtime();
1487 BroadcastStats bs = inflight.mBroadcastStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 bs.nesting--;
1489 if (bs.nesting <= 0) {
1490 bs.nesting = 0;
Dianne Hackborn81038902012-11-26 17:04:09 -08001491 bs.aggregateTime += nowELAPSED - bs.startTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001493 FilterStats fs = inflight.mFilterStats;
1494 fs.nesting--;
1495 if (fs.nesting <= 0) {
1496 fs.nesting = 0;
1497 fs.aggregateTime += nowELAPSED - fs.startTime;
1498 }
1499 } else {
1500 mLog.w("No in-flight alarm for " + pi + " " + intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 }
1502 mBroadcastRefCount--;
1503 if (mBroadcastRefCount == 0) {
1504 mWakeLock.release();
Dianne Hackborn81038902012-11-26 17:04:09 -08001505 if (mInFlight.size() > 0) {
1506 mLog.w("Finished all broadcasts with " + mInFlight.size()
1507 + " remaining inflights");
1508 for (int i=0; i<mInFlight.size(); i++) {
1509 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
1510 }
1511 mInFlight.clear();
1512 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07001513 } else {
1514 // the next of our alarms is now in flight. reattribute the wakelock.
Dianne Hackborn81038902012-11-26 17:04:09 -08001515 if (mInFlight.size() > 0) {
David Christieebe51fc2013-07-26 13:23:29 -07001516 InFlight inFlight = mInFlight.get(0);
1517 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource);
Christopher Tatec4a07d12012-04-06 14:19:13 -07001518 } else {
1519 // should never happen
Dianne Hackborn81038902012-11-26 17:04:09 -08001520 mLog.w("Alarm wakelock still held but sent queue empty");
Christopher Tatec4a07d12012-04-06 14:19:13 -07001521 mWakeLock.setWorkSource(null);
1522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 }
1524 }
1525 }
1526 }
1527}