blob: eb347bb443f00261cf0669fa5e9c1f3426155533 [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 Hackborn3d658bf2014-02-05 13:38:56 -080042import android.util.ArrayMap;
Dianne Hackborn81038902012-11-26 17:04:09 -080043import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -080044import android.util.Slog;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080045import android.util.SparseArray;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070046import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047
Christopher Tate4cb338d2013-07-26 13:11:31 -070048import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import java.io.FileDescriptor;
50import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070051import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -080053import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import java.util.Calendar;
55import java.util.Collections;
56import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -050057import java.util.Date;
Christopher Tate18a75f12013-07-01 18:18:59 -070058import java.util.LinkedList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import 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 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800316
317 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
318 @Override
319 public int compare(Alarm lhs, Alarm rhs) {
320 if (lhs.wakeup != rhs.wakeup) {
321 return lhs.wakeup ? -1 : 1;
322 }
323 if (lhs.whenElapsed < rhs.whenElapsed) {
324 return -1;
325 } else if (lhs.whenElapsed > rhs.whenElapsed) {
326 return 1;
327 }
328 return 0;
329 }
330 };
331
Christopher Tatee0a22b32013-07-11 14:43:13 -0700332 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800333 static final long MIN_FUZZABLE_INTERVAL = 10000;
334 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
335 final ArrayList<Batch> mAlarmBatches = new ArrayList<Batch>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700336
337 static long convertToElapsed(long when, int type) {
338 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
339 if (isRtc) {
340 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
341 }
342 return when;
343 }
344
345 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
346 // calculate the end of our nominal delivery window for the alarm.
347 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
348 // Current heuristic: batchable window is 75% of either the recurrence interval
349 // [for a periodic alarm] or of the time from now to the desired delivery time,
350 // with a minimum delay/interval of 10 seconds, under which we will simply not
351 // defer the alarm.
352 long futurity = (interval == 0)
353 ? (triggerAtTime - now)
354 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700355 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700356 futurity = 0;
357 }
358 return triggerAtTime + (long)(.75 * futurity);
359 }
360
361 // returns true if the batch was added at the head
362 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
363 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
364 if (index < 0) {
365 index = 0 - index - 1;
366 }
367 list.add(index, newBatch);
368 return (index == 0);
369 }
370
Christopher Tate385e4982013-07-23 18:22:29 -0700371 // Return the index of the matching batch, or -1 if none found.
372 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700373 final int N = mAlarmBatches.size();
374 for (int i = 0; i < N; i++) {
375 Batch b = mAlarmBatches.get(i);
376 if (!b.standalone && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700377 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700378 }
379 }
Christopher Tate385e4982013-07-23 18:22:29 -0700380 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700381 }
382
383 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
384 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700385 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700386 rebatchAllAlarmsLocked(true);
387 }
388 }
389
390 void rebatchAllAlarmsLocked(boolean doValidate) {
391 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
392 mAlarmBatches.clear();
393 final long nowElapsed = SystemClock.elapsedRealtime();
394 final int oldBatches = oldSet.size();
395 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
396 Batch batch = oldSet.get(batchNum);
397 final int N = batch.size();
398 for (int i = 0; i < N; i++) {
399 Alarm a = batch.get(i);
400 long whenElapsed = convertToElapsed(a.when, a.type);
Christopher Tate3e04b472013-10-21 17:51:31 -0700401 final long maxElapsed;
402 if (a.whenElapsed == a.maxWhen) {
403 // Exact
404 maxElapsed = whenElapsed;
405 } else {
406 // Not exact. Preserve any explicit window, otherwise recalculate
407 // the window based on the alarm's new futurity. Note that this
408 // reflects a policy of preferring timely to deferred delivery.
409 maxElapsed = (a.windowLength > 0)
410 ? (whenElapsed + a.windowLength)
411 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
412 }
413 setImplLocked(a.type, a.when, whenElapsed, a.windowLength, maxElapsed,
David Christieebe51fc2013-07-26 13:23:29 -0700414 a.repeatInterval, a.operation, batch.standalone, doValidate, a.workSource);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700415 }
416 }
417 }
418
Adam Lesinski182f73f2013-12-05 16:48:06 -0800419 static final class InFlight extends Intent {
Dianne Hackborn81038902012-11-26 17:04:09 -0800420 final PendingIntent mPendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700421 final WorkSource mWorkSource;
Dianne Hackborn81038902012-11-26 17:04:09 -0800422 final Pair<String, ComponentName> mTarget;
423 final BroadcastStats mBroadcastStats;
424 final FilterStats mFilterStats;
425
David Christieebe51fc2013-07-26 13:23:29 -0700426 InFlight(AlarmManagerService service, PendingIntent pendingIntent, WorkSource workSource) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800427 mPendingIntent = pendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700428 mWorkSource = workSource;
Dianne Hackborn81038902012-11-26 17:04:09 -0800429 Intent intent = pendingIntent.getIntent();
430 mTarget = intent != null
431 ? new Pair<String, ComponentName>(intent.getAction(), intent.getComponent())
432 : null;
433 mBroadcastStats = service.getStatsLocked(pendingIntent);
434 FilterStats fs = mBroadcastStats.filterStats.get(mTarget);
435 if (fs == null) {
436 fs = new FilterStats(mBroadcastStats, mTarget);
437 mBroadcastStats.filterStats.put(mTarget, fs);
438 }
439 mFilterStats = fs;
440 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800441 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800442
Adam Lesinski182f73f2013-12-05 16:48:06 -0800443 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -0800444 final BroadcastStats mBroadcastStats;
445 final Pair<String, ComponentName> mTarget;
446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800448 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800449 int numWakeup;
450 long startTime;
451 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -0800452
453 FilterStats(BroadcastStats broadcastStats, Pair<String, ComponentName> target) {
454 mBroadcastStats = broadcastStats;
455 mTarget = target;
456 }
457 }
458
Adam Lesinski182f73f2013-12-05 16:48:06 -0800459 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800460 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800461 final String mPackageName;
462
463 long aggregateTime;
464 int count;
465 int numWakeup;
466 long startTime;
467 int nesting;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800468 final ArrayMap<Pair<String, ComponentName>, FilterStats> filterStats
469 = new ArrayMap<Pair<String, ComponentName>, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -0800470
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800471 BroadcastStats(int uid, String packageName) {
472 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800473 mPackageName = packageName;
474 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800475 }
476
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800477 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
478 = new SparseArray<ArrayMap<String, BroadcastStats>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800479
Adam Lesinski182f73f2013-12-05 16:48:06 -0800480 @Override
481 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800482 mNativeData = init();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700483 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800484
485 // We have to set current TimeZone info to kernel
486 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -0800487 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800488
Adam Lesinski182f73f2013-12-05 16:48:06 -0800489 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800490 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800491
Adam Lesinski182f73f2013-12-05 16:48:06 -0800492 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800493 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700494 Intent.FLAG_RECEIVER_REGISTERED_ONLY
495 | Intent.FLAG_RECEIVER_FOREGROUND), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700496 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800497 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
498 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800499 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700500 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800501
502 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -0800503 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 mClockReceiver.scheduleTimeTickEvent();
505 mClockReceiver.scheduleDateChangedEvent();
506 mUninstallReceiver = new UninstallReceiver();
507
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800508 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800509 AlarmThread waitThread = new AlarmThread();
510 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800511 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800512 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800514
515 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800516 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800517
518 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800519 protected void finalize() throws Throwable {
520 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800521 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800522 } finally {
523 super.finalize();
524 }
525 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700526
Adam Lesinski182f73f2013-12-05 16:48:06 -0800527 void setTimeZoneImpl(String tz) {
528 if (TextUtils.isEmpty(tz)) {
529 return;
David Christieebe51fc2013-07-26 13:23:29 -0700530 }
531
Adam Lesinski182f73f2013-12-05 16:48:06 -0800532 TimeZone zone = TimeZone.getTimeZone(tz);
533 // Prevent reentrant calls from stepping on each other when writing
534 // the time zone property
535 boolean timeZoneWasChanged = false;
536 synchronized (this) {
537 String current = SystemProperties.get(TIMEZONE_PROPERTY);
538 if (current == null || !current.equals(zone.getID())) {
539 if (localLOGV) {
540 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
541 }
542 timeZoneWasChanged = true;
543 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
544 }
545
546 // Update the kernel timezone information
547 // Kernel tracks time offsets as 'minutes west of GMT'
548 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800549 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -0800550 }
551
552 TimeZone.setDefault(null);
553
554 if (timeZoneWasChanged) {
555 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
556 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
557 intent.putExtra("time-zone", zone.getID());
558 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
559 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700561
Adam Lesinski182f73f2013-12-05 16:48:06 -0800562 void removeImpl(PendingIntent operation) {
563 if (operation == null) {
564 return;
565 }
566 synchronized (mLock) {
567 removeLocked(operation);
568 }
569 }
570
571 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
David Christieebe51fc2013-07-26 13:23:29 -0700572 PendingIntent operation, boolean isStandalone, WorkSource workSource) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800573 if (operation == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800574 Slog.w(TAG, "set/setRepeating ignored because there is no intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 return;
576 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700577
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700578 // Sanity check the window length. This will catch people mistakenly
579 // trying to pass an end-of-window timestamp rather than a duration.
580 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
581 Slog.w(TAG, "Window length " + windowLength
582 + "ms suspiciously long; limiting to 1 hour");
583 windowLength = AlarmManager.INTERVAL_HOUR;
584 }
585
Christopher Tatee0a22b32013-07-11 14:43:13 -0700586 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
587 throw new IllegalArgumentException("Invalid alarm type " + type);
588 }
589
Christopher Tate5f221e82013-07-30 17:13:15 -0700590 if (triggerAtTime < 0) {
591 final long who = Binder.getCallingUid();
592 final long what = Binder.getCallingPid();
593 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + who
594 + " pid=" + what);
595 triggerAtTime = 0;
596 }
597
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700598 final long nowElapsed = SystemClock.elapsedRealtime();
599 final long triggerElapsed = convertToElapsed(triggerAtTime, type);
600 final long maxElapsed;
601 if (windowLength == AlarmManager.WINDOW_EXACT) {
602 maxElapsed = triggerElapsed;
603 } else if (windowLength < 0) {
604 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
605 } else {
606 maxElapsed = triggerElapsed + windowLength;
607 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800609 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700610 if (DEBUG_BATCH) {
611 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700612 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -0700613 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
614 + " interval=" + interval + " standalone=" + isStandalone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800615 }
Christopher Tate3e04b472013-10-21 17:51:31 -0700616 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
David Christieebe51fc2013-07-26 13:23:29 -0700617 interval, operation, isStandalone, true, workSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 }
619 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800620
Christopher Tate3e04b472013-10-21 17:51:31 -0700621 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
622 long maxWhen, long interval, PendingIntent operation, boolean isStandalone,
623 boolean doValidate, WorkSource workSource) {
624 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
625 operation, workSource);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700626 removeLocked(operation);
Christopher Tateb8849c12011-02-08 13:39:01 -0800627
Christopher Tate385e4982013-07-23 18:22:29 -0700628 int whichBatch = (isStandalone) ? -1 : attemptCoalesceLocked(whenElapsed, maxWhen);
629 if (whichBatch < 0) {
630 Batch batch = new Batch(a);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700631 batch.standalone = isStandalone;
Christopher Tate7d57ed82013-10-25 20:18:03 -0700632 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633 } else {
Christopher Tate385e4982013-07-23 18:22:29 -0700634 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -0700635 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700636 // The start time of this batch advanced, so batch ordering may
637 // have just been broken. Move it to where it now belongs.
638 mAlarmBatches.remove(whichBatch);
639 addBatchLocked(mAlarmBatches, batch);
640 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800641 }
642
Christopher Tate4cb338d2013-07-26 13:11:31 -0700643 if (DEBUG_VALIDATE) {
Christopher Tate5f221e82013-07-30 17:13:15 -0700644 if (doValidate && !validateConsistencyLocked()) {
645 Slog.v(TAG, "Tipping-point operation: type=" + type + " when=" + when
646 + " when(hex)=" + Long.toHexString(when)
647 + " whenElapsed=" + whenElapsed + " maxWhen=" + maxWhen
648 + " interval=" + interval + " op=" + operation
649 + " standalone=" + isStandalone);
Christopher Tate4cb338d2013-07-26 13:11:31 -0700650 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -0700651 }
652 }
653
Christopher Tate7d57ed82013-10-25 20:18:03 -0700654 rescheduleKernelAlarmsLocked();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700655 }
656
Adam Lesinski182f73f2013-12-05 16:48:06 -0800657 private final IBinder mService = new IAlarmManager.Stub() {
658 @Override
659 public void set(int type, long triggerAtTime, long windowLength, long interval,
660 PendingIntent operation, WorkSource workSource) {
661 if (workSource != null) {
662 getContext().enforceCallingPermission(
663 android.Manifest.permission.UPDATE_DEVICE_STATS,
664 "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -0700665 }
666
Adam Lesinski182f73f2013-12-05 16:48:06 -0800667 setImpl(type, triggerAtTime, windowLength, interval, operation,
668 false, workSource);
669 }
Christopher Tate89779822012-08-31 14:40:03 -0700670
Adam Lesinski182f73f2013-12-05 16:48:06 -0800671 @Override
672 public void setTime(long millis) {
673 getContext().enforceCallingOrSelfPermission(
674 "android.permission.SET_TIME",
675 "setTime");
676
677 SystemClock.setCurrentTimeMillis(millis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800679
680 @Override
681 public void setTimeZone(String tz) {
682 getContext().enforceCallingOrSelfPermission(
683 "android.permission.SET_TIME_ZONE",
684 "setTimeZone");
685
686 final long oldId = Binder.clearCallingIdentity();
687 try {
688 setTimeZoneImpl(tz);
689 } finally {
690 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 }
692 }
Christopher Tate4cb338d2013-07-26 13:11:31 -0700693
Adam Lesinski182f73f2013-12-05 16:48:06 -0800694 @Override
695 public void remove(PendingIntent operation) {
696 removeImpl(operation);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698 }
Christopher Tate4cb338d2013-07-26 13:11:31 -0700699
Adam Lesinski182f73f2013-12-05 16:48:06 -0800700 @Override
701 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
702 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
703 != PackageManager.PERMISSION_GRANTED) {
704 pw.println("Permission Denial: can't dump AlarmManager from from pid="
705 + Binder.getCallingPid()
706 + ", uid=" + Binder.getCallingUid());
707 return;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700708 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700709
Adam Lesinski182f73f2013-12-05 16:48:06 -0800710 dumpImpl(pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700711 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800712 };
Christopher Tate4cb338d2013-07-26 13:11:31 -0700713
Adam Lesinski182f73f2013-12-05 16:48:06 -0800714 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 synchronized (mLock) {
716 pw.println("Current Alarm Manager state:");
Christopher Tatee0a22b32013-07-11 14:43:13 -0700717 final long nowRTC = System.currentTimeMillis();
718 final long nowELAPSED = SystemClock.elapsedRealtime();
719 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
720
721 pw.print("nowRTC="); pw.print(nowRTC);
722 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
723 pw.print(" nowELAPSED="); pw.println(nowELAPSED);
724
725 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
726 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
727 pw.print("Next alarm: "); pw.print(mNextNonWakeup);
728 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
729 pw.print("Next wakeup: "); pw.print(mNextWakeup);
730 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
731
732 if (mAlarmBatches.size() > 0) {
733 pw.println();
734 pw.print("Pending alarm batches: ");
735 pw.println(mAlarmBatches.size());
736 for (Batch b : mAlarmBatches) {
737 pw.print(b); pw.println(':');
738 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC);
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700739 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800741
742 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700743 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -0800744 pw.println();
745
746 if (mLog.dump(pw, " Recent problems", " ")) {
747 pw.println();
748 }
749
750 final FilterStats[] topFilters = new FilterStats[10];
751 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
752 @Override
753 public int compare(FilterStats lhs, FilterStats rhs) {
754 if (lhs.aggregateTime < rhs.aggregateTime) {
755 return 1;
756 } else if (lhs.aggregateTime > rhs.aggregateTime) {
757 return -1;
758 }
759 return 0;
760 }
761 };
762 int len = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800763 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
764 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
765 for (int ip=0; ip<uidStats.size(); ip++) {
766 BroadcastStats bs = uidStats.valueAt(ip);
767 for (int is=0; is<bs.filterStats.size(); is++) {
768 FilterStats fs = bs.filterStats.valueAt(is);
769 int pos = len > 0
770 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
771 if (pos < 0) {
772 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -0800773 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800774 if (pos < topFilters.length) {
775 int copylen = topFilters.length - pos - 1;
776 if (copylen > 0) {
777 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
778 }
779 topFilters[pos] = fs;
780 if (len < topFilters.length) {
781 len++;
782 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800783 }
784 }
785 }
786 }
787 if (len > 0) {
788 pw.println(" Top Alarms:");
789 for (int i=0; i<len; i++) {
790 FilterStats fs = topFilters[i];
791 pw.print(" ");
792 if (fs.nesting > 0) pw.print("*ACTIVE* ");
793 TimeUtils.formatDuration(fs.aggregateTime, pw);
794 pw.print(" running, "); pw.print(fs.numWakeup);
795 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800796 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
797 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -0800798 pw.println();
799 pw.print(" ");
800 if (fs.mTarget.first != null) {
801 pw.print(" act="); pw.print(fs.mTarget.first);
802 }
803 if (fs.mTarget.second != null) {
804 pw.print(" cmp="); pw.print(fs.mTarget.second.toShortString());
805 }
806 pw.println();
807 }
808 }
809
810 pw.println(" ");
811 pw.println(" Alarm Stats:");
812 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800813 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
814 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
815 for (int ip=0; ip<uidStats.size(); ip++) {
816 BroadcastStats bs = uidStats.valueAt(ip);
817 pw.print(" ");
818 if (bs.nesting > 0) pw.print("*ACTIVE* ");
819 UserHandle.formatUid(pw, bs.mUid);
820 pw.print(":");
821 pw.print(bs.mPackageName);
822 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
823 pw.print(" running, "); pw.print(bs.numWakeup);
824 pw.println(" wakeups:");
825 tmpFilters.clear();
826 for (int is=0; is<bs.filterStats.size(); is++) {
827 tmpFilters.add(bs.filterStats.valueAt(is));
828 }
829 Collections.sort(tmpFilters, comparator);
830 for (int i=0; i<tmpFilters.size(); i++) {
831 FilterStats fs = tmpFilters.get(i);
832 pw.print(" ");
833 if (fs.nesting > 0) pw.print("*ACTIVE* ");
834 TimeUtils.formatDuration(fs.aggregateTime, pw);
835 pw.print(" "); pw.print(fs.numWakeup);
836 pw.print(" wakes " ); pw.print(fs.count);
837 pw.print(" alarms:");
838 if (fs.mTarget.first != null) {
839 pw.print(" act="); pw.print(fs.mTarget.first);
840 }
841 if (fs.mTarget.second != null) {
842 pw.print(" cmp="); pw.print(fs.mTarget.second.toShortString());
843 }
844 pw.println();
845 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 }
847 }
Christopher Tate18a75f12013-07-01 18:18:59 -0700848
849 if (WAKEUP_STATS) {
850 pw.println();
851 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -0700852 long last = -1;
853 for (WakeupEvent event : mRecentWakeups) {
854 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
855 pw.print('|');
856 if (last < 0) {
857 pw.print('0');
858 } else {
859 pw.print(event.when - last);
860 }
861 last = event.when;
862 pw.print('|'); pw.print(event.uid);
863 pw.print('|'); pw.print(event.action);
864 pw.println();
865 }
866 pw.println();
867 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 }
869 }
870
Adam Lesinski182f73f2013-12-05 16:48:06 -0800871 private void logBatchesLocked() {
872 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
873 PrintWriter pw = new PrintWriter(bs);
874 final long nowRTC = System.currentTimeMillis();
875 final long nowELAPSED = SystemClock.elapsedRealtime();
876 final int NZ = mAlarmBatches.size();
877 for (int iz = 0; iz < NZ; iz++) {
878 Batch bz = mAlarmBatches.get(iz);
879 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
880 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC);
881 pw.flush();
882 Slog.v(TAG, bs.toString());
883 bs.reset();
884 }
885 }
886
887 private boolean validateConsistencyLocked() {
888 if (DEBUG_VALIDATE) {
889 long lastTime = Long.MIN_VALUE;
890 final int N = mAlarmBatches.size();
891 for (int i = 0; i < N; i++) {
892 Batch b = mAlarmBatches.get(i);
893 if (b.start >= lastTime) {
894 // duplicate start times are okay because of standalone batches
895 lastTime = b.start;
896 } else {
897 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
898 logBatchesLocked();
899 return false;
900 }
901 }
902 }
903 return true;
904 }
905
906 private Batch findFirstWakeupBatchLocked() {
907 final int N = mAlarmBatches.size();
908 for (int i = 0; i < N; i++) {
909 Batch b = mAlarmBatches.get(i);
910 if (b.hasWakeups()) {
911 return b;
912 }
913 }
914 return null;
915 }
916
917 void rescheduleKernelAlarmsLocked() {
918 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
919 // prior to that which contains no wakeups, we schedule that as well.
920 if (mAlarmBatches.size() > 0) {
921 final Batch firstWakeup = findFirstWakeupBatchLocked();
922 final Batch firstBatch = mAlarmBatches.get(0);
923 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
924 mNextWakeup = firstWakeup.start;
925 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
926 }
927 if (firstBatch != firstWakeup && mNextNonWakeup != firstBatch.start) {
928 mNextNonWakeup = firstBatch.start;
929 setLocked(ELAPSED_REALTIME, firstBatch.start);
930 }
931 }
932 }
933
934 private void removeLocked(PendingIntent operation) {
935 boolean didRemove = false;
936 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
937 Batch b = mAlarmBatches.get(i);
938 didRemove |= b.remove(operation);
939 if (b.size() == 0) {
940 mAlarmBatches.remove(i);
941 }
942 }
943
944 if (didRemove) {
945 if (DEBUG_BATCH) {
946 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
947 }
948 rebatchAllAlarmsLocked(true);
949 rescheduleKernelAlarmsLocked();
950 }
951 }
952
953 void removeLocked(String packageName) {
954 boolean didRemove = false;
955 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
956 Batch b = mAlarmBatches.get(i);
957 didRemove |= b.remove(packageName);
958 if (b.size() == 0) {
959 mAlarmBatches.remove(i);
960 }
961 }
962
963 if (didRemove) {
964 if (DEBUG_BATCH) {
965 Slog.v(TAG, "remove(package) changed bounds; rebatching");
966 }
967 rebatchAllAlarmsLocked(true);
968 rescheduleKernelAlarmsLocked();
969 }
970 }
971
972 void removeUserLocked(int userHandle) {
973 boolean didRemove = false;
974 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
975 Batch b = mAlarmBatches.get(i);
976 didRemove |= b.remove(userHandle);
977 if (b.size() == 0) {
978 mAlarmBatches.remove(i);
979 }
980 }
981
982 if (didRemove) {
983 if (DEBUG_BATCH) {
984 Slog.v(TAG, "remove(user) changed bounds; rebatching");
985 }
986 rebatchAllAlarmsLocked(true);
987 rescheduleKernelAlarmsLocked();
988 }
989 }
990
991 boolean lookForPackageLocked(String packageName) {
992 for (int i = 0; i < mAlarmBatches.size(); i++) {
993 Batch b = mAlarmBatches.get(i);
994 if (b.hasPackage(packageName)) {
995 return true;
996 }
997 }
998 return false;
999 }
1000
1001 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001002 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001003 // The kernel never triggers alarms with negative wakeup times
1004 // so we ensure they are positive.
1005 long alarmSeconds, alarmNanoseconds;
1006 if (when < 0) {
1007 alarmSeconds = 0;
1008 alarmNanoseconds = 0;
1009 } else {
1010 alarmSeconds = when / 1000;
1011 alarmNanoseconds = (when % 1000) * 1000 * 1000;
1012 }
1013
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001014 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001015 } else {
1016 Message msg = Message.obtain();
1017 msg.what = ALARM_EVENT;
1018
1019 mHandler.removeMessages(ALARM_EVENT);
1020 mHandler.sendMessageAtTime(msg, when);
1021 }
1022 }
1023
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001024 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
1025 String prefix, String label, long now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026 for (int i=list.size()-1; i>=0; i--) {
1027 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001028 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1029 pw.print(": "); pw.println(a);
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001030 a.dump(pw, prefix + " ", now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 }
1032 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001033
1034 private static final String labelForType(int type) {
1035 switch (type) {
1036 case RTC: return "RTC";
1037 case RTC_WAKEUP : return "RTC_WAKEUP";
1038 case ELAPSED_REALTIME : return "ELAPSED";
1039 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
1040 default:
1041 break;
1042 }
1043 return "--unknown--";
1044 }
1045
1046 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
1047 String prefix, long nowELAPSED, long nowRTC) {
1048 for (int i=list.size()-1; i>=0; i--) {
1049 Alarm a = list.get(i);
1050 final String label = labelForType(a.type);
1051 long now = (a.type <= RTC) ? nowRTC : nowELAPSED;
1052 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1053 pw.print(": "); pw.println(a);
1054 a.dump(pw, prefix + " ", now);
1055 }
1056 }
1057
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001058 private native long init();
1059 private native void close(long nativeData);
1060 private native void set(long nativeData, int type, long seconds, long nanoseconds);
1061 private native int waitForAlarm(long nativeData);
1062 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001064 void triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
1065 final long nowRTC) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001066 // batches are temporally sorted, so we need only pull from the
1067 // start of the list until we either empty it or hit a batch
1068 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07001069 while (mAlarmBatches.size() > 0) {
1070 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001071 if (batch.start > nowELAPSED) {
1072 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 break;
1074 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075
Christopher Tatee0a22b32013-07-11 14:43:13 -07001076 // We will (re)schedule some alarms now; don't let that interfere
1077 // with delivery of this current batch
1078 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001079
Christopher Tatee0a22b32013-07-11 14:43:13 -07001080 final int N = batch.size();
1081 for (int i = 0; i < N; i++) {
1082 Alarm alarm = batch.get(i);
1083 alarm.count = 1;
1084 triggerList.add(alarm);
1085
1086 // Recurring alarms may have passed several alarm intervals while the
1087 // phone was asleep or off, so pass a trigger count when sending them.
1088 if (alarm.repeatInterval > 0) {
1089 // this adjustment will be zero if we're late by
1090 // less than one full repeat interval
1091 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
1092
1093 // Also schedule its next recurrence
1094 final long delta = alarm.count * alarm.repeatInterval;
1095 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07001096 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07001097 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
David Christieebe51fc2013-07-26 13:23:29 -07001098 alarm.repeatInterval, alarm.operation, batch.standalone, true,
1099 alarm.workSource);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001100 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001101
Dianne Hackborn390517b2013-05-30 15:03:32 -07001102 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001104
1105 Collections.sort(triggerList, mAlarmDispatchComparator);
1106
1107 if (localLOGV) {
1108 for (int i=0; i<triggerList.size(); i++) {
1109 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
1110 }
1111 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001114 /**
1115 * This Comparator sorts Alarms into increasing time order.
1116 */
1117 public static class IncreasingTimeOrder implements Comparator<Alarm> {
1118 public int compare(Alarm a1, Alarm a2) {
1119 long when1 = a1.when;
1120 long when2 = a2.when;
1121 if (when1 - when2 > 0) {
1122 return 1;
1123 }
1124 if (when1 - when2 < 0) {
1125 return -1;
1126 }
1127 return 0;
1128 }
1129 }
1130
1131 private static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001132 public final int type;
1133 public final boolean wakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 public int count;
1135 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07001136 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001137 public long whenElapsed; // 'when' in the elapsed time base
1138 public long maxWhen; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139 public long repeatInterval;
1140 public PendingIntent operation;
David Christieebe51fc2013-07-26 13:23:29 -07001141 public WorkSource workSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142
Christopher Tate3e04b472013-10-21 17:51:31 -07001143 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
David Christieebe51fc2013-07-26 13:23:29 -07001144 long _interval, PendingIntent _op, WorkSource _ws) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001145 type = _type;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001146 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
1147 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001148 when = _when;
1149 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07001150 windowLength = _windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001151 maxWhen = _maxWhen;
1152 repeatInterval = _interval;
1153 operation = _op;
David Christieebe51fc2013-07-26 13:23:29 -07001154 workSource = _ws;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157 @Override
1158 public String toString()
1159 {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001160 StringBuilder sb = new StringBuilder(128);
1161 sb.append("Alarm{");
1162 sb.append(Integer.toHexString(System.identityHashCode(this)));
1163 sb.append(" type ");
1164 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001165 sb.append(" when ");
1166 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001167 sb.append(" ");
1168 sb.append(operation.getTargetPackage());
1169 sb.append('}');
1170 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171 }
1172
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001173 public void dump(PrintWriter pw, String prefix, long now) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001174 pw.print(prefix); pw.print("type="); pw.print(type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001175 pw.print(" whenElapsed="); pw.print(whenElapsed);
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001176 pw.print(" when="); TimeUtils.formatDuration(when, now, pw);
Christopher Tate3e04b472013-10-21 17:51:31 -07001177 pw.print(" window="); pw.print(windowLength);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001178 pw.print(" repeatInterval="); pw.print(repeatInterval);
1179 pw.print(" count="); pw.println(count);
1180 pw.print(prefix); pw.print("operation="); pw.println(operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 }
1182 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001183
Christopher Tatee0a22b32013-07-11 14:43:13 -07001184 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
1185 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07001186 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
1187 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001188 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07001189 break;
1190 }
1191
Christopher Tatee0a22b32013-07-11 14:43:13 -07001192 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07001193 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
1194 Alarm a = b.alarms.get(nextAlarm);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001195 WakeupEvent e = new WakeupEvent(nowRTC,
1196 a.operation.getCreatorUid(),
1197 a.operation.getIntent().getAction());
1198 mRecentWakeups.add(e);
1199 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001200 }
1201 }
1202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001203 private class AlarmThread extends Thread
1204 {
1205 public AlarmThread()
1206 {
1207 super("AlarmManager");
1208 }
1209
1210 public void run()
1211 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07001212 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
1213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 while (true)
1215 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001216 int result = waitForAlarm(mNativeData);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001217
1218 triggerList.clear();
1219
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001220 if ((result & TIME_CHANGED_MASK) != 0) {
Christopher Tate385e4982013-07-23 18:22:29 -07001221 if (DEBUG_BATCH) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001222 Slog.v(TAG, "Time changed notification from kernel; rebatching");
Christopher Tate385e4982013-07-23 18:22:29 -07001223 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001224 removeImpl(mTimeTickSender);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001225 rebatchAllAlarms();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226 mClockReceiver.scheduleTimeTickEvent();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001227 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
Dianne Hackborn89ba6752011-01-23 16:51:16 -08001228 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1229 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001230 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 }
1232
1233 synchronized (mLock) {
1234 final long nowRTC = System.currentTimeMillis();
1235 final long nowELAPSED = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001236 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237 TAG, "Checking for alarms... rtc=" + nowRTC
1238 + ", elapsed=" + nowELAPSED);
1239
Christopher Tate18a75f12013-07-01 18:18:59 -07001240 if (WAKEUP_STATS) {
1241 if ((result & IS_WAKEUP_MASK) != 0) {
1242 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
1243 int n = 0;
1244 for (WakeupEvent event : mRecentWakeups) {
1245 if (event.when > newEarliest) break;
1246 n++; // number of now-stale entries at the list head
1247 }
1248 for (int i = 0; i < n; i++) {
1249 mRecentWakeups.remove();
1250 }
1251
Christopher Tatee0a22b32013-07-11 14:43:13 -07001252 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Christopher Tate18a75f12013-07-01 18:18:59 -07001253 }
1254 }
1255
Christopher Tatee0a22b32013-07-11 14:43:13 -07001256 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
1257 rescheduleKernelAlarmsLocked();
1258
1259 // now deliver the alarm intents
Dianne Hackborn390517b2013-05-30 15:03:32 -07001260 for (int i=0; i<triggerList.size(); i++) {
1261 Alarm alarm = triggerList.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001263 if (localLOGV) Slog.v(TAG, "sending alarm " + alarm);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001264 alarm.operation.send(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265 mBackgroundIntent.putExtra(
1266 Intent.EXTRA_ALARM_COUNT, alarm.count),
1267 mResultReceiver, mHandler);
1268
Christopher Tatec4a07d12012-04-06 14:19:13 -07001269 // we have an active broadcast so stay awake.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 if (mBroadcastRefCount == 0) {
David Christieebe51fc2013-07-26 13:23:29 -07001271 setWakelockWorkSource(alarm.operation, alarm.workSource);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001272 mWakeLock.setUnimportantForLogging(
1273 alarm.operation == mTimeTickSender);
1274 // XXX debugging
1275 /*
1276 Intent intent = alarm.operation.getIntent();
1277 mWakeLock.setTag(intent.getAction() != null ? intent.getAction()
1278 : (intent.getComponent() != null
1279 ? intent.getComponent().toShortString() : TAG));
1280 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 mWakeLock.acquire();
1282 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001283 final InFlight inflight = new InFlight(AlarmManagerService.this,
David Christieebe51fc2013-07-26 13:23:29 -07001284 alarm.operation, alarm.workSource);
Dianne Hackborn81038902012-11-26 17:04:09 -08001285 mInFlight.add(inflight);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 mBroadcastRefCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08001287
1288 final BroadcastStats bs = inflight.mBroadcastStats;
1289 bs.count++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 if (bs.nesting == 0) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001291 bs.nesting = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 bs.startTime = nowELAPSED;
1293 } else {
1294 bs.nesting++;
1295 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001296 final FilterStats fs = inflight.mFilterStats;
1297 fs.count++;
1298 if (fs.nesting == 0) {
1299 fs.nesting = 1;
1300 fs.startTime = nowELAPSED;
1301 } else {
1302 fs.nesting++;
1303 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001304 if (alarm.type == ELAPSED_REALTIME_WAKEUP
1305 || alarm.type == RTC_WAKEUP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 bs.numWakeup++;
Dianne Hackborn81038902012-11-26 17:04:09 -08001307 fs.numWakeup++;
Dianne Hackborn099bc622014-01-22 13:39:16 -08001308 if (alarm.workSource != null && alarm.workSource.size() > 0) {
1309 for (int wi=0; wi<alarm.workSource.size(); wi++) {
1310 ActivityManagerNative.noteWakeupAlarm(
1311 alarm.operation, alarm.workSource.get(wi),
1312 alarm.workSource.getName(wi));
1313 }
1314 } else {
1315 ActivityManagerNative.noteWakeupAlarm(
1316 alarm.operation, -1, null);
1317 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 }
1319 } catch (PendingIntent.CanceledException e) {
1320 if (alarm.repeatInterval > 0) {
1321 // This IntentSender is no longer valid, but this
1322 // is a repeating alarm, so toss the hoser.
Adam Lesinski182f73f2013-12-05 16:48:06 -08001323 removeImpl(alarm.operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 }
1325 } catch (RuntimeException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001326 Slog.w(TAG, "Failure sending alarm.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 }
1328 }
1329 }
1330 }
1331 }
1332 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07001333
David Christieebe51fc2013-07-26 13:23:29 -07001334 /**
1335 * Attribute blame for a WakeLock.
1336 * @param pi PendingIntent to attribute blame to if ws is null.
1337 * @param ws WorkSource to attribute blame.
1338 */
1339 void setWakelockWorkSource(PendingIntent pi, WorkSource ws) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07001340 try {
David Christieebe51fc2013-07-26 13:23:29 -07001341 if (ws != null) {
1342 mWakeLock.setWorkSource(ws);
1343 return;
1344 }
1345
Christopher Tatec4a07d12012-04-06 14:19:13 -07001346 final int uid = ActivityManagerNative.getDefault()
1347 .getUidForIntentSender(pi.getTarget());
1348 if (uid >= 0) {
1349 mWakeLock.setWorkSource(new WorkSource(uid));
1350 return;
1351 }
1352 } catch (Exception e) {
1353 }
1354
1355 // Something went wrong; fall back to attributing the lock to the OS
1356 mWakeLock.setWorkSource(null);
1357 }
1358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001359 private class AlarmHandler extends Handler {
1360 public static final int ALARM_EVENT = 1;
1361 public static final int MINUTE_CHANGE_EVENT = 2;
1362 public static final int DATE_CHANGE_EVENT = 3;
1363
1364 public AlarmHandler() {
1365 }
1366
1367 public void handleMessage(Message msg) {
1368 if (msg.what == ALARM_EVENT) {
1369 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
1370 synchronized (mLock) {
1371 final long nowRTC = System.currentTimeMillis();
Christopher Tatee0a22b32013-07-11 14:43:13 -07001372 final long nowELAPSED = SystemClock.elapsedRealtime();
1373 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 }
1375
1376 // now trigger the alarms without the lock held
Dianne Hackborn390517b2013-05-30 15:03:32 -07001377 for (int i=0; i<triggerList.size(); i++) {
1378 Alarm alarm = triggerList.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 try {
1380 alarm.operation.send();
1381 } catch (PendingIntent.CanceledException e) {
1382 if (alarm.repeatInterval > 0) {
1383 // This IntentSender is no longer valid, but this
1384 // is a repeating alarm, so toss the hoser.
Adam Lesinski182f73f2013-12-05 16:48:06 -08001385 removeImpl(alarm.operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 }
1387 }
1388 }
1389 }
1390 }
1391 }
1392
1393 class ClockReceiver extends BroadcastReceiver {
1394 public ClockReceiver() {
1395 IntentFilter filter = new IntentFilter();
1396 filter.addAction(Intent.ACTION_TIME_TICK);
1397 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001398 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 }
1400
1401 @Override
1402 public void onReceive(Context context, Intent intent) {
1403 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001404 if (DEBUG_BATCH) {
1405 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
1406 }
1407 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
1409 // Since the kernel does not keep track of DST, we need to
1410 // reset the TZ information at the beginning of each day
1411 // based off of the current Zone gmt offset + userspace tracked
1412 // daylight savings information.
1413 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02001414 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001415 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07001416 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 }
1418 }
1419
1420 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07001421 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09001422 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07001423
1424 // Schedule this event for the amount of time that it would take to get to
1425 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09001426 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07001427
David Christieebe51fc2013-07-26 13:23:29 -07001428 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08001429 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
David Christieebe51fc2013-07-26 13:23:29 -07001430 0, mTimeTickSender, true, workSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001431 }
Christopher Tate385e4982013-07-23 18:22:29 -07001432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 public void scheduleDateChangedEvent() {
1434 Calendar calendar = Calendar.getInstance();
1435 calendar.setTimeInMillis(System.currentTimeMillis());
1436 calendar.set(Calendar.HOUR, 0);
1437 calendar.set(Calendar.MINUTE, 0);
1438 calendar.set(Calendar.SECOND, 0);
1439 calendar.set(Calendar.MILLISECOND, 0);
1440 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07001441
1442 final WorkSource workSource = null; // Let system take blame for date change events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08001443 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, true, workSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 }
1445 }
1446
1447 class UninstallReceiver extends BroadcastReceiver {
1448 public UninstallReceiver() {
1449 IntentFilter filter = new IntentFilter();
1450 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1451 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001452 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001453 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08001454 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001455 // Register for events related to sdcard installation.
1456 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001457 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001458 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001459 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001460 }
1461
1462 @Override
1463 public void onReceive(Context context, Intent intent) {
1464 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001465 String action = intent.getAction();
1466 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001467 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
1468 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
1469 for (String packageName : pkgList) {
1470 if (lookForPackageLocked(packageName)) {
1471 setResultCode(Activity.RESULT_OK);
1472 return;
1473 }
1474 }
1475 return;
1476 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001477 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001478 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
1479 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
1480 if (userHandle >= 0) {
1481 removeUserLocked(userHandle);
1482 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001483 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08001484 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
1485 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
1486 // This package is being updated; don't kill its alarms.
1487 return;
1488 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001489 Uri data = intent.getData();
1490 if (data != null) {
1491 String pkg = data.getSchemeSpecificPart();
1492 if (pkg != null) {
1493 pkgList = new String[]{pkg};
1494 }
1495 }
1496 }
1497 if (pkgList != null && (pkgList.length > 0)) {
1498 for (String pkg : pkgList) {
1499 removeLocked(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001500 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
1501 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
1502 if (uidStats.remove(pkg) != null) {
1503 if (uidStats.size() <= 0) {
1504 mBroadcastStats.removeAt(i);
1505 }
1506 }
1507 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001508 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509 }
1510 }
1511 }
1512 }
1513
1514 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001515 String pkg = pi.getCreatorPackage();
1516 int uid = pi.getCreatorUid();
1517 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
1518 if (uidStats == null) {
1519 uidStats = new ArrayMap<String, BroadcastStats>();
1520 mBroadcastStats.put(uid, uidStats);
1521 }
1522 BroadcastStats bs = uidStats.get(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 if (bs == null) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001524 bs = new BroadcastStats(uid, pkg);
1525 uidStats.put(pkg, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 }
1527 return bs;
1528 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 class ResultReceiver implements PendingIntent.OnFinished {
1531 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
1532 String resultData, Bundle resultExtras) {
1533 synchronized (mLock) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001534 InFlight inflight = null;
1535 for (int i=0; i<mInFlight.size(); i++) {
1536 if (mInFlight.get(i).mPendingIntent == pi) {
1537 inflight = mInFlight.remove(i);
1538 break;
1539 }
1540 }
1541 if (inflight != null) {
1542 final long nowELAPSED = SystemClock.elapsedRealtime();
1543 BroadcastStats bs = inflight.mBroadcastStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 bs.nesting--;
1545 if (bs.nesting <= 0) {
1546 bs.nesting = 0;
Dianne Hackborn81038902012-11-26 17:04:09 -08001547 bs.aggregateTime += nowELAPSED - bs.startTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001549 FilterStats fs = inflight.mFilterStats;
1550 fs.nesting--;
1551 if (fs.nesting <= 0) {
1552 fs.nesting = 0;
1553 fs.aggregateTime += nowELAPSED - fs.startTime;
1554 }
1555 } else {
1556 mLog.w("No in-flight alarm for " + pi + " " + intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557 }
1558 mBroadcastRefCount--;
1559 if (mBroadcastRefCount == 0) {
1560 mWakeLock.release();
Dianne Hackborn81038902012-11-26 17:04:09 -08001561 if (mInFlight.size() > 0) {
1562 mLog.w("Finished all broadcasts with " + mInFlight.size()
1563 + " remaining inflights");
1564 for (int i=0; i<mInFlight.size(); i++) {
1565 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
1566 }
1567 mInFlight.clear();
1568 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07001569 } else {
1570 // the next of our alarms is now in flight. reattribute the wakelock.
Dianne Hackborn81038902012-11-26 17:04:09 -08001571 if (mInFlight.size() > 0) {
David Christieebe51fc2013-07-26 13:23:29 -07001572 InFlight inFlight = mInFlight.get(0);
1573 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource);
Christopher Tatec4a07d12012-04-06 14:19:13 -07001574 } else {
1575 // should never happen
Dianne Hackborn81038902012-11-26 17:04:09 -08001576 mLog.w("Alarm wakelock still held but sent queue empty");
Christopher Tatec4a07d12012-04-06 14:19:13 -07001577 mWakeLock.setWorkSource(null);
1578 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 }
1580 }
1581 }
1582 }
1583}