blob: 21e56702b6ad27c65a89370209ae0d64ed4cb3fd [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;
Adrian Roosc42a1e12014-07-07 23:35:53 +020020import android.app.ActivityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import android.app.ActivityManagerNative;
Adrian Roosc42a1e12014-07-07 23:35:53 +020022import android.app.AlarmClockInfo;
Christopher Tate57ceaaa2013-07-19 16:30:43 -070023import android.app.AlarmManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.app.IAlarmManager;
25import android.app.PendingIntent;
26import android.content.BroadcastReceiver;
27import android.content.Context;
28import android.content.Intent;
29import android.content.IntentFilter;
30import android.content.pm.PackageManager;
31import android.net.Uri;
32import android.os.Binder;
33import android.os.Bundle;
34import android.os.Handler;
Adam Lesinski182f73f2013-12-05 16:48:06 -080035import android.os.IBinder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.os.Message;
37import android.os.PowerManager;
38import android.os.SystemClock;
39import android.os.SystemProperties;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070040import android.os.UserHandle;
Christopher Tatec4a07d12012-04-06 14:19:13 -070041import android.os.WorkSource;
Adrian Roosc42a1e12014-07-07 23:35:53 +020042import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.text.TextUtils;
Adrian Roosc42a1e12014-07-07 23:35:53 +020044import android.text.format.DateFormat;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080045import android.util.ArrayMap;
Adrian Roosc42a1e12014-07-07 23:35:53 +020046import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080047import android.util.Slog;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080048import android.util.SparseArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +020049import android.util.SparseBooleanArray;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070050import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051
Christopher Tate4cb338d2013-07-26 13:11:31 -070052import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import java.io.FileDescriptor;
54import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070055import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -080057import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import java.util.Calendar;
59import java.util.Collections;
60import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -050061import java.util.Date;
Christopher Tate18a75f12013-07-01 18:18:59 -070062import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +020063import java.util.Locale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import java.util.TimeZone;
65
Christopher Tatee0a22b32013-07-11 14:43:13 -070066import static android.app.AlarmManager.RTC_WAKEUP;
67import static android.app.AlarmManager.RTC;
68import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
69import static android.app.AlarmManager.ELAPSED_REALTIME;
70
Dianne Hackborn81038902012-11-26 17:04:09 -080071import com.android.internal.util.LocalLog;
72
Adam Lesinski182f73f2013-12-05 16:48:06 -080073class AlarmManagerService extends SystemService {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074 // The threshold for how long an alarm can be late before we print a
75 // warning message. The time duration is in milliseconds.
76 private static final long LATE_ALARM_THRESHOLD = 10 * 1000;
Christopher Tatee0a22b32013-07-11 14:43:13 -070077
78 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
79 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -080080 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -070081 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -080082 static final int TIME_CHANGED_MASK = 1 << 16;
83 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -080084
Christopher Tatee0a22b32013-07-11 14:43:13 -070085 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -080086 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -080087
Adam Lesinski182f73f2013-12-05 16:48:06 -080088 static final String TAG = "AlarmManager";
89 static final String ClockReceiver_TAG = "ClockReceiver";
90 static final boolean localLOGV = false;
91 static final boolean DEBUG_BATCH = localLOGV || false;
92 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +020093 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Adam Lesinski182f73f2013-12-05 16:48:06 -080094 static final int ALARM_EVENT = 1;
95 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +020096
Adam Lesinski182f73f2013-12-05 16:48:06 -080097 static final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -080099 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100
Adam Lesinski182f73f2013-12-05 16:48:06 -0800101 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700102
Adrian Roosc42a1e12014-07-07 23:35:53 +0200103 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT = new Intent(
104 AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED);
105
Adam Lesinski182f73f2013-12-05 16:48:06 -0800106 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800107
Adam Lesinski182f73f2013-12-05 16:48:06 -0800108 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800109
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800110 long mNativeData;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700111 private long mNextWakeup;
112 private long mNextNonWakeup;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800113 int mBroadcastRefCount = 0;
114 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700115 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700116 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<Alarm>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800117 ArrayList<InFlight> mInFlight = new ArrayList<InFlight>();
118 final AlarmHandler mHandler = new AlarmHandler();
119 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700120 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 private UninstallReceiver mUninstallReceiver;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800122 final ResultReceiver mResultReceiver = new ResultReceiver();
123 PendingIntent mTimeTickSender;
124 PendingIntent mDateChangeSender;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700125 boolean mInteractive = true;
126 long mNonInteractiveStartTime;
127 long mNonInteractiveTime;
128 long mLastAlarmDeliveryTime;
129 long mStartCurrentDelayTime;
130 long mNextNonWakeupDeliveryTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800131
Adrian Roosc42a1e12014-07-07 23:35:53 +0200132 private final SparseArray<AlarmClockInfo> mNextAlarmClockForUser = new SparseArray<>();
133 private final SparseArray<AlarmClockInfo> mTmpSparseAlarmClockArray = new SparseArray<>();
134 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
135 new SparseBooleanArray();
136 private boolean mNextAlarmClockMayChange;
137
138 // May only use on mHandler's thread, locking not required.
139 private final SparseArray<AlarmClockInfo> mHandlerSparseAlarmClockArray = new SparseArray<>();
140
Christopher Tate18a75f12013-07-01 18:18:59 -0700141 class WakeupEvent {
142 public long when;
143 public int uid;
144 public String action;
145
146 public WakeupEvent(long theTime, int theUid, String theAction) {
147 when = theTime;
148 uid = theUid;
149 action = theAction;
150 }
151 }
152
Adam Lesinski182f73f2013-12-05 16:48:06 -0800153 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
154 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700155
Adrian Roosc42a1e12014-07-07 23:35:53 +0200156 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700157 long start; // These endpoints are always in ELAPSED
158 long end;
159 boolean standalone; // certain "batches" don't participate in coalescing
160
161 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
162
163 Batch() {
164 start = 0;
165 end = Long.MAX_VALUE;
166 }
167
168 Batch(Alarm seed) {
169 start = seed.whenElapsed;
170 end = seed.maxWhen;
171 alarms.add(seed);
172 }
173
174 int size() {
175 return alarms.size();
176 }
177
178 Alarm get(int index) {
179 return alarms.get(index);
180 }
181
182 boolean canHold(long whenElapsed, long maxWhen) {
183 return (end >= whenElapsed) && (start <= maxWhen);
184 }
185
186 boolean add(Alarm alarm) {
187 boolean newStart = false;
188 // narrows the batch if necessary; presumes that canHold(alarm) is true
189 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
190 if (index < 0) {
191 index = 0 - index - 1;
192 }
193 alarms.add(index, alarm);
194 if (DEBUG_BATCH) {
195 Slog.v(TAG, "Adding " + alarm + " to " + this);
196 }
197 if (alarm.whenElapsed > start) {
198 start = alarm.whenElapsed;
199 newStart = true;
200 }
201 if (alarm.maxWhen < end) {
202 end = alarm.maxWhen;
203 }
204
205 if (DEBUG_BATCH) {
206 Slog.v(TAG, " => now " + this);
207 }
208 return newStart;
209 }
210
211 boolean remove(final PendingIntent operation) {
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.equals(operation)) {
218 alarms.remove(i);
219 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200220 if (alarm.alarmClock != null) {
221 mNextAlarmClockMayChange = true;
222 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700223 } else {
224 if (alarm.whenElapsed > newStart) {
225 newStart = alarm.whenElapsed;
226 }
227 if (alarm.maxWhen < newEnd) {
228 newEnd = alarm.maxWhen;
229 }
230 i++;
231 }
232 }
233 if (didRemove) {
234 // commit the new batch bounds
235 start = newStart;
236 end = newEnd;
237 }
238 return didRemove;
239 }
240
241 boolean remove(final String packageName) {
242 boolean didRemove = false;
243 long newStart = 0; // recalculate endpoints as we go
244 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700245 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700246 Alarm alarm = alarms.get(i);
247 if (alarm.operation.getTargetPackage().equals(packageName)) {
248 alarms.remove(i);
249 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200250 if (alarm.alarmClock != null) {
251 mNextAlarmClockMayChange = true;
252 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700253 } else {
254 if (alarm.whenElapsed > newStart) {
255 newStart = alarm.whenElapsed;
256 }
257 if (alarm.maxWhen < newEnd) {
258 newEnd = alarm.maxWhen;
259 }
260 i++;
261 }
262 }
263 if (didRemove) {
264 // commit the new batch bounds
265 start = newStart;
266 end = newEnd;
267 }
268 return didRemove;
269 }
270
271 boolean remove(final int userHandle) {
272 boolean didRemove = false;
273 long newStart = 0; // recalculate endpoints as we go
274 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700275 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700276 Alarm alarm = alarms.get(i);
277 if (UserHandle.getUserId(alarm.operation.getCreatorUid()) == userHandle) {
278 alarms.remove(i);
279 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200280 if (alarm.alarmClock != null) {
281 mNextAlarmClockMayChange = true;
282 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700283 } else {
284 if (alarm.whenElapsed > newStart) {
285 newStart = alarm.whenElapsed;
286 }
287 if (alarm.maxWhen < newEnd) {
288 newEnd = alarm.maxWhen;
289 }
290 i++;
291 }
292 }
293 if (didRemove) {
294 // commit the new batch bounds
295 start = newStart;
296 end = newEnd;
297 }
298 return didRemove;
299 }
300
301 boolean hasPackage(final String packageName) {
302 final int N = alarms.size();
303 for (int i = 0; i < N; i++) {
304 Alarm a = alarms.get(i);
305 if (a.operation.getTargetPackage().equals(packageName)) {
306 return true;
307 }
308 }
309 return false;
310 }
311
312 boolean hasWakeups() {
313 final int N = alarms.size();
314 for (int i = 0; i < N; i++) {
315 Alarm a = alarms.get(i);
316 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
317 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
318 return true;
319 }
320 }
321 return false;
322 }
323
324 @Override
325 public String toString() {
326 StringBuilder b = new StringBuilder(40);
327 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
328 b.append(" num="); b.append(size());
329 b.append(" start="); b.append(start);
330 b.append(" end="); b.append(end);
331 if (standalone) {
332 b.append(" STANDALONE");
333 }
334 b.append('}');
335 return b.toString();
336 }
337 }
338
339 static class BatchTimeOrder implements Comparator<Batch> {
340 public int compare(Batch b1, Batch b2) {
341 long when1 = b1.start;
342 long when2 = b2.start;
343 if (when1 - when2 > 0) {
344 return 1;
345 }
346 if (when1 - when2 < 0) {
347 return -1;
348 }
349 return 0;
350 }
351 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800352
353 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
354 @Override
355 public int compare(Alarm lhs, Alarm rhs) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700356 if ((!lhs.operation.getCreatorPackage().equals(rhs.operation.getCreatorPackage()))
357 && lhs.wakeup != rhs.wakeup) {
358 // We want to put wakeup alarms before non-wakeup alarms, since they are
359 // the things that drive most activity in the alarm manager. However,
360 // alarms from the same package should always be ordered strictly by time.
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800361 return lhs.wakeup ? -1 : 1;
362 }
363 if (lhs.whenElapsed < rhs.whenElapsed) {
364 return -1;
365 } else if (lhs.whenElapsed > rhs.whenElapsed) {
366 return 1;
367 }
368 return 0;
369 }
370 };
371
Christopher Tatee0a22b32013-07-11 14:43:13 -0700372 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800373 static final long MIN_FUZZABLE_INTERVAL = 10000;
374 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
375 final ArrayList<Batch> mAlarmBatches = new ArrayList<Batch>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700376
Jeff Brownb880d882014-02-10 19:47:07 -0800377 public AlarmManagerService(Context context) {
378 super(context);
379 }
380
Christopher Tatee0a22b32013-07-11 14:43:13 -0700381 static long convertToElapsed(long when, int type) {
382 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
383 if (isRtc) {
384 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
385 }
386 return when;
387 }
388
389 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
390 // calculate the end of our nominal delivery window for the alarm.
391 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
392 // Current heuristic: batchable window is 75% of either the recurrence interval
393 // [for a periodic alarm] or of the time from now to the desired delivery time,
394 // with a minimum delay/interval of 10 seconds, under which we will simply not
395 // defer the alarm.
396 long futurity = (interval == 0)
397 ? (triggerAtTime - now)
398 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700399 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700400 futurity = 0;
401 }
402 return triggerAtTime + (long)(.75 * futurity);
403 }
404
405 // returns true if the batch was added at the head
406 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
407 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
408 if (index < 0) {
409 index = 0 - index - 1;
410 }
411 list.add(index, newBatch);
412 return (index == 0);
413 }
414
Christopher Tate385e4982013-07-23 18:22:29 -0700415 // Return the index of the matching batch, or -1 if none found.
416 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700417 final int N = mAlarmBatches.size();
418 for (int i = 0; i < N; i++) {
419 Batch b = mAlarmBatches.get(i);
420 if (!b.standalone && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700421 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700422 }
423 }
Christopher Tate385e4982013-07-23 18:22:29 -0700424 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700425 }
426
427 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
428 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700429 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700430 rebatchAllAlarmsLocked(true);
431 }
432 }
433
434 void rebatchAllAlarmsLocked(boolean doValidate) {
435 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
436 mAlarmBatches.clear();
437 final long nowElapsed = SystemClock.elapsedRealtime();
438 final int oldBatches = oldSet.size();
439 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
440 Batch batch = oldSet.get(batchNum);
441 final int N = batch.size();
442 for (int i = 0; i < N; i++) {
443 Alarm a = batch.get(i);
444 long whenElapsed = convertToElapsed(a.when, a.type);
Christopher Tate3e04b472013-10-21 17:51:31 -0700445 final long maxElapsed;
446 if (a.whenElapsed == a.maxWhen) {
447 // Exact
448 maxElapsed = whenElapsed;
449 } else {
450 // Not exact. Preserve any explicit window, otherwise recalculate
451 // the window based on the alarm's new futurity. Note that this
452 // reflects a policy of preferring timely to deferred delivery.
453 maxElapsed = (a.windowLength > 0)
454 ? (whenElapsed + a.windowLength)
455 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
456 }
457 setImplLocked(a.type, a.when, whenElapsed, a.windowLength, maxElapsed,
Adrian Roosc42a1e12014-07-07 23:35:53 +0200458 a.repeatInterval, a.operation, batch.standalone, doValidate, a.workSource,
459 a.alarmClock, a.userId);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700460 }
461 }
462 }
463
Adam Lesinski182f73f2013-12-05 16:48:06 -0800464 static final class InFlight extends Intent {
Dianne Hackborn81038902012-11-26 17:04:09 -0800465 final PendingIntent mPendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700466 final WorkSource mWorkSource;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700467 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800468 final BroadcastStats mBroadcastStats;
469 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800470 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800471
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800472 InFlight(AlarmManagerService service, PendingIntent pendingIntent, WorkSource workSource,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700473 int alarmType, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800474 mPendingIntent = pendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700475 mWorkSource = workSource;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700476 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800477 mBroadcastStats = service.getStatsLocked(pendingIntent);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700478 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -0800479 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700480 fs = new FilterStats(mBroadcastStats, mTag);
481 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -0800482 }
483 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800484 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800486 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800487
Adam Lesinski182f73f2013-12-05 16:48:06 -0800488 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -0800489 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700490 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800493 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494 int numWakeup;
495 long startTime;
496 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -0800497
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700498 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800499 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700500 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800501 }
502 }
503
Adam Lesinski182f73f2013-12-05 16:48:06 -0800504 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800505 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800506 final String mPackageName;
507
508 long aggregateTime;
509 int count;
510 int numWakeup;
511 long startTime;
512 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700513 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -0800514
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800515 BroadcastStats(int uid, String packageName) {
516 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800517 mPackageName = packageName;
518 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800519 }
520
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800521 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
522 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700523
524 int mNumDelayedAlarms = 0;
525 long mTotalDelayTime = 0;
526 long mMaxDelayTime = 0;
527
Adam Lesinski182f73f2013-12-05 16:48:06 -0800528 @Override
529 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800530 mNativeData = init();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700531 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800532
533 // We have to set current TimeZone info to kernel
534 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -0800535 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800536
Adam Lesinski182f73f2013-12-05 16:48:06 -0800537 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800538 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800539
Adam Lesinski182f73f2013-12-05 16:48:06 -0800540 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800541 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700542 Intent.FLAG_RECEIVER_REGISTERED_ONLY
543 | Intent.FLAG_RECEIVER_FOREGROUND), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700544 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800545 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
546 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800547 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700548 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549
550 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -0800551 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 mClockReceiver.scheduleTimeTickEvent();
553 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700554 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555 mUninstallReceiver = new UninstallReceiver();
556
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800557 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800558 AlarmThread waitThread = new AlarmThread();
559 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800561 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800563
564 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800565 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800566
567 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800568 protected void finalize() throws Throwable {
569 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800570 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800571 } finally {
572 super.finalize();
573 }
574 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700575
Adam Lesinski182f73f2013-12-05 16:48:06 -0800576 void setTimeZoneImpl(String tz) {
577 if (TextUtils.isEmpty(tz)) {
578 return;
David Christieebe51fc2013-07-26 13:23:29 -0700579 }
580
Adam Lesinski182f73f2013-12-05 16:48:06 -0800581 TimeZone zone = TimeZone.getTimeZone(tz);
582 // Prevent reentrant calls from stepping on each other when writing
583 // the time zone property
584 boolean timeZoneWasChanged = false;
585 synchronized (this) {
586 String current = SystemProperties.get(TIMEZONE_PROPERTY);
587 if (current == null || !current.equals(zone.getID())) {
588 if (localLOGV) {
589 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
590 }
591 timeZoneWasChanged = true;
592 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
593 }
594
595 // Update the kernel timezone information
596 // Kernel tracks time offsets as 'minutes west of GMT'
597 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800598 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -0800599 }
600
601 TimeZone.setDefault(null);
602
603 if (timeZoneWasChanged) {
604 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
605 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
606 intent.putExtra("time-zone", zone.getID());
607 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
608 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800609 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700610
Adam Lesinski182f73f2013-12-05 16:48:06 -0800611 void removeImpl(PendingIntent operation) {
612 if (operation == null) {
613 return;
614 }
615 synchronized (mLock) {
616 removeLocked(operation);
617 }
618 }
619
620 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Adrian Roosc42a1e12014-07-07 23:35:53 +0200621 PendingIntent operation, boolean isStandalone, WorkSource workSource,
622 AlarmClockInfo alarmClock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800623 if (operation == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800624 Slog.w(TAG, "set/setRepeating ignored because there is no intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625 return;
626 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700627
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700628 // Sanity check the window length. This will catch people mistakenly
629 // trying to pass an end-of-window timestamp rather than a duration.
630 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
631 Slog.w(TAG, "Window length " + windowLength
632 + "ms suspiciously long; limiting to 1 hour");
633 windowLength = AlarmManager.INTERVAL_HOUR;
634 }
635
Christopher Tatee0a22b32013-07-11 14:43:13 -0700636 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
637 throw new IllegalArgumentException("Invalid alarm type " + type);
638 }
639
Christopher Tate5f221e82013-07-30 17:13:15 -0700640 if (triggerAtTime < 0) {
641 final long who = Binder.getCallingUid();
642 final long what = Binder.getCallingPid();
643 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + who
644 + " pid=" + what);
645 triggerAtTime = 0;
646 }
647
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700648 final long nowElapsed = SystemClock.elapsedRealtime();
649 final long triggerElapsed = convertToElapsed(triggerAtTime, type);
650 final long maxElapsed;
651 if (windowLength == AlarmManager.WINDOW_EXACT) {
652 maxElapsed = triggerElapsed;
653 } else if (windowLength < 0) {
654 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
655 } else {
656 maxElapsed = triggerElapsed + windowLength;
657 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700658
Adrian Roosc42a1e12014-07-07 23:35:53 +0200659 final int userId = UserHandle.getCallingUserId();
660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700662 if (DEBUG_BATCH) {
663 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700664 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -0700665 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
666 + " interval=" + interval + " standalone=" + isStandalone);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 }
Christopher Tate3e04b472013-10-21 17:51:31 -0700668 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Adrian Roosc42a1e12014-07-07 23:35:53 +0200669 interval, operation, isStandalone, true, workSource, alarmClock, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670 }
671 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672
Christopher Tate3e04b472013-10-21 17:51:31 -0700673 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
674 long maxWhen, long interval, PendingIntent operation, boolean isStandalone,
Adrian Roosc42a1e12014-07-07 23:35:53 +0200675 boolean doValidate, WorkSource workSource, AlarmClockInfo alarmClock, int userId) {
Christopher Tate3e04b472013-10-21 17:51:31 -0700676 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Adrian Roosc42a1e12014-07-07 23:35:53 +0200677 operation, workSource, alarmClock, userId);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700678 removeLocked(operation);
Christopher Tateb8849c12011-02-08 13:39:01 -0800679
Christopher Tate385e4982013-07-23 18:22:29 -0700680 int whichBatch = (isStandalone) ? -1 : attemptCoalesceLocked(whenElapsed, maxWhen);
681 if (whichBatch < 0) {
682 Batch batch = new Batch(a);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700683 batch.standalone = isStandalone;
Christopher Tate7d57ed82013-10-25 20:18:03 -0700684 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 } else {
Christopher Tate385e4982013-07-23 18:22:29 -0700686 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -0700687 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700688 // The start time of this batch advanced, so batch ordering may
689 // have just been broken. Move it to where it now belongs.
690 mAlarmBatches.remove(whichBatch);
691 addBatchLocked(mAlarmBatches, batch);
692 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693 }
694
Adrian Roosc42a1e12014-07-07 23:35:53 +0200695 if (alarmClock != null) {
696 mNextAlarmClockMayChange = true;
697 updateNextAlarmClockLocked();
698 }
699
Christopher Tate4cb338d2013-07-26 13:11:31 -0700700 if (DEBUG_VALIDATE) {
Christopher Tate5f221e82013-07-30 17:13:15 -0700701 if (doValidate && !validateConsistencyLocked()) {
702 Slog.v(TAG, "Tipping-point operation: type=" + type + " when=" + when
703 + " when(hex)=" + Long.toHexString(when)
704 + " whenElapsed=" + whenElapsed + " maxWhen=" + maxWhen
705 + " interval=" + interval + " op=" + operation
706 + " standalone=" + isStandalone);
Christopher Tate4cb338d2013-07-26 13:11:31 -0700707 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -0700708 }
709 }
710
Christopher Tate7d57ed82013-10-25 20:18:03 -0700711 rescheduleKernelAlarmsLocked();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700712 }
713
Adam Lesinski182f73f2013-12-05 16:48:06 -0800714 private final IBinder mService = new IAlarmManager.Stub() {
715 @Override
716 public void set(int type, long triggerAtTime, long windowLength, long interval,
Adrian Roosc42a1e12014-07-07 23:35:53 +0200717 PendingIntent operation, WorkSource workSource, AlarmClockInfo alarmClock) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800718 if (workSource != null) {
719 getContext().enforceCallingPermission(
720 android.Manifest.permission.UPDATE_DEVICE_STATS,
721 "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -0700722 }
723
Adam Lesinski182f73f2013-12-05 16:48:06 -0800724 setImpl(type, triggerAtTime, windowLength, interval, operation,
Adrian Roosc42a1e12014-07-07 23:35:53 +0200725 false, workSource, alarmClock);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800726 }
Christopher Tate89779822012-08-31 14:40:03 -0700727
Adam Lesinski182f73f2013-12-05 16:48:06 -0800728 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -0800729 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800730 getContext().enforceCallingOrSelfPermission(
731 "android.permission.SET_TIME",
732 "setTime");
733
Greg Hackmann0cab8962014-02-21 16:35:52 -0800734 if (mNativeData == 0) {
735 Slog.w(TAG, "Not setting time since no alarm driver is available.");
736 return false;
Christopher Tate89779822012-08-31 14:40:03 -0700737 }
Greg Hackmann0cab8962014-02-21 16:35:52 -0800738
739 synchronized (mLock) {
740 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800742 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800743
744 @Override
745 public void setTimeZone(String tz) {
746 getContext().enforceCallingOrSelfPermission(
747 "android.permission.SET_TIME_ZONE",
748 "setTimeZone");
749
750 final long oldId = Binder.clearCallingIdentity();
751 try {
752 setTimeZoneImpl(tz);
753 } finally {
754 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 }
756 }
Christopher Tate4cb338d2013-07-26 13:11:31 -0700757
Adam Lesinski182f73f2013-12-05 16:48:06 -0800758 @Override
759 public void remove(PendingIntent operation) {
760 removeImpl(operation);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800762 }
Christopher Tate4cb338d2013-07-26 13:11:31 -0700763
Adam Lesinski182f73f2013-12-05 16:48:06 -0800764 @Override
Adrian Roosc42a1e12014-07-07 23:35:53 +0200765 public AlarmClockInfo getNextAlarmClock(int userId) {
766 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
767 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
768 "getNextAlarmClock", null);
769
770 return getNextAlarmClockImpl(userId);
771 }
772
773 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -0800774 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
775 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
776 != PackageManager.PERMISSION_GRANTED) {
777 pw.println("Permission Denial: can't dump AlarmManager from from pid="
778 + Binder.getCallingPid()
779 + ", uid=" + Binder.getCallingUid());
780 return;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700781 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700782
Adam Lesinski182f73f2013-12-05 16:48:06 -0800783 dumpImpl(pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700784 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800785 };
Christopher Tate4cb338d2013-07-26 13:11:31 -0700786
Adam Lesinski182f73f2013-12-05 16:48:06 -0800787 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788 synchronized (mLock) {
789 pw.println("Current Alarm Manager state:");
Christopher Tatee0a22b32013-07-11 14:43:13 -0700790 final long nowRTC = System.currentTimeMillis();
791 final long nowELAPSED = SystemClock.elapsedRealtime();
792 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
793
794 pw.print("nowRTC="); pw.print(nowRTC);
795 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700796 pw.print(" nowELAPSED="); TimeUtils.formatDuration(nowELAPSED, pw);
797 pw.println();
798 if (!mInteractive) {
799 pw.print("Time since non-interactive: ");
800 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
801 pw.println();
802 pw.print("Max wakeup delay: ");
803 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
804 pw.println();
805 pw.print("Time since last dispatch: ");
806 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
807 pw.println();
808 pw.print("Next non-wakeup delivery time: ");
809 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
810 pw.println();
811 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700812
813 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
814 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700815 pw.print("Next non-wakeup alarm: ");
816 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700817 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700818 pw.print("Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700819 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
820
821 if (mAlarmBatches.size() > 0) {
822 pw.println();
823 pw.print("Pending alarm batches: ");
824 pw.println(mAlarmBatches.size());
825 for (Batch b : mAlarmBatches) {
826 pw.print(b); pw.println(':');
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700827 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700828 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800830
831 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700832 pw.print("Past-due non-wakeup alarms: ");
833 if (mPendingNonWakeupAlarms.size() > 0) {
834 pw.println(mPendingNonWakeupAlarms.size());
835 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
836 } else {
837 pw.println("(none)");
838 }
839 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
840 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
841 pw.println();
842 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
843 pw.print(", max non-interactive time: ");
844 TimeUtils.formatDuration(mNonInteractiveTime, pw);
845 pw.println();
846
847 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700848 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -0800849 pw.println();
850
851 if (mLog.dump(pw, " Recent problems", " ")) {
852 pw.println();
853 }
854
855 final FilterStats[] topFilters = new FilterStats[10];
856 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
857 @Override
858 public int compare(FilterStats lhs, FilterStats rhs) {
859 if (lhs.aggregateTime < rhs.aggregateTime) {
860 return 1;
861 } else if (lhs.aggregateTime > rhs.aggregateTime) {
862 return -1;
863 }
864 return 0;
865 }
866 };
867 int len = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800868 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
869 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
870 for (int ip=0; ip<uidStats.size(); ip++) {
871 BroadcastStats bs = uidStats.valueAt(ip);
872 for (int is=0; is<bs.filterStats.size(); is++) {
873 FilterStats fs = bs.filterStats.valueAt(is);
874 int pos = len > 0
875 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
876 if (pos < 0) {
877 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -0800878 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800879 if (pos < topFilters.length) {
880 int copylen = topFilters.length - pos - 1;
881 if (copylen > 0) {
882 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
883 }
884 topFilters[pos] = fs;
885 if (len < topFilters.length) {
886 len++;
887 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800888 }
889 }
890 }
891 }
892 if (len > 0) {
893 pw.println(" Top Alarms:");
894 for (int i=0; i<len; i++) {
895 FilterStats fs = topFilters[i];
896 pw.print(" ");
897 if (fs.nesting > 0) pw.print("*ACTIVE* ");
898 TimeUtils.formatDuration(fs.aggregateTime, pw);
899 pw.print(" running, "); pw.print(fs.numWakeup);
900 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800901 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
902 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -0800903 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700904 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -0800905 pw.println();
906 }
907 }
908
909 pw.println(" ");
910 pw.println(" Alarm Stats:");
911 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800912 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
913 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
914 for (int ip=0; ip<uidStats.size(); ip++) {
915 BroadcastStats bs = uidStats.valueAt(ip);
916 pw.print(" ");
917 if (bs.nesting > 0) pw.print("*ACTIVE* ");
918 UserHandle.formatUid(pw, bs.mUid);
919 pw.print(":");
920 pw.print(bs.mPackageName);
921 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
922 pw.print(" running, "); pw.print(bs.numWakeup);
923 pw.println(" wakeups:");
924 tmpFilters.clear();
925 for (int is=0; is<bs.filterStats.size(); is++) {
926 tmpFilters.add(bs.filterStats.valueAt(is));
927 }
928 Collections.sort(tmpFilters, comparator);
929 for (int i=0; i<tmpFilters.size(); i++) {
930 FilterStats fs = tmpFilters.get(i);
931 pw.print(" ");
932 if (fs.nesting > 0) pw.print("*ACTIVE* ");
933 TimeUtils.formatDuration(fs.aggregateTime, pw);
934 pw.print(" "); pw.print(fs.numWakeup);
935 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700936 pw.print(" alarms: ");
937 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800938 pw.println();
939 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 }
941 }
Christopher Tate18a75f12013-07-01 18:18:59 -0700942
943 if (WAKEUP_STATS) {
944 pw.println();
945 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -0700946 long last = -1;
947 for (WakeupEvent event : mRecentWakeups) {
948 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
949 pw.print('|');
950 if (last < 0) {
951 pw.print('0');
952 } else {
953 pw.print(event.when - last);
954 }
955 last = event.when;
956 pw.print('|'); pw.print(event.uid);
957 pw.print('|'); pw.print(event.action);
958 pw.println();
959 }
960 pw.println();
961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 }
963 }
964
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700965 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800966 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
967 PrintWriter pw = new PrintWriter(bs);
968 final long nowRTC = System.currentTimeMillis();
969 final long nowELAPSED = SystemClock.elapsedRealtime();
970 final int NZ = mAlarmBatches.size();
971 for (int iz = 0; iz < NZ; iz++) {
972 Batch bz = mAlarmBatches.get(iz);
973 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700974 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800975 pw.flush();
976 Slog.v(TAG, bs.toString());
977 bs.reset();
978 }
979 }
980
981 private boolean validateConsistencyLocked() {
982 if (DEBUG_VALIDATE) {
983 long lastTime = Long.MIN_VALUE;
984 final int N = mAlarmBatches.size();
985 for (int i = 0; i < N; i++) {
986 Batch b = mAlarmBatches.get(i);
987 if (b.start >= lastTime) {
988 // duplicate start times are okay because of standalone batches
989 lastTime = b.start;
990 } else {
991 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700992 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
993 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800994 return false;
995 }
996 }
997 }
998 return true;
999 }
1000
1001 private Batch findFirstWakeupBatchLocked() {
1002 final int N = mAlarmBatches.size();
1003 for (int i = 0; i < N; i++) {
1004 Batch b = mAlarmBatches.get(i);
1005 if (b.hasWakeups()) {
1006 return b;
1007 }
1008 }
1009 return null;
1010 }
1011
Adrian Roosc42a1e12014-07-07 23:35:53 +02001012 private AlarmClockInfo getNextAlarmClockImpl(int userId) {
1013 synchronized (mLock) {
1014 return mNextAlarmClockForUser.get(userId);
1015 }
1016 }
1017
1018 /**
1019 * Recomputes the next alarm clock for all users.
1020 */
1021 private void updateNextAlarmClockLocked() {
1022 if (!mNextAlarmClockMayChange) {
1023 return;
1024 }
1025 mNextAlarmClockMayChange = false;
1026
1027 SparseArray<AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
1028 nextForUser.clear();
1029
1030 final int N = mAlarmBatches.size();
1031 for (int i = 0; i < N; i++) {
1032 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
1033 final int M = alarms.size();
1034
1035 for (int j = 0; j < M; j++) {
1036 Alarm a = alarms.get(j);
1037 if (a.alarmClock != null) {
1038 final int userId = a.userId;
1039
1040 if (DEBUG_ALARM_CLOCK) {
1041 Log.v(TAG, "Found AlarmClockInfo at " +
1042 formatNextAlarm(getContext(), a.alarmClock) +
1043 " for user " + userId);
1044 }
1045
1046 // Alarms and batches are sorted by time, no need to compare times here.
1047 if (nextForUser.get(userId) == null) {
1048 nextForUser.put(userId, a.alarmClock);
1049 }
1050 }
1051 }
1052 }
1053
1054 // Update mNextAlarmForUser with new values.
1055 final int NN = nextForUser.size();
1056 for (int i = 0; i < NN; i++) {
1057 AlarmClockInfo newAlarm = nextForUser.valueAt(i);
1058 int userId = nextForUser.keyAt(i);
1059 AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
1060 if (!newAlarm.equals(currentAlarm)) {
1061 updateNextAlarmInfoForUserLocked(userId, newAlarm);
1062 }
1063 }
1064
1065 // Remove users without any alarm clocks scheduled.
1066 final int NNN = mNextAlarmClockForUser.size();
1067 for (int i = NNN - 1; i >= 0; i--) {
1068 int userId = mNextAlarmClockForUser.keyAt(i);
1069 if (nextForUser.get(userId) == null) {
1070 updateNextAlarmInfoForUserLocked(userId, null);
1071 }
1072 }
1073 }
1074
1075 private void updateNextAlarmInfoForUserLocked(int userId, AlarmClockInfo alarmClock) {
1076 if (alarmClock != null) {
1077 if (DEBUG_ALARM_CLOCK) {
1078 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
1079 formatNextAlarm(getContext(), alarmClock));
1080 }
1081 mNextAlarmClockForUser.put(userId, alarmClock);
1082 } else {
1083 if (DEBUG_ALARM_CLOCK) {
1084 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
1085 }
1086 mNextAlarmClockForUser.remove(userId);
1087 }
1088
1089 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
1090 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1091 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1092 }
1093
1094 /**
1095 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
1096 * for which alarm clocks have changed since the last call to this.
1097 *
1098 * Do not call with a lock held. Only call from mHandler's thread.
1099 *
1100 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
1101 */
1102 private void sendNextAlarmClockChanged() {
1103 SparseArray<AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
1104 pendingUsers.clear();
1105
1106 synchronized (mLock) {
1107 final int N = mPendingSendNextAlarmClockChangedForUser.size();
1108 for (int i = 0; i < N; i++) {
1109 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
1110 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
1111 }
1112 mPendingSendNextAlarmClockChangedForUser.clear();
1113 }
1114
1115 final int N = pendingUsers.size();
1116 for (int i = 0; i < N; i++) {
1117 int userId = pendingUsers.keyAt(i);
1118 AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
1119 Settings.System.putStringForUser(getContext().getContentResolver(),
1120 Settings.System.NEXT_ALARM_FORMATTED,
1121 formatNextAlarm(getContext(), alarmClock),
1122 userId);
1123
1124 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
1125 new UserHandle(userId));
1126 }
1127 }
1128
1129 /**
1130 * Formats an alarm like platform/packages/apps/DeskClock used to.
1131 */
1132 private static String formatNextAlarm(final Context context, AlarmClockInfo info) {
1133 String skeleton = DateFormat.is24HourFormat(context) ? "EHm" : "Ehma";
1134 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
1135 return (info == null) ? "" :
1136 DateFormat.format(pattern, info.getTriggerTime()).toString();
1137 }
1138
Adam Lesinski182f73f2013-12-05 16:48:06 -08001139 void rescheduleKernelAlarmsLocked() {
1140 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
1141 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001142 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001143 if (mAlarmBatches.size() > 0) {
1144 final Batch firstWakeup = findFirstWakeupBatchLocked();
1145 final Batch firstBatch = mAlarmBatches.get(0);
1146 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
1147 mNextWakeup = firstWakeup.start;
1148 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
1149 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001150 if (firstBatch != firstWakeup) {
1151 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001152 }
1153 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001154 if (mPendingNonWakeupAlarms.size() > 0) {
1155 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
1156 nextNonWakeup = mNextNonWakeupDeliveryTime;
1157 }
1158 }
1159 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
1160 mNextNonWakeup = nextNonWakeup;
1161 setLocked(ELAPSED_REALTIME, nextNonWakeup);
1162 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001163 }
1164
1165 private void removeLocked(PendingIntent operation) {
1166 boolean didRemove = false;
1167 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1168 Batch b = mAlarmBatches.get(i);
1169 didRemove |= b.remove(operation);
1170 if (b.size() == 0) {
1171 mAlarmBatches.remove(i);
1172 }
1173 }
1174
1175 if (didRemove) {
1176 if (DEBUG_BATCH) {
1177 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
1178 }
1179 rebatchAllAlarmsLocked(true);
1180 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001181 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001182 }
1183 }
1184
1185 void removeLocked(String packageName) {
1186 boolean didRemove = false;
1187 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1188 Batch b = mAlarmBatches.get(i);
1189 didRemove |= b.remove(packageName);
1190 if (b.size() == 0) {
1191 mAlarmBatches.remove(i);
1192 }
1193 }
1194
1195 if (didRemove) {
1196 if (DEBUG_BATCH) {
1197 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1198 }
1199 rebatchAllAlarmsLocked(true);
1200 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001201 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001202 }
1203 }
1204
1205 void removeUserLocked(int userHandle) {
1206 boolean didRemove = false;
1207 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1208 Batch b = mAlarmBatches.get(i);
1209 didRemove |= b.remove(userHandle);
1210 if (b.size() == 0) {
1211 mAlarmBatches.remove(i);
1212 }
1213 }
1214
1215 if (didRemove) {
1216 if (DEBUG_BATCH) {
1217 Slog.v(TAG, "remove(user) changed bounds; rebatching");
1218 }
1219 rebatchAllAlarmsLocked(true);
1220 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001221 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001222 }
1223 }
1224
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001225 void interactiveStateChangedLocked(boolean interactive) {
1226 if (mInteractive != interactive) {
1227 mInteractive = interactive;
1228 final long nowELAPSED = SystemClock.elapsedRealtime();
1229 if (interactive) {
1230 if (mPendingNonWakeupAlarms.size() > 0) {
1231 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1232 mTotalDelayTime += thisDelayTime;
1233 if (mMaxDelayTime < thisDelayTime) {
1234 mMaxDelayTime = thisDelayTime;
1235 }
1236 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
1237 mPendingNonWakeupAlarms.clear();
1238 }
1239 if (mNonInteractiveStartTime > 0) {
1240 long dur = nowELAPSED - mNonInteractiveStartTime;
1241 if (dur > mNonInteractiveTime) {
1242 mNonInteractiveTime = dur;
1243 }
1244 }
1245 } else {
1246 mNonInteractiveStartTime = nowELAPSED;
1247 }
1248 }
1249 }
1250
Adam Lesinski182f73f2013-12-05 16:48:06 -08001251 boolean lookForPackageLocked(String packageName) {
1252 for (int i = 0; i < mAlarmBatches.size(); i++) {
1253 Batch b = mAlarmBatches.get(i);
1254 if (b.hasPackage(packageName)) {
1255 return true;
1256 }
1257 }
1258 return false;
1259 }
1260
1261 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001262 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001263 // The kernel never triggers alarms with negative wakeup times
1264 // so we ensure they are positive.
1265 long alarmSeconds, alarmNanoseconds;
1266 if (when < 0) {
1267 alarmSeconds = 0;
1268 alarmNanoseconds = 0;
1269 } else {
1270 alarmSeconds = when / 1000;
1271 alarmNanoseconds = (when % 1000) * 1000 * 1000;
1272 }
1273
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001274 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001275 } else {
1276 Message msg = Message.obtain();
1277 msg.what = ALARM_EVENT;
1278
1279 mHandler.removeMessages(ALARM_EVENT);
1280 mHandler.sendMessageAtTime(msg, when);
1281 }
1282 }
1283
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001284 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001285 String prefix, String label, long nowRTC, long nowELAPSED, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 for (int i=list.size()-1; i>=0; i--) {
1287 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001288 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1289 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001290 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 }
1292 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001293
1294 private static final String labelForType(int type) {
1295 switch (type) {
1296 case RTC: return "RTC";
1297 case RTC_WAKEUP : return "RTC_WAKEUP";
1298 case ELAPSED_REALTIME : return "ELAPSED";
1299 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
1300 default:
1301 break;
1302 }
1303 return "--unknown--";
1304 }
1305
1306 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001307 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001308 for (int i=list.size()-1; i>=0; i--) {
1309 Alarm a = list.get(i);
1310 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001311 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1312 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001313 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001314 }
1315 }
1316
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001317 private native long init();
1318 private native void close(long nativeData);
1319 private native void set(long nativeData, int type, long seconds, long nanoseconds);
1320 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08001321 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001322 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001324 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001325 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001326 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001327 // batches are temporally sorted, so we need only pull from the
1328 // start of the list until we either empty it or hit a batch
1329 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07001330 while (mAlarmBatches.size() > 0) {
1331 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001332 if (batch.start > nowELAPSED) {
1333 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001334 break;
1335 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001336
Christopher Tatee0a22b32013-07-11 14:43:13 -07001337 // We will (re)schedule some alarms now; don't let that interfere
1338 // with delivery of this current batch
1339 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001340
Christopher Tatee0a22b32013-07-11 14:43:13 -07001341 final int N = batch.size();
1342 for (int i = 0; i < N; i++) {
1343 Alarm alarm = batch.get(i);
1344 alarm.count = 1;
1345 triggerList.add(alarm);
1346
1347 // Recurring alarms may have passed several alarm intervals while the
1348 // phone was asleep or off, so pass a trigger count when sending them.
1349 if (alarm.repeatInterval > 0) {
1350 // this adjustment will be zero if we're late by
1351 // less than one full repeat interval
1352 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
1353
1354 // Also schedule its next recurrence
1355 final long delta = alarm.count * alarm.repeatInterval;
1356 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07001357 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07001358 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
David Christieebe51fc2013-07-26 13:23:29 -07001359 alarm.repeatInterval, alarm.operation, batch.standalone, true,
Adrian Roosc42a1e12014-07-07 23:35:53 +02001360 alarm.workSource, alarm.alarmClock, alarm.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001362 // For now we count this as a wakeup alarm, meaning it needs to be
1363 // delivered immediately. In the future we should change this, but
1364 // that required delaying when we reschedule the repeat...!
1365 hasWakeup = false;
1366 } else if (alarm.wakeup) {
1367 hasWakeup = true;
1368 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001369
1370 // We removed an alarm clock. Let the caller recompute the next alarm clock.
1371 if (alarm.alarmClock != null) {
1372 mNextAlarmClockMayChange = true;
1373 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07001374 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001376
1377 Collections.sort(triggerList, mAlarmDispatchComparator);
1378
1379 if (localLOGV) {
1380 for (int i=0; i<triggerList.size(); i++) {
1381 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
1382 }
1383 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001384
1385 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001387
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 /**
1389 * This Comparator sorts Alarms into increasing time order.
1390 */
1391 public static class IncreasingTimeOrder implements Comparator<Alarm> {
1392 public int compare(Alarm a1, Alarm a2) {
1393 long when1 = a1.when;
1394 long when2 = a2.when;
1395 if (when1 - when2 > 0) {
1396 return 1;
1397 }
1398 if (when1 - when2 < 0) {
1399 return -1;
1400 }
1401 return 0;
1402 }
1403 }
1404
1405 private static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001406 public final int type;
1407 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001408 public final PendingIntent operation;
1409 public final String tag;
1410 public final WorkSource workSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 public int count;
1412 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07001413 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001414 public long whenElapsed; // 'when' in the elapsed time base
1415 public long maxWhen; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 public long repeatInterval;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001417 public final AlarmClockInfo alarmClock;
1418 public final int userId;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001419
Christopher Tate3e04b472013-10-21 17:51:31 -07001420 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Adrian Roosc42a1e12014-07-07 23:35:53 +02001421 long _interval, PendingIntent _op, WorkSource _ws, AlarmClockInfo _info,
1422 int _userId) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001423 type = _type;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001424 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
1425 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001426 when = _when;
1427 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07001428 windowLength = _windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001429 maxWhen = _maxWhen;
1430 repeatInterval = _interval;
1431 operation = _op;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001432 tag = makeTag(_op, _type);
David Christieebe51fc2013-07-26 13:23:29 -07001433 workSource = _ws;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001434 alarmClock = _info;
1435 userId = _userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001436 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001437
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001438 public static String makeTag(PendingIntent pi, int type) {
1439 return pi.getTag(type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
1440 ? "*walarm*:" : "*alarm*:");
1441 }
1442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001444 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001445 StringBuilder sb = new StringBuilder(128);
1446 sb.append("Alarm{");
1447 sb.append(Integer.toHexString(System.identityHashCode(this)));
1448 sb.append(" type ");
1449 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001450 sb.append(" when ");
1451 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001452 sb.append(" ");
1453 sb.append(operation.getTargetPackage());
1454 sb.append('}');
1455 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 }
1457
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001458 public void dump(PrintWriter pw, String prefix, long nowRTC, long nowELAPSED,
1459 SimpleDateFormat sdf) {
1460 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
1461 pw.print(prefix); pw.print("tag="); pw.println(tag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001462 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001463 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
1464 nowELAPSED, pw);
1465 if (isRtc) {
1466 pw.print(" when="); pw.print(sdf.format(new Date(when)));
1467 } else {
1468 pw.print(" when="); TimeUtils.formatDuration(when, nowELAPSED, pw);
1469 }
1470 pw.println();
1471 pw.print(prefix); pw.print("window="); pw.print(windowLength);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001472 pw.print(" repeatInterval="); pw.print(repeatInterval);
1473 pw.print(" count="); pw.println(count);
1474 pw.print(prefix); pw.print("operation="); pw.println(operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 }
1476 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001477
Christopher Tatee0a22b32013-07-11 14:43:13 -07001478 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
1479 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07001480 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
1481 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001482 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07001483 break;
1484 }
1485
Christopher Tatee0a22b32013-07-11 14:43:13 -07001486 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07001487 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
1488 Alarm a = b.alarms.get(nextAlarm);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001489 WakeupEvent e = new WakeupEvent(nowRTC,
1490 a.operation.getCreatorUid(),
1491 a.operation.getIntent().getAction());
1492 mRecentWakeups.add(e);
1493 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001494 }
1495 }
1496
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001497 long currentNonWakeupFuzzLocked(long nowELAPSED) {
1498 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
1499 if (timeSinceOn < 5*60*1000) {
1500 // If the screen has been off for 5 minutes, only delay by at most two minutes.
1501 return 2*60*1000;
1502 } else if (timeSinceOn < 30*60*1000) {
1503 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
1504 return 15*60*1000;
1505 } else {
1506 // Otherwise, we will delay by at most an hour.
1507 return 60*60*1000;
1508 }
1509 }
1510
1511 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
1512 if (mInteractive) {
1513 return false;
1514 }
1515 if (mLastAlarmDeliveryTime <= 0) {
1516 return false;
1517 }
1518 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime > nowELAPSED) {
1519 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
1520 // and the next delivery time is in the past, then just deliver them all. This
1521 // avoids bugs where we get stuck in a loop trying to poll for alarms.
1522 return false;
1523 }
1524 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
1525 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
1526 }
1527
1528 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
1529 mLastAlarmDeliveryTime = nowELAPSED;
1530 for (int i=0; i<triggerList.size(); i++) {
1531 Alarm alarm = triggerList.get(i);
1532 try {
1533 if (localLOGV) Slog.v(TAG, "sending alarm " + alarm);
1534 alarm.operation.send(getContext(), 0,
1535 mBackgroundIntent.putExtra(
1536 Intent.EXTRA_ALARM_COUNT, alarm.count),
1537 mResultReceiver, mHandler);
1538
1539 // we have an active broadcast so stay awake.
1540 if (mBroadcastRefCount == 0) {
1541 setWakelockWorkSource(alarm.operation, alarm.workSource,
1542 alarm.type, alarm.tag, true);
1543 mWakeLock.acquire();
1544 }
1545 final InFlight inflight = new InFlight(AlarmManagerService.this,
1546 alarm.operation, alarm.workSource, alarm.type, alarm.tag);
1547 mInFlight.add(inflight);
1548 mBroadcastRefCount++;
1549
1550 final BroadcastStats bs = inflight.mBroadcastStats;
1551 bs.count++;
1552 if (bs.nesting == 0) {
1553 bs.nesting = 1;
1554 bs.startTime = nowELAPSED;
1555 } else {
1556 bs.nesting++;
1557 }
1558 final FilterStats fs = inflight.mFilterStats;
1559 fs.count++;
1560 if (fs.nesting == 0) {
1561 fs.nesting = 1;
1562 fs.startTime = nowELAPSED;
1563 } else {
1564 fs.nesting++;
1565 }
1566 if (alarm.type == ELAPSED_REALTIME_WAKEUP
1567 || alarm.type == RTC_WAKEUP) {
1568 bs.numWakeup++;
1569 fs.numWakeup++;
1570 if (alarm.workSource != null && alarm.workSource.size() > 0) {
1571 for (int wi=0; wi<alarm.workSource.size(); wi++) {
1572 ActivityManagerNative.noteWakeupAlarm(
1573 alarm.operation, alarm.workSource.get(wi),
1574 alarm.workSource.getName(wi));
1575 }
1576 } else {
1577 ActivityManagerNative.noteWakeupAlarm(
1578 alarm.operation, -1, null);
1579 }
1580 }
1581 } catch (PendingIntent.CanceledException e) {
1582 if (alarm.repeatInterval > 0) {
1583 // This IntentSender is no longer valid, but this
1584 // is a repeating alarm, so toss the hoser.
1585 removeImpl(alarm.operation);
1586 }
1587 } catch (RuntimeException e) {
1588 Slog.w(TAG, "Failure sending alarm.", e);
1589 }
1590 }
1591 }
1592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001593 private class AlarmThread extends Thread
1594 {
1595 public AlarmThread()
1596 {
1597 super("AlarmManager");
1598 }
1599
1600 public void run()
1601 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07001602 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
1603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001604 while (true)
1605 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001606 int result = waitForAlarm(mNativeData);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001607
1608 triggerList.clear();
1609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 if ((result & TIME_CHANGED_MASK) != 0) {
Christopher Tate385e4982013-07-23 18:22:29 -07001611 if (DEBUG_BATCH) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001612 Slog.v(TAG, "Time changed notification from kernel; rebatching");
Christopher Tate385e4982013-07-23 18:22:29 -07001613 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001614 removeImpl(mTimeTickSender);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001615 rebatchAllAlarms();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001616 mClockReceiver.scheduleTimeTickEvent();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001617 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
Dianne Hackborn89ba6752011-01-23 16:51:16 -08001618 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1619 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001620 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621 }
1622
1623 synchronized (mLock) {
1624 final long nowRTC = System.currentTimeMillis();
1625 final long nowELAPSED = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001626 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 TAG, "Checking for alarms... rtc=" + nowRTC
1628 + ", elapsed=" + nowELAPSED);
1629
Christopher Tate18a75f12013-07-01 18:18:59 -07001630 if (WAKEUP_STATS) {
1631 if ((result & IS_WAKEUP_MASK) != 0) {
1632 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
1633 int n = 0;
1634 for (WakeupEvent event : mRecentWakeups) {
1635 if (event.when > newEarliest) break;
1636 n++; // number of now-stale entries at the list head
1637 }
1638 for (int i = 0; i < n; i++) {
1639 mRecentWakeups.remove();
1640 }
1641
Christopher Tatee0a22b32013-07-11 14:43:13 -07001642 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Christopher Tate18a75f12013-07-01 18:18:59 -07001643 }
1644 }
1645
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001646 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
1647 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
1648 // if there are no wakeup alarms and the screen is off, we can
1649 // delay what we have so far until the future.
1650 if (mPendingNonWakeupAlarms.size() == 0) {
1651 mStartCurrentDelayTime = nowELAPSED;
1652 mNextNonWakeupDeliveryTime = nowELAPSED
1653 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001655 mPendingNonWakeupAlarms.addAll(triggerList);
1656 mNumDelayedAlarms += triggerList.size();
1657 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001658 updateNextAlarmClockLocked();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001659 } else {
1660 // now deliver the alarm intents; if there are pending non-wakeup
1661 // alarms, we need to merge them in to the list. note we don't
1662 // just deliver them first because we generally want non-wakeup
1663 // alarms delivered after wakeup alarms.
1664 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001665 updateNextAlarmClockLocked();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001666 if (mPendingNonWakeupAlarms.size() > 0) {
1667 triggerList.addAll(mPendingNonWakeupAlarms);
1668 Collections.sort(triggerList, mAlarmDispatchComparator);
1669 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1670 mTotalDelayTime += thisDelayTime;
1671 if (mMaxDelayTime < thisDelayTime) {
1672 mMaxDelayTime = thisDelayTime;
1673 }
1674 mPendingNonWakeupAlarms.clear();
1675 }
1676 deliverAlarmsLocked(triggerList, nowELAPSED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 }
1678 }
1679 }
1680 }
1681 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07001682
David Christieebe51fc2013-07-26 13:23:29 -07001683 /**
1684 * Attribute blame for a WakeLock.
1685 * @param pi PendingIntent to attribute blame to if ws is null.
1686 * @param ws WorkSource to attribute blame.
1687 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001688 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
1689 boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07001690 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001691 final boolean unimportant = pi == mTimeTickSender;
1692 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07001693 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001694 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07001695 } else {
1696 mWakeLock.setHistoryTag(null);
1697 }
1698 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07001699 if (ws != null) {
1700 mWakeLock.setWorkSource(ws);
1701 return;
1702 }
1703
Christopher Tatec4a07d12012-04-06 14:19:13 -07001704 final int uid = ActivityManagerNative.getDefault()
1705 .getUidForIntentSender(pi.getTarget());
1706 if (uid >= 0) {
1707 mWakeLock.setWorkSource(new WorkSource(uid));
1708 return;
1709 }
1710 } catch (Exception e) {
1711 }
1712
1713 // Something went wrong; fall back to attributing the lock to the OS
1714 mWakeLock.setWorkSource(null);
1715 }
1716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 private class AlarmHandler extends Handler {
1718 public static final int ALARM_EVENT = 1;
1719 public static final int MINUTE_CHANGE_EVENT = 2;
1720 public static final int DATE_CHANGE_EVENT = 3;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001721 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722
1723 public AlarmHandler() {
1724 }
1725
1726 public void handleMessage(Message msg) {
1727 if (msg.what == ALARM_EVENT) {
1728 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
1729 synchronized (mLock) {
1730 final long nowRTC = System.currentTimeMillis();
Christopher Tatee0a22b32013-07-11 14:43:13 -07001731 final long nowELAPSED = SystemClock.elapsedRealtime();
1732 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001733 updateNextAlarmClockLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 // now trigger the alarms without the lock held
Dianne Hackborn390517b2013-05-30 15:03:32 -07001737 for (int i=0; i<triggerList.size(); i++) {
1738 Alarm alarm = triggerList.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 try {
1740 alarm.operation.send();
1741 } catch (PendingIntent.CanceledException e) {
1742 if (alarm.repeatInterval > 0) {
1743 // This IntentSender is no longer valid, but this
1744 // is a repeating alarm, so toss the hoser.
Adam Lesinski182f73f2013-12-05 16:48:06 -08001745 removeImpl(alarm.operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001746 }
1747 }
1748 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001749 } else if (msg.what == SEND_NEXT_ALARM_CLOCK_CHANGED) {
1750 sendNextAlarmClockChanged();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001751 }
1752 }
1753 }
1754
1755 class ClockReceiver extends BroadcastReceiver {
1756 public ClockReceiver() {
1757 IntentFilter filter = new IntentFilter();
1758 filter.addAction(Intent.ACTION_TIME_TICK);
1759 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001760 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 }
1762
1763 @Override
1764 public void onReceive(Context context, Intent intent) {
1765 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001766 if (DEBUG_BATCH) {
1767 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
1768 }
1769 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
1771 // Since the kernel does not keep track of DST, we need to
1772 // reset the TZ information at the beginning of each day
1773 // based off of the current Zone gmt offset + userspace tracked
1774 // daylight savings information.
1775 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02001776 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001777 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07001778 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779 }
1780 }
1781
1782 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07001783 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09001784 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07001785
1786 // Schedule this event for the amount of time that it would take to get to
1787 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09001788 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07001789
David Christieebe51fc2013-07-26 13:23:29 -07001790 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08001791 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Adrian Roosc42a1e12014-07-07 23:35:53 +02001792 0, mTimeTickSender, true, workSource, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001793 }
Christopher Tate385e4982013-07-23 18:22:29 -07001794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001795 public void scheduleDateChangedEvent() {
1796 Calendar calendar = Calendar.getInstance();
1797 calendar.setTimeInMillis(System.currentTimeMillis());
1798 calendar.set(Calendar.HOUR, 0);
1799 calendar.set(Calendar.MINUTE, 0);
1800 calendar.set(Calendar.SECOND, 0);
1801 calendar.set(Calendar.MILLISECOND, 0);
1802 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07001803
1804 final WorkSource workSource = null; // Let system take blame for date change events.
Adrian Roosc42a1e12014-07-07 23:35:53 +02001805 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, true, workSource,
1806 null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 }
1808 }
1809
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001810 class InteractiveStateReceiver extends BroadcastReceiver {
1811 public InteractiveStateReceiver() {
1812 IntentFilter filter = new IntentFilter();
1813 filter.addAction(Intent.ACTION_SCREEN_OFF);
1814 filter.addAction(Intent.ACTION_SCREEN_ON);
1815 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
1816 getContext().registerReceiver(this, filter);
1817 }
1818
1819 @Override
1820 public void onReceive(Context context, Intent intent) {
1821 synchronized (mLock) {
1822 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
1823 }
1824 }
1825 }
1826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001827 class UninstallReceiver extends BroadcastReceiver {
1828 public UninstallReceiver() {
1829 IntentFilter filter = new IntentFilter();
1830 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1831 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001832 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08001834 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001835 // Register for events related to sdcard installation.
1836 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001837 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001838 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001839 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 }
1841
1842 @Override
1843 public void onReceive(Context context, Intent intent) {
1844 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001845 String action = intent.getAction();
1846 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001847 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
1848 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
1849 for (String packageName : pkgList) {
1850 if (lookForPackageLocked(packageName)) {
1851 setResultCode(Activity.RESULT_OK);
1852 return;
1853 }
1854 }
1855 return;
1856 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001857 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001858 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
1859 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
1860 if (userHandle >= 0) {
1861 removeUserLocked(userHandle);
1862 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001863 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08001864 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
1865 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
1866 // This package is being updated; don't kill its alarms.
1867 return;
1868 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001869 Uri data = intent.getData();
1870 if (data != null) {
1871 String pkg = data.getSchemeSpecificPart();
1872 if (pkg != null) {
1873 pkgList = new String[]{pkg};
1874 }
1875 }
1876 }
1877 if (pkgList != null && (pkgList.length > 0)) {
1878 for (String pkg : pkgList) {
1879 removeLocked(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001880 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
1881 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
1882 if (uidStats.remove(pkg) != null) {
1883 if (uidStats.size() <= 0) {
1884 mBroadcastStats.removeAt(i);
1885 }
1886 }
1887 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001888 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001889 }
1890 }
1891 }
1892 }
1893
1894 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001895 String pkg = pi.getCreatorPackage();
1896 int uid = pi.getCreatorUid();
1897 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
1898 if (uidStats == null) {
1899 uidStats = new ArrayMap<String, BroadcastStats>();
1900 mBroadcastStats.put(uid, uidStats);
1901 }
1902 BroadcastStats bs = uidStats.get(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001903 if (bs == null) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001904 bs = new BroadcastStats(uid, pkg);
1905 uidStats.put(pkg, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 }
1907 return bs;
1908 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001910 class ResultReceiver implements PendingIntent.OnFinished {
1911 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
1912 String resultData, Bundle resultExtras) {
1913 synchronized (mLock) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001914 InFlight inflight = null;
1915 for (int i=0; i<mInFlight.size(); i++) {
1916 if (mInFlight.get(i).mPendingIntent == pi) {
1917 inflight = mInFlight.remove(i);
1918 break;
1919 }
1920 }
1921 if (inflight != null) {
1922 final long nowELAPSED = SystemClock.elapsedRealtime();
1923 BroadcastStats bs = inflight.mBroadcastStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001924 bs.nesting--;
1925 if (bs.nesting <= 0) {
1926 bs.nesting = 0;
Dianne Hackborn81038902012-11-26 17:04:09 -08001927 bs.aggregateTime += nowELAPSED - bs.startTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001929 FilterStats fs = inflight.mFilterStats;
1930 fs.nesting--;
1931 if (fs.nesting <= 0) {
1932 fs.nesting = 0;
1933 fs.aggregateTime += nowELAPSED - fs.startTime;
1934 }
1935 } else {
1936 mLog.w("No in-flight alarm for " + pi + " " + intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 }
1938 mBroadcastRefCount--;
1939 if (mBroadcastRefCount == 0) {
1940 mWakeLock.release();
Dianne Hackborn81038902012-11-26 17:04:09 -08001941 if (mInFlight.size() > 0) {
1942 mLog.w("Finished all broadcasts with " + mInFlight.size()
1943 + " remaining inflights");
1944 for (int i=0; i<mInFlight.size(); i++) {
1945 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
1946 }
1947 mInFlight.clear();
1948 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07001949 } else {
1950 // the next of our alarms is now in flight. reattribute the wakelock.
Dianne Hackborn81038902012-11-26 17:04:09 -08001951 if (mInFlight.size() > 0) {
David Christieebe51fc2013-07-26 13:23:29 -07001952 InFlight inFlight = mInFlight.get(0);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001953 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001954 inFlight.mAlarmType, inFlight.mTag, false);
Christopher Tatec4a07d12012-04-06 14:19:13 -07001955 } else {
1956 // should never happen
Dianne Hackborn81038902012-11-26 17:04:09 -08001957 mLog.w("Alarm wakelock still held but sent queue empty");
Christopher Tatec4a07d12012-04-06 14:19:13 -07001958 mWakeLock.setWorkSource(null);
1959 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 }
1961 }
1962 }
1963 }
1964}