blob: 52310b1ddebc701a505ddd662036472f9c9ac6fe [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;
Christopher Tate57ceaaa2013-07-19 16:30:43 -070022import android.app.AlarmManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import android.app.IAlarmManager;
24import android.app.PendingIntent;
25import android.content.BroadcastReceiver;
26import 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;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070037import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import 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 Tate1590f1e2014-10-02 17:27:57 -070062import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -070063import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +020064import java.util.Locale;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070065import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import java.util.TimeZone;
67
Christopher Tatee0a22b32013-07-11 14:43:13 -070068import static android.app.AlarmManager.RTC_WAKEUP;
69import static android.app.AlarmManager.RTC;
70import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
71import static android.app.AlarmManager.ELAPSED_REALTIME;
72
Dianne Hackborn81038902012-11-26 17:04:09 -080073import com.android.internal.util.LocalLog;
74
Adam Lesinski182f73f2013-12-05 16:48:06 -080075class AlarmManagerService extends SystemService {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076 // The threshold for how long an alarm can be late before we print a
77 // warning message. The time duration is in milliseconds.
78 private static final long LATE_ALARM_THRESHOLD = 10 * 1000;
Christopher Tatee0a22b32013-07-11 14:43:13 -070079
Christopher Tate498c6cb2014-11-17 16:09:27 -080080 // Minimum futurity of a new alarm
81 private static final long MIN_FUTURITY = 5 * 1000; // 5 seconds, in millis
82
83 // Minimum alarm recurrence interval
84 private static final long MIN_INTERVAL = 60 * 1000; // one minute, in millis
85
Christopher Tatee0a22b32013-07-11 14:43:13 -070086 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
87 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -080088 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -070089 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -080090 static final int TIME_CHANGED_MASK = 1 << 16;
91 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -080092
Christopher Tatee0a22b32013-07-11 14:43:13 -070093 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -080094 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -080095
Adam Lesinski182f73f2013-12-05 16:48:06 -080096 static final String TAG = "AlarmManager";
97 static final String ClockReceiver_TAG = "ClockReceiver";
98 static final boolean localLOGV = false;
99 static final boolean DEBUG_BATCH = localLOGV || false;
100 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200101 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700102 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800103 static final int ALARM_EVENT = 1;
104 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200105
Adam Lesinski182f73f2013-12-05 16:48:06 -0800106 static final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800108 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109
Adam Lesinski182f73f2013-12-05 16:48:06 -0800110 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700111
Adrian Roosc42a1e12014-07-07 23:35:53 +0200112 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT = new Intent(
113 AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED);
114
Adam Lesinski182f73f2013-12-05 16:48:06 -0800115 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800116
Adam Lesinski182f73f2013-12-05 16:48:06 -0800117 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800118
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800119 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800120 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700121 private long mNextNonWakeup;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800122 int mBroadcastRefCount = 0;
123 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700124 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700125 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<Alarm>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800126 ArrayList<InFlight> mInFlight = new ArrayList<InFlight>();
127 final AlarmHandler mHandler = new AlarmHandler();
128 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700129 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130 private UninstallReceiver mUninstallReceiver;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800131 final ResultReceiver mResultReceiver = new ResultReceiver();
132 PendingIntent mTimeTickSender;
133 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700134 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700135 boolean mInteractive = true;
136 long mNonInteractiveStartTime;
137 long mNonInteractiveTime;
138 long mLastAlarmDeliveryTime;
139 long mStartCurrentDelayTime;
140 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700141 long mLastTimeChangeClockTime;
142 long mLastTimeChangeRealtime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700143 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800144
Jose Lima235510e2014-08-13 12:50:01 -0700145 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
146 new SparseArray<>();
147 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
148 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200149 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
150 new SparseBooleanArray();
151 private boolean mNextAlarmClockMayChange;
152
153 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700154 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
155 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200156
Christopher Tate1590f1e2014-10-02 17:27:57 -0700157 // Alarm delivery ordering bookkeeping
158 static final int PRIO_TICK = 0;
159 static final int PRIO_WAKEUP = 1;
160 static final int PRIO_NORMAL = 2;
161
162 class PriorityClass {
163 int seq;
164 int priority;
165
166 PriorityClass() {
167 seq = mCurrentSeq - 1;
168 priority = PRIO_NORMAL;
169 }
170 }
171
172 final HashMap<String, PriorityClass> mPriorities =
173 new HashMap<String, PriorityClass>();
174 int mCurrentSeq = 0;
175
Christopher Tate18a75f12013-07-01 18:18:59 -0700176 class WakeupEvent {
177 public long when;
178 public int uid;
179 public String action;
180
181 public WakeupEvent(long theTime, int theUid, String theAction) {
182 when = theTime;
183 uid = theUid;
184 action = theAction;
185 }
186 }
187
Adam Lesinski182f73f2013-12-05 16:48:06 -0800188 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
189 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700190
Adrian Roosc42a1e12014-07-07 23:35:53 +0200191 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700192 long start; // These endpoints are always in ELAPSED
193 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700194 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700195
196 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
197
198 Batch() {
199 start = 0;
200 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700201 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700202 }
203
204 Batch(Alarm seed) {
205 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700206 end = seed.maxWhenElapsed;
207 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700208 alarms.add(seed);
209 }
210
211 int size() {
212 return alarms.size();
213 }
214
215 Alarm get(int index) {
216 return alarms.get(index);
217 }
218
219 boolean canHold(long whenElapsed, long maxWhen) {
220 return (end >= whenElapsed) && (start <= maxWhen);
221 }
222
223 boolean add(Alarm alarm) {
224 boolean newStart = false;
225 // narrows the batch if necessary; presumes that canHold(alarm) is true
226 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
227 if (index < 0) {
228 index = 0 - index - 1;
229 }
230 alarms.add(index, alarm);
231 if (DEBUG_BATCH) {
232 Slog.v(TAG, "Adding " + alarm + " to " + this);
233 }
234 if (alarm.whenElapsed > start) {
235 start = alarm.whenElapsed;
236 newStart = true;
237 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700238 if (alarm.maxWhenElapsed < end) {
239 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700240 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700241 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700242
243 if (DEBUG_BATCH) {
244 Slog.v(TAG, " => now " + this);
245 }
246 return newStart;
247 }
248
249 boolean remove(final PendingIntent operation) {
250 boolean didRemove = false;
251 long newStart = 0; // recalculate endpoints as we go
252 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700253 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700254 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700255 Alarm alarm = alarms.get(i);
256 if (alarm.operation.equals(operation)) {
257 alarms.remove(i);
258 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200259 if (alarm.alarmClock != null) {
260 mNextAlarmClockMayChange = true;
261 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700262 } else {
263 if (alarm.whenElapsed > newStart) {
264 newStart = alarm.whenElapsed;
265 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700266 if (alarm.maxWhenElapsed < newEnd) {
267 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700268 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700269 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700270 i++;
271 }
272 }
273 if (didRemove) {
274 // commit the new batch bounds
275 start = newStart;
276 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700277 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700278 }
279 return didRemove;
280 }
281
282 boolean remove(final String packageName) {
283 boolean didRemove = false;
284 long newStart = 0; // recalculate endpoints as we go
285 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700286 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700287 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700288 Alarm alarm = alarms.get(i);
289 if (alarm.operation.getTargetPackage().equals(packageName)) {
290 alarms.remove(i);
291 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200292 if (alarm.alarmClock != null) {
293 mNextAlarmClockMayChange = true;
294 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700295 } else {
296 if (alarm.whenElapsed > newStart) {
297 newStart = alarm.whenElapsed;
298 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700299 if (alarm.maxWhenElapsed < newEnd) {
300 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700301 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700302 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700303 i++;
304 }
305 }
306 if (didRemove) {
307 // commit the new batch bounds
308 start = newStart;
309 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700310 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700311 }
312 return didRemove;
313 }
314
315 boolean remove(final int userHandle) {
316 boolean didRemove = false;
317 long newStart = 0; // recalculate endpoints as we go
318 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700319 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700320 Alarm alarm = alarms.get(i);
321 if (UserHandle.getUserId(alarm.operation.getCreatorUid()) == userHandle) {
322 alarms.remove(i);
323 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200324 if (alarm.alarmClock != null) {
325 mNextAlarmClockMayChange = true;
326 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700327 } else {
328 if (alarm.whenElapsed > newStart) {
329 newStart = alarm.whenElapsed;
330 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700331 if (alarm.maxWhenElapsed < newEnd) {
332 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700333 }
334 i++;
335 }
336 }
337 if (didRemove) {
338 // commit the new batch bounds
339 start = newStart;
340 end = newEnd;
341 }
342 return didRemove;
343 }
344
345 boolean hasPackage(final String packageName) {
346 final int N = alarms.size();
347 for (int i = 0; i < N; i++) {
348 Alarm a = alarms.get(i);
349 if (a.operation.getTargetPackage().equals(packageName)) {
350 return true;
351 }
352 }
353 return false;
354 }
355
356 boolean hasWakeups() {
357 final int N = alarms.size();
358 for (int i = 0; i < N; i++) {
359 Alarm a = alarms.get(i);
360 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
361 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
362 return true;
363 }
364 }
365 return false;
366 }
367
368 @Override
369 public String toString() {
370 StringBuilder b = new StringBuilder(40);
371 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
372 b.append(" num="); b.append(size());
373 b.append(" start="); b.append(start);
374 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700375 if (flags != 0) {
376 b.append(" flgs=0x");
377 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700378 }
379 b.append('}');
380 return b.toString();
381 }
382 }
383
384 static class BatchTimeOrder implements Comparator<Batch> {
385 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800386 long when1 = b1.start;
387 long when2 = b2.start;
388 if (when1 - when2 > 0) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700389 return 1;
390 }
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800391 if (when1 - when2 < 0) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700392 return -1;
393 }
394 return 0;
395 }
396 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800397
398 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
399 @Override
400 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700401 // priority class trumps everything. TICK < WAKEUP < NORMAL
402 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
403 return -1;
404 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
405 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800406 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700407
408 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800409 if (lhs.whenElapsed < rhs.whenElapsed) {
410 return -1;
411 } else if (lhs.whenElapsed > rhs.whenElapsed) {
412 return 1;
413 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700414
415 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800416 return 0;
417 }
418 };
419
Christopher Tate1590f1e2014-10-02 17:27:57 -0700420 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
421 final int N = alarms.size();
422 for (int i = 0; i < N; i++) {
423 Alarm a = alarms.get(i);
424
425 final int alarmPrio;
426 if (Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
427 alarmPrio = PRIO_TICK;
428 } else if (a.wakeup) {
429 alarmPrio = PRIO_WAKEUP;
430 } else {
431 alarmPrio = PRIO_NORMAL;
432 }
433
434 PriorityClass packagePrio = a.priorityClass;
435 if (packagePrio == null) packagePrio = mPriorities.get(a.operation.getCreatorPackage());
436 if (packagePrio == null) {
437 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
438 mPriorities.put(a.operation.getCreatorPackage(), packagePrio);
439 }
440 a.priorityClass = packagePrio;
441
442 if (packagePrio.seq != mCurrentSeq) {
443 // first alarm we've seen in the current delivery generation from this package
444 packagePrio.priority = alarmPrio;
445 packagePrio.seq = mCurrentSeq;
446 } else {
447 // Multiple alarms from this package being delivered in this generation;
448 // bump the package's delivery class if it's warranted.
449 // TICK < WAKEUP < NORMAL
450 if (alarmPrio < packagePrio.priority) {
451 packagePrio.priority = alarmPrio;
452 }
453 }
454 }
455 }
456
Christopher Tatee0a22b32013-07-11 14:43:13 -0700457 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800458 static final long MIN_FUZZABLE_INTERVAL = 10000;
459 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700460 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
461
462 // set to null if in idle mode; while in this mode, any alarms we don't want
463 // to run during this time are placed in mPendingWhileIdleAlarms
464 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700465 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700466 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700467
Jeff Brownb880d882014-02-10 19:47:07 -0800468 public AlarmManagerService(Context context) {
469 super(context);
470 }
471
Christopher Tatee0a22b32013-07-11 14:43:13 -0700472 static long convertToElapsed(long when, int type) {
473 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
474 if (isRtc) {
475 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
476 }
477 return when;
478 }
479
480 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
481 // calculate the end of our nominal delivery window for the alarm.
482 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
483 // Current heuristic: batchable window is 75% of either the recurrence interval
484 // [for a periodic alarm] or of the time from now to the desired delivery time,
485 // with a minimum delay/interval of 10 seconds, under which we will simply not
486 // defer the alarm.
487 long futurity = (interval == 0)
488 ? (triggerAtTime - now)
489 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700490 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700491 futurity = 0;
492 }
493 return triggerAtTime + (long)(.75 * futurity);
494 }
495
496 // returns true if the batch was added at the head
497 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
498 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
499 if (index < 0) {
500 index = 0 - index - 1;
501 }
502 list.add(index, newBatch);
503 return (index == 0);
504 }
505
Christopher Tate385e4982013-07-23 18:22:29 -0700506 // Return the index of the matching batch, or -1 if none found.
507 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700508 final int N = mAlarmBatches.size();
509 for (int i = 0; i < N; i++) {
510 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700511 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700512 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700513 }
514 }
Christopher Tate385e4982013-07-23 18:22:29 -0700515 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700516 }
517
518 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
519 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700520 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700521 rebatchAllAlarmsLocked(true);
522 }
523 }
524
525 void rebatchAllAlarmsLocked(boolean doValidate) {
526 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
527 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700528 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700529 final long nowElapsed = SystemClock.elapsedRealtime();
530 final int oldBatches = oldSet.size();
531 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
532 Batch batch = oldSet.get(batchNum);
533 final int N = batch.size();
534 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700535 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700536 }
537 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700538 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
539 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
540 + " to " + mPendingIdleUntil);
541 if (mPendingIdleUntil == null) {
542 // Somehow we lost this... we need to restore all of the pending alarms.
543 restorePendingWhileIdleAlarmsLocked();
544 }
545 }
546 rescheduleKernelAlarmsLocked();
547 updateNextAlarmClockLocked();
548 }
549
550 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
551 a.when = a.origWhen;
552 long whenElapsed = convertToElapsed(a.when, a.type);
553 final long maxElapsed;
554 if (a.whenElapsed == a.maxWhenElapsed) {
555 // Exact
556 maxElapsed = whenElapsed;
557 } else {
558 // Not exact. Preserve any explicit window, otherwise recalculate
559 // the window based on the alarm's new futurity. Note that this
560 // reflects a policy of preferring timely to deferred delivery.
561 maxElapsed = (a.windowLength > 0)
562 ? (whenElapsed + a.windowLength)
563 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
564 }
565 a.whenElapsed = whenElapsed;
566 a.maxWhenElapsed = maxElapsed;
567 setImplLocked(a, true, doValidate);
568 }
569
570 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackborn35d54032015-04-23 10:30:43 -0700571 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700572 if (mPendingWhileIdleAlarms.size() > 0) {
573 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
574 mPendingWhileIdleAlarms = new ArrayList<>();
575 final long nowElapsed = SystemClock.elapsedRealtime();
576 for (int i=alarms.size() - 1; i >= 0; i--) {
577 Alarm a = alarms.get(i);
578 reAddAlarmLocked(a, nowElapsed, false);
579 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700580 }
Dianne Hackborn35d54032015-04-23 10:30:43 -0700581
582 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700583 rescheduleKernelAlarmsLocked();
584 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -0700585
586 // And send a TIME_TICK right now, since it is important to get the UI updated.
587 try {
588 mTimeTickSender.send();
589 } catch (PendingIntent.CanceledException e) {
590 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700591 }
592
Adam Lesinski182f73f2013-12-05 16:48:06 -0800593 static final class InFlight extends Intent {
Dianne Hackborn81038902012-11-26 17:04:09 -0800594 final PendingIntent mPendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700595 final WorkSource mWorkSource;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700596 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800597 final BroadcastStats mBroadcastStats;
598 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800599 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800600
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800601 InFlight(AlarmManagerService service, PendingIntent pendingIntent, WorkSource workSource,
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700602 int alarmType, String tag, long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800603 mPendingIntent = pendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700604 mWorkSource = workSource;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700605 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800606 mBroadcastStats = service.getStatsLocked(pendingIntent);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700607 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -0800608 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700609 fs = new FilterStats(mBroadcastStats, mTag);
610 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -0800611 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700612 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -0800613 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800614 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800615 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800616 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800617
Adam Lesinski182f73f2013-12-05 16:48:06 -0800618 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -0800619 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700620 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800621
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700622 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800623 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800624 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625 int numWakeup;
626 long startTime;
627 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -0800628
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700629 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800630 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700631 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800632 }
633 }
634
Adam Lesinski182f73f2013-12-05 16:48:06 -0800635 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800636 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800637 final String mPackageName;
638
639 long aggregateTime;
640 int count;
641 int numWakeup;
642 long startTime;
643 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700644 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -0800645
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800646 BroadcastStats(int uid, String packageName) {
647 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800648 mPackageName = packageName;
649 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800650 }
651
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800652 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
653 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700654
655 int mNumDelayedAlarms = 0;
656 long mTotalDelayTime = 0;
657 long mMaxDelayTime = 0;
658
Adam Lesinski182f73f2013-12-05 16:48:06 -0800659 @Override
660 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800661 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800662 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800663
664 // We have to set current TimeZone info to kernel
665 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -0800666 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800667
Adam Lesinski182f73f2013-12-05 16:48:06 -0800668 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800669 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800670
Adam Lesinski182f73f2013-12-05 16:48:06 -0800671 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700673 Intent.FLAG_RECEIVER_REGISTERED_ONLY
674 | Intent.FLAG_RECEIVER_FOREGROUND), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700675 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800676 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
677 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800678 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700679 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680
681 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -0800682 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 mClockReceiver.scheduleTimeTickEvent();
684 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700685 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800686 mUninstallReceiver = new UninstallReceiver();
687
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800688 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800689 AlarmThread waitThread = new AlarmThread();
690 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800692 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800694
695 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800697
698 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 protected void finalize() throws Throwable {
700 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800701 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702 } finally {
703 super.finalize();
704 }
705 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700706
Adam Lesinski182f73f2013-12-05 16:48:06 -0800707 void setTimeZoneImpl(String tz) {
708 if (TextUtils.isEmpty(tz)) {
709 return;
David Christieebe51fc2013-07-26 13:23:29 -0700710 }
711
Adam Lesinski182f73f2013-12-05 16:48:06 -0800712 TimeZone zone = TimeZone.getTimeZone(tz);
713 // Prevent reentrant calls from stepping on each other when writing
714 // the time zone property
715 boolean timeZoneWasChanged = false;
716 synchronized (this) {
717 String current = SystemProperties.get(TIMEZONE_PROPERTY);
718 if (current == null || !current.equals(zone.getID())) {
719 if (localLOGV) {
720 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
721 }
722 timeZoneWasChanged = true;
723 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
724 }
725
726 // Update the kernel timezone information
727 // Kernel tracks time offsets as 'minutes west of GMT'
728 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800729 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -0800730 }
731
732 TimeZone.setDefault(null);
733
734 if (timeZoneWasChanged) {
735 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
736 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
737 intent.putExtra("time-zone", zone.getID());
738 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
739 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700741
Adam Lesinski182f73f2013-12-05 16:48:06 -0800742 void removeImpl(PendingIntent operation) {
743 if (operation == null) {
744 return;
745 }
746 synchronized (mLock) {
747 removeLocked(operation);
748 }
749 }
750
751 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700752 PendingIntent operation, int flags, WorkSource workSource,
Jose Lima235510e2014-08-13 12:50:01 -0700753 AlarmManager.AlarmClockInfo alarmClock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 if (operation == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800755 Slog.w(TAG, "set/setRepeating ignored because there is no intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 return;
757 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700758
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700759 // Sanity check the window length. This will catch people mistakenly
760 // trying to pass an end-of-window timestamp rather than a duration.
761 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
762 Slog.w(TAG, "Window length " + windowLength
763 + "ms suspiciously long; limiting to 1 hour");
764 windowLength = AlarmManager.INTERVAL_HOUR;
765 }
766
Christopher Tate498c6cb2014-11-17 16:09:27 -0800767 // Sanity check the recurrence interval. This will catch people who supply
768 // seconds when the API expects milliseconds.
769 if (interval > 0 && interval < MIN_INTERVAL) {
770 Slog.w(TAG, "Suspiciously short interval " + interval
771 + " millis; expanding to " + (int)(MIN_INTERVAL/1000)
772 + " seconds");
773 interval = MIN_INTERVAL;
774 }
775
Christopher Tatee0a22b32013-07-11 14:43:13 -0700776 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
777 throw new IllegalArgumentException("Invalid alarm type " + type);
778 }
779
Christopher Tate5f221e82013-07-30 17:13:15 -0700780 if (triggerAtTime < 0) {
781 final long who = Binder.getCallingUid();
782 final long what = Binder.getCallingPid();
783 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + who
784 + " pid=" + what);
785 triggerAtTime = 0;
786 }
787
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700788 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -0800789 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
790 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
791 final long minTrigger = nowElapsed + MIN_FUTURITY;
792 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
793
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700794 final long maxElapsed;
795 if (windowLength == AlarmManager.WINDOW_EXACT) {
796 maxElapsed = triggerElapsed;
797 } else if (windowLength < 0) {
798 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
799 } else {
800 maxElapsed = triggerElapsed + windowLength;
801 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700802
Adrian Roosc42a1e12014-07-07 23:35:53 +0200803 final int userId = UserHandle.getCallingUserId();
804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700806 if (DEBUG_BATCH) {
807 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700808 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -0700809 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700810 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 }
Christopher Tate3e04b472013-10-21 17:51:31 -0700812 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700813 interval, operation, flags, true, workSource, alarmClock, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 }
815 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816
Christopher Tate3e04b472013-10-21 17:51:31 -0700817 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700818 long maxWhen, long interval, PendingIntent operation, int flags,
Jose Lima235510e2014-08-13 12:50:01 -0700819 boolean doValidate, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
820 int userId) {
Christopher Tate3e04b472013-10-21 17:51:31 -0700821 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700822 operation, workSource, flags, alarmClock, userId);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700823 removeLocked(operation);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700824 setImplLocked(a, false, doValidate);
825 }
Christopher Tateb8849c12011-02-08 13:39:01 -0800826
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700827 private void updateNextWakeFromIdleFuzzLocked() {
828 if (mNextWakeFromIdle != null) {
829
830 }
831 }
832
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700833 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
834 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700835 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700836 // The caller has given the time they want this to happen at, however we need
837 // to pull that earlier if there are existing alarms that have requested to
838 // bring us out of idle.
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700839 if (mNextWakeFromIdle != null) {
840 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700841 }
842 // Add fuzz to make the alarm go off some time before the actual desired time.
843 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700844 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700845 if (fuzz > 0) {
846 if (mRandom == null) {
847 mRandom = new Random();
848 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700849 final int delta = mRandom.nextInt(fuzz);
850 a.whenElapsed -= delta;
851 if (false) {
852 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
853 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
854 Slog.d(TAG, "Applied fuzz: " + fuzz);
855 Slog.d(TAG, "Final delta: " + delta);
856 Slog.d(TAG, "Final when: " + a.whenElapsed);
857 }
858 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700859 }
860
861 } else if (mPendingIdleUntil != null) {
862 // We currently have an idle until alarm scheduled; if the new alarm has
863 // not explicitly stated it wants to run while idle, then put it on hold.
864 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE|AlarmManager.FLAG_WAKE_FROM_IDLE))
865 == 0) {
866 mPendingWhileIdleAlarms.add(a);
867 return;
868 }
869 }
870
871 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
872 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -0700873 if (whichBatch < 0) {
874 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -0700875 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 } else {
Christopher Tate385e4982013-07-23 18:22:29 -0700877 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -0700878 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700879 // The start time of this batch advanced, so batch ordering may
880 // have just been broken. Move it to where it now belongs.
881 mAlarmBatches.remove(whichBatch);
882 addBatchLocked(mAlarmBatches, batch);
883 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884 }
885
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700886 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +0200887 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200888 }
889
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700890 boolean needRebatch = false;
891
892 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
893 mPendingIdleUntil = a;
894 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700895 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
896 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
897 mNextWakeFromIdle = a;
898 // If this wake from idle is earlier than whatever was previously scheduled,
899 // and we are currently idling, then we need to rebatch alarms in case the idle
900 // until time needs to be updated.
901 if (mPendingIdleUntil != null) {
902 needRebatch = true;
903 }
904 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700905 }
906
907 if (!rebatching) {
908 if (DEBUG_VALIDATE) {
909 if (doValidate && !validateConsistencyLocked()) {
910 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
911 + " when(hex)=" + Long.toHexString(a.when)
912 + " whenElapsed=" + a.whenElapsed
913 + " maxWhenElapsed=" + a.maxWhenElapsed
914 + " interval=" + a.repeatInterval + " op=" + a.operation
915 + " flags=0x" + Integer.toHexString(a.flags));
916 rebatchAllAlarmsLocked(false);
917 needRebatch = false;
918 }
919 }
920
921 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700922 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -0700923 }
Christopher Tate4cb338d2013-07-26 13:11:31 -0700924
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700925 rescheduleKernelAlarmsLocked();
926 updateNextAlarmClockLocked();
927 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700928 }
929
Adam Lesinski182f73f2013-12-05 16:48:06 -0800930 private final IBinder mService = new IAlarmManager.Stub() {
931 @Override
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700932 public void set(int type, long triggerAtTime, long windowLength, long interval, int flags,
Jose Lima235510e2014-08-13 12:50:01 -0700933 PendingIntent operation, WorkSource workSource,
934 AlarmManager.AlarmClockInfo alarmClock) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800935 if (workSource != null) {
936 getContext().enforceCallingPermission(
937 android.Manifest.permission.UPDATE_DEVICE_STATS,
938 "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -0700939 }
940
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700941 if (windowLength == AlarmManager.WINDOW_EXACT) {
942 flags |= AlarmManager.FLAG_STANDALONE;
943 }
944 if (alarmClock != null) {
945 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
946 }
947 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
948 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE;
949 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800950 setImpl(type, triggerAtTime, windowLength, interval, operation,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700951 flags, workSource, alarmClock);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800952 }
Christopher Tate89779822012-08-31 14:40:03 -0700953
Adam Lesinski182f73f2013-12-05 16:48:06 -0800954 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -0800955 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800956 getContext().enforceCallingOrSelfPermission(
957 "android.permission.SET_TIME",
958 "setTime");
959
Greg Hackmann0cab8962014-02-21 16:35:52 -0800960 if (mNativeData == 0) {
961 Slog.w(TAG, "Not setting time since no alarm driver is available.");
962 return false;
Christopher Tate89779822012-08-31 14:40:03 -0700963 }
Greg Hackmann0cab8962014-02-21 16:35:52 -0800964
965 synchronized (mLock) {
966 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800969
970 @Override
971 public void setTimeZone(String tz) {
972 getContext().enforceCallingOrSelfPermission(
973 "android.permission.SET_TIME_ZONE",
974 "setTimeZone");
975
976 final long oldId = Binder.clearCallingIdentity();
977 try {
978 setTimeZoneImpl(tz);
979 } finally {
980 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 }
982 }
Christopher Tate4cb338d2013-07-26 13:11:31 -0700983
Adam Lesinski182f73f2013-12-05 16:48:06 -0800984 @Override
985 public void remove(PendingIntent operation) {
986 removeImpl(operation);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700987
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 }
Christopher Tate4cb338d2013-07-26 13:11:31 -0700989
Adam Lesinski182f73f2013-12-05 16:48:06 -0800990 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700991 public long getNextWakeFromIdleTime() {
992 return getNextWakeFromIdleTimeImpl();
993 }
994
995 @Override
Jose Lima235510e2014-08-13 12:50:01 -0700996 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +0200997 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
998 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
999 "getNextAlarmClock", null);
1000
1001 return getNextAlarmClockImpl(userId);
1002 }
1003
1004 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001005 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1006 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1007 != PackageManager.PERMISSION_GRANTED) {
1008 pw.println("Permission Denial: can't dump AlarmManager from from pid="
1009 + Binder.getCallingPid()
1010 + ", uid=" + Binder.getCallingUid());
1011 return;
Christopher Tate4cb338d2013-07-26 13:11:31 -07001012 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001013
Adam Lesinski182f73f2013-12-05 16:48:06 -08001014 dumpImpl(pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001015 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001016 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001017
Adam Lesinski182f73f2013-12-05 16:48:06 -08001018 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 synchronized (mLock) {
1020 pw.println("Current Alarm Manager state:");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001021 final long nowRTC = System.currentTimeMillis();
1022 final long nowELAPSED = SystemClock.elapsedRealtime();
1023 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1024
1025 pw.print("nowRTC="); pw.print(nowRTC);
1026 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001027 pw.print(" nowELAPSED="); TimeUtils.formatDuration(nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001028 pw.println();
Dianne Hackbornc3527222015-05-13 14:03:20 -07001029 pw.print("mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
1030 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
1031 pw.print("mLastTimeChangeRealtime=");
1032 TimeUtils.formatDuration(mLastTimeChangeRealtime, pw);
1033 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001034 if (!mInteractive) {
1035 pw.print("Time since non-interactive: ");
1036 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1037 pw.println();
1038 pw.print("Max wakeup delay: ");
1039 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1040 pw.println();
1041 pw.print("Time since last dispatch: ");
1042 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1043 pw.println();
1044 pw.print("Next non-wakeup delivery time: ");
1045 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1046 pw.println();
1047 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001048
1049 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1050 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001051 pw.print("Next non-wakeup alarm: ");
1052 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001053 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001054 pw.print("Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001055 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackborn998e6082014-09-11 19:13:23 -07001056 pw.print("Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001057
1058 if (mAlarmBatches.size() > 0) {
1059 pw.println();
1060 pw.print("Pending alarm batches: ");
1061 pw.println(mAlarmBatches.size());
1062 for (Batch b : mAlarmBatches) {
1063 pw.print(b); pw.println(':');
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001064 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001065 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001067 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001068 pw.println();
1069 pw.println("Idle mode state:");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001070 pw.print(" Idling until: ");
1071 if (mPendingIdleUntil != null) {
1072 pw.println(mPendingIdleUntil);
1073 mPendingIdleUntil.dump(pw, " ", nowRTC, nowELAPSED, sdf);
1074 } else {
1075 pw.println("null");
1076 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001077 pw.println(" Pending alarms:");
1078 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
1079 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001080 if (mNextWakeFromIdle != null) {
1081 pw.println();
1082 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
1083 mNextWakeFromIdle.dump(pw, " ", nowRTC, nowELAPSED, sdf);
1084 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001085
1086 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001087 pw.print("Past-due non-wakeup alarms: ");
1088 if (mPendingNonWakeupAlarms.size() > 0) {
1089 pw.println(mPendingNonWakeupAlarms.size());
1090 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
1091 } else {
1092 pw.println("(none)");
1093 }
1094 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
1095 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1096 pw.println();
1097 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
1098 pw.print(", max non-interactive time: ");
1099 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1100 pw.println();
1101
1102 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001103 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001104 pw.println();
1105
1106 if (mLog.dump(pw, " Recent problems", " ")) {
1107 pw.println();
1108 }
1109
1110 final FilterStats[] topFilters = new FilterStats[10];
1111 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1112 @Override
1113 public int compare(FilterStats lhs, FilterStats rhs) {
1114 if (lhs.aggregateTime < rhs.aggregateTime) {
1115 return 1;
1116 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1117 return -1;
1118 }
1119 return 0;
1120 }
1121 };
1122 int len = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001123 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1124 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1125 for (int ip=0; ip<uidStats.size(); ip++) {
1126 BroadcastStats bs = uidStats.valueAt(ip);
1127 for (int is=0; is<bs.filterStats.size(); is++) {
1128 FilterStats fs = bs.filterStats.valueAt(is);
1129 int pos = len > 0
1130 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1131 if (pos < 0) {
1132 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001133 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001134 if (pos < topFilters.length) {
1135 int copylen = topFilters.length - pos - 1;
1136 if (copylen > 0) {
1137 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1138 }
1139 topFilters[pos] = fs;
1140 if (len < topFilters.length) {
1141 len++;
1142 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001143 }
1144 }
1145 }
1146 }
1147 if (len > 0) {
1148 pw.println(" Top Alarms:");
1149 for (int i=0; i<len; i++) {
1150 FilterStats fs = topFilters[i];
1151 pw.print(" ");
1152 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1153 TimeUtils.formatDuration(fs.aggregateTime, pw);
1154 pw.print(" running, "); pw.print(fs.numWakeup);
1155 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001156 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1157 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001158 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001159 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001160 pw.println();
1161 }
1162 }
1163
1164 pw.println(" ");
1165 pw.println(" Alarm Stats:");
1166 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001167 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1168 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1169 for (int ip=0; ip<uidStats.size(); ip++) {
1170 BroadcastStats bs = uidStats.valueAt(ip);
1171 pw.print(" ");
1172 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1173 UserHandle.formatUid(pw, bs.mUid);
1174 pw.print(":");
1175 pw.print(bs.mPackageName);
1176 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1177 pw.print(" running, "); pw.print(bs.numWakeup);
1178 pw.println(" wakeups:");
1179 tmpFilters.clear();
1180 for (int is=0; is<bs.filterStats.size(); is++) {
1181 tmpFilters.add(bs.filterStats.valueAt(is));
1182 }
1183 Collections.sort(tmpFilters, comparator);
1184 for (int i=0; i<tmpFilters.size(); i++) {
1185 FilterStats fs = tmpFilters.get(i);
1186 pw.print(" ");
1187 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1188 TimeUtils.formatDuration(fs.aggregateTime, pw);
1189 pw.print(" "); pw.print(fs.numWakeup);
1190 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001191 pw.print(" alarms, last ");
1192 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1193 pw.println(":");
1194 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001195 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001196 pw.println();
1197 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 }
1199 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001200
1201 if (WAKEUP_STATS) {
1202 pw.println();
1203 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001204 long last = -1;
1205 for (WakeupEvent event : mRecentWakeups) {
1206 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1207 pw.print('|');
1208 if (last < 0) {
1209 pw.print('0');
1210 } else {
1211 pw.print(event.when - last);
1212 }
1213 last = event.when;
1214 pw.print('|'); pw.print(event.uid);
1215 pw.print('|'); pw.print(event.action);
1216 pw.println();
1217 }
1218 pw.println();
1219 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001220 }
1221 }
1222
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001223 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001224 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
1225 PrintWriter pw = new PrintWriter(bs);
1226 final long nowRTC = System.currentTimeMillis();
1227 final long nowELAPSED = SystemClock.elapsedRealtime();
1228 final int NZ = mAlarmBatches.size();
1229 for (int iz = 0; iz < NZ; iz++) {
1230 Batch bz = mAlarmBatches.get(iz);
1231 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001232 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001233 pw.flush();
1234 Slog.v(TAG, bs.toString());
1235 bs.reset();
1236 }
1237 }
1238
1239 private boolean validateConsistencyLocked() {
1240 if (DEBUG_VALIDATE) {
1241 long lastTime = Long.MIN_VALUE;
1242 final int N = mAlarmBatches.size();
1243 for (int i = 0; i < N; i++) {
1244 Batch b = mAlarmBatches.get(i);
1245 if (b.start >= lastTime) {
1246 // duplicate start times are okay because of standalone batches
1247 lastTime = b.start;
1248 } else {
1249 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001250 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1251 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001252 return false;
1253 }
1254 }
1255 }
1256 return true;
1257 }
1258
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001259 private Batch findFirstWakeupBatchLocked() {
1260 final int N = mAlarmBatches.size();
1261 for (int i = 0; i < N; i++) {
1262 Batch b = mAlarmBatches.get(i);
1263 if (b.hasWakeups()) {
1264 return b;
1265 }
1266 }
1267 return null;
1268 }
1269
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001270 long getNextWakeFromIdleTimeImpl() {
1271 synchronized (mLock) {
1272 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
1273 }
1274 }
1275
1276 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001277 synchronized (mLock) {
1278 return mNextAlarmClockForUser.get(userId);
1279 }
1280 }
1281
1282 /**
1283 * Recomputes the next alarm clock for all users.
1284 */
1285 private void updateNextAlarmClockLocked() {
1286 if (!mNextAlarmClockMayChange) {
1287 return;
1288 }
1289 mNextAlarmClockMayChange = false;
1290
Jose Lima235510e2014-08-13 12:50:01 -07001291 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001292 nextForUser.clear();
1293
1294 final int N = mAlarmBatches.size();
1295 for (int i = 0; i < N; i++) {
1296 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
1297 final int M = alarms.size();
1298
1299 for (int j = 0; j < M; j++) {
1300 Alarm a = alarms.get(j);
1301 if (a.alarmClock != null) {
1302 final int userId = a.userId;
1303
1304 if (DEBUG_ALARM_CLOCK) {
1305 Log.v(TAG, "Found AlarmClockInfo at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001306 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02001307 " for user " + userId);
1308 }
1309
1310 // Alarms and batches are sorted by time, no need to compare times here.
1311 if (nextForUser.get(userId) == null) {
1312 nextForUser.put(userId, a.alarmClock);
1313 }
1314 }
1315 }
1316 }
1317
1318 // Update mNextAlarmForUser with new values.
1319 final int NN = nextForUser.size();
1320 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07001321 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001322 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001323 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001324 if (!newAlarm.equals(currentAlarm)) {
1325 updateNextAlarmInfoForUserLocked(userId, newAlarm);
1326 }
1327 }
1328
1329 // Remove users without any alarm clocks scheduled.
1330 final int NNN = mNextAlarmClockForUser.size();
1331 for (int i = NNN - 1; i >= 0; i--) {
1332 int userId = mNextAlarmClockForUser.keyAt(i);
1333 if (nextForUser.get(userId) == null) {
1334 updateNextAlarmInfoForUserLocked(userId, null);
1335 }
1336 }
1337 }
1338
Jose Lima235510e2014-08-13 12:50:01 -07001339 private void updateNextAlarmInfoForUserLocked(int userId,
1340 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001341 if (alarmClock != null) {
1342 if (DEBUG_ALARM_CLOCK) {
1343 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001344 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02001345 }
1346 mNextAlarmClockForUser.put(userId, alarmClock);
1347 } else {
1348 if (DEBUG_ALARM_CLOCK) {
1349 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
1350 }
1351 mNextAlarmClockForUser.remove(userId);
1352 }
1353
1354 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
1355 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1356 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1357 }
1358
1359 /**
1360 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
1361 * for which alarm clocks have changed since the last call to this.
1362 *
1363 * Do not call with a lock held. Only call from mHandler's thread.
1364 *
1365 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
1366 */
1367 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07001368 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001369 pendingUsers.clear();
1370
1371 synchronized (mLock) {
1372 final int N = mPendingSendNextAlarmClockChangedForUser.size();
1373 for (int i = 0; i < N; i++) {
1374 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
1375 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
1376 }
1377 mPendingSendNextAlarmClockChangedForUser.clear();
1378 }
1379
1380 final int N = pendingUsers.size();
1381 for (int i = 0; i < N; i++) {
1382 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001383 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001384 Settings.System.putStringForUser(getContext().getContentResolver(),
1385 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01001386 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02001387 userId);
1388
1389 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
1390 new UserHandle(userId));
1391 }
1392 }
1393
1394 /**
1395 * Formats an alarm like platform/packages/apps/DeskClock used to.
1396 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01001397 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
1398 int userId) {
1399 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02001400 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
1401 return (info == null) ? "" :
1402 DateFormat.format(pattern, info.getTriggerTime()).toString();
1403 }
1404
Adam Lesinski182f73f2013-12-05 16:48:06 -08001405 void rescheduleKernelAlarmsLocked() {
1406 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
1407 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001408 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001409 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001410 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001411 final Batch firstBatch = mAlarmBatches.get(0);
Christopher Tatec83d3e42015-02-04 13:48:29 -08001412 // always update the kernel alarms, as a backstop against missed wakeups
1413 if (firstWakeup != null) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001414 mNextWakeup = firstWakeup.start;
1415 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001416 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001417 if (firstBatch != firstWakeup) {
1418 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001419 }
1420 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001421 if (mPendingNonWakeupAlarms.size() > 0) {
1422 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
1423 nextNonWakeup = mNextNonWakeupDeliveryTime;
1424 }
1425 }
Christopher Tatec83d3e42015-02-04 13:48:29 -08001426 // always update the kernel alarm, as a backstop against missed wakeups
1427 if (nextNonWakeup != 0) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001428 mNextNonWakeup = nextNonWakeup;
1429 setLocked(ELAPSED_REALTIME, nextNonWakeup);
1430 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001431 }
1432
1433 private void removeLocked(PendingIntent operation) {
1434 boolean didRemove = false;
1435 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1436 Batch b = mAlarmBatches.get(i);
1437 didRemove |= b.remove(operation);
1438 if (b.size() == 0) {
1439 mAlarmBatches.remove(i);
1440 }
1441 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001442 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1443 if (mPendingWhileIdleAlarms.get(i).operation.equals(operation)) {
1444 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1445 mPendingWhileIdleAlarms.remove(i);
1446 }
1447 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001448
1449 if (didRemove) {
1450 if (DEBUG_BATCH) {
1451 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
1452 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001453 boolean restorePending = false;
1454 if (mPendingIdleUntil != null && mPendingIdleUntil.operation.equals(operation)) {
1455 mPendingIdleUntil = null;
1456 restorePending = true;
1457 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001458 if (mNextWakeFromIdle != null && mNextWakeFromIdle.operation.equals(operation)) {
1459 mNextWakeFromIdle = null;
1460 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001461 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001462 if (restorePending) {
1463 restorePendingWhileIdleAlarmsLocked();
1464 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001465 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001466 }
1467 }
1468
1469 void removeLocked(String packageName) {
1470 boolean didRemove = false;
1471 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1472 Batch b = mAlarmBatches.get(i);
1473 didRemove |= b.remove(packageName);
1474 if (b.size() == 0) {
1475 mAlarmBatches.remove(i);
1476 }
1477 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001478 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1479 if (mPendingWhileIdleAlarms.get(i).operation.getTargetPackage().equals(packageName)) {
1480 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1481 mPendingWhileIdleAlarms.remove(i);
1482 }
1483 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001484
1485 if (didRemove) {
1486 if (DEBUG_BATCH) {
1487 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1488 }
1489 rebatchAllAlarmsLocked(true);
1490 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001491 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001492 }
1493 }
1494
1495 void removeUserLocked(int userHandle) {
1496 boolean didRemove = false;
1497 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1498 Batch b = mAlarmBatches.get(i);
1499 didRemove |= b.remove(userHandle);
1500 if (b.size() == 0) {
1501 mAlarmBatches.remove(i);
1502 }
1503 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001504 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1505 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).operation.getCreatorUid())
1506 == userHandle) {
1507 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1508 mPendingWhileIdleAlarms.remove(i);
1509 }
1510 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001511
1512 if (didRemove) {
1513 if (DEBUG_BATCH) {
1514 Slog.v(TAG, "remove(user) changed bounds; rebatching");
1515 }
1516 rebatchAllAlarmsLocked(true);
1517 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001518 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001519 }
1520 }
1521
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001522 void interactiveStateChangedLocked(boolean interactive) {
1523 if (mInteractive != interactive) {
1524 mInteractive = interactive;
1525 final long nowELAPSED = SystemClock.elapsedRealtime();
1526 if (interactive) {
1527 if (mPendingNonWakeupAlarms.size() > 0) {
1528 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1529 mTotalDelayTime += thisDelayTime;
1530 if (mMaxDelayTime < thisDelayTime) {
1531 mMaxDelayTime = thisDelayTime;
1532 }
1533 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
1534 mPendingNonWakeupAlarms.clear();
1535 }
1536 if (mNonInteractiveStartTime > 0) {
1537 long dur = nowELAPSED - mNonInteractiveStartTime;
1538 if (dur > mNonInteractiveTime) {
1539 mNonInteractiveTime = dur;
1540 }
1541 }
1542 } else {
1543 mNonInteractiveStartTime = nowELAPSED;
1544 }
1545 }
1546 }
1547
Adam Lesinski182f73f2013-12-05 16:48:06 -08001548 boolean lookForPackageLocked(String packageName) {
1549 for (int i = 0; i < mAlarmBatches.size(); i++) {
1550 Batch b = mAlarmBatches.get(i);
1551 if (b.hasPackage(packageName)) {
1552 return true;
1553 }
1554 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001555 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
1556 if (mPendingWhileIdleAlarms.get(i).operation.getTargetPackage().equals(packageName)) {
1557 return true;
1558 }
1559 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001560 return false;
1561 }
1562
1563 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001564 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001565 // The kernel never triggers alarms with negative wakeup times
1566 // so we ensure they are positive.
1567 long alarmSeconds, alarmNanoseconds;
1568 if (when < 0) {
1569 alarmSeconds = 0;
1570 alarmNanoseconds = 0;
1571 } else {
1572 alarmSeconds = when / 1000;
1573 alarmNanoseconds = (when % 1000) * 1000 * 1000;
1574 }
1575
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001576 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001577 } else {
1578 Message msg = Message.obtain();
1579 msg.what = ALARM_EVENT;
1580
1581 mHandler.removeMessages(ALARM_EVENT);
1582 mHandler.sendMessageAtTime(msg, when);
1583 }
1584 }
1585
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001586 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001587 String prefix, String label, long nowRTC, long nowELAPSED, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 for (int i=list.size()-1; i>=0; i--) {
1589 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001590 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1591 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001592 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001593 }
1594 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001595
1596 private static final String labelForType(int type) {
1597 switch (type) {
1598 case RTC: return "RTC";
1599 case RTC_WAKEUP : return "RTC_WAKEUP";
1600 case ELAPSED_REALTIME : return "ELAPSED";
1601 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
1602 default:
1603 break;
1604 }
1605 return "--unknown--";
1606 }
1607
1608 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001609 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001610 for (int i=list.size()-1; i>=0; i--) {
1611 Alarm a = list.get(i);
1612 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001613 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1614 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001615 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001616 }
1617 }
1618
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001619 private native long init();
1620 private native void close(long nativeData);
1621 private native void set(long nativeData, int type, long seconds, long nanoseconds);
1622 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08001623 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001624 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001626 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001627 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001628 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001629 // batches are temporally sorted, so we need only pull from the
1630 // start of the list until we either empty it or hit a batch
1631 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07001632 while (mAlarmBatches.size() > 0) {
1633 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001634 if (batch.start > nowELAPSED) {
1635 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 break;
1637 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638
Christopher Tatee0a22b32013-07-11 14:43:13 -07001639 // We will (re)schedule some alarms now; don't let that interfere
1640 // with delivery of this current batch
1641 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001642
Christopher Tatee0a22b32013-07-11 14:43:13 -07001643 final int N = batch.size();
1644 for (int i = 0; i < N; i++) {
1645 Alarm alarm = batch.get(i);
1646 alarm.count = 1;
1647 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001648 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1649 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
1650 alarm.tag);
1651 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001652 if (mPendingIdleUntil == alarm) {
1653 mPendingIdleUntil = null;
1654 rebatchAllAlarmsLocked(false);
1655 restorePendingWhileIdleAlarmsLocked();
1656 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001657 if (mNextWakeFromIdle == alarm) {
1658 mNextWakeFromIdle = null;
1659 rebatchAllAlarmsLocked(false);
1660 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001661
1662 // Recurring alarms may have passed several alarm intervals while the
1663 // phone was asleep or off, so pass a trigger count when sending them.
1664 if (alarm.repeatInterval > 0) {
1665 // this adjustment will be zero if we're late by
1666 // less than one full repeat interval
1667 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
1668
1669 // Also schedule its next recurrence
1670 final long delta = alarm.count * alarm.repeatInterval;
1671 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07001672 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07001673 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001674 alarm.repeatInterval, alarm.operation, alarm.flags, true,
Adrian Roosc42a1e12014-07-07 23:35:53 +02001675 alarm.workSource, alarm.alarmClock, alarm.userId);
Christopher Tate864d42e2014-12-02 11:48:53 -08001676 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677
Christopher Tate864d42e2014-12-02 11:48:53 -08001678 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001679 hasWakeup = true;
1680 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001681
1682 // We removed an alarm clock. Let the caller recompute the next alarm clock.
1683 if (alarm.alarmClock != null) {
1684 mNextAlarmClockMayChange = true;
1685 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07001686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001688
Christopher Tate1590f1e2014-10-02 17:27:57 -07001689 // This is a new alarm delivery set; bump the sequence number to indicate that
1690 // all apps' alarm delivery classes should be recalculated.
1691 mCurrentSeq++;
1692 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001693 Collections.sort(triggerList, mAlarmDispatchComparator);
1694
1695 if (localLOGV) {
1696 for (int i=0; i<triggerList.size(); i++) {
1697 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
1698 }
1699 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001700
1701 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001702 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 /**
1705 * This Comparator sorts Alarms into increasing time order.
1706 */
1707 public static class IncreasingTimeOrder implements Comparator<Alarm> {
1708 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09001709 long when1 = a1.whenElapsed;
1710 long when2 = a2.whenElapsed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 if (when1 - when2 > 0) {
1712 return 1;
1713 }
1714 if (when1 - when2 < 0) {
1715 return -1;
1716 }
1717 return 0;
1718 }
1719 }
1720
1721 private static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001722 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001723 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001724 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001725 public final PendingIntent operation;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001726 public final String tag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001727 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001728 public final int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001729 public int count;
1730 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07001731 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001732 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001733 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 public long repeatInterval;
Jose Lima235510e2014-08-13 12:50:01 -07001735 public final AlarmManager.AlarmClockInfo alarmClock;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001736 public final int userId;
Christopher Tate1590f1e2014-10-02 17:27:57 -07001737 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001738
Christopher Tate3e04b472013-10-21 17:51:31 -07001739 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001740 long _interval, PendingIntent _op, WorkSource _ws, int _flags,
Jose Lima235510e2014-08-13 12:50:01 -07001741 AlarmManager.AlarmClockInfo _info, int _userId) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001742 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001743 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001744 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
1745 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001746 when = _when;
1747 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07001748 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001749 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001750 repeatInterval = _interval;
1751 operation = _op;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001752 tag = makeTag(_op, _type);
David Christieebe51fc2013-07-26 13:23:29 -07001753 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001754 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001755 alarmClock = _info;
1756 userId = _userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001757 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001758
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001759 public static String makeTag(PendingIntent pi, int type) {
1760 return pi.getTag(type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
1761 ? "*walarm*:" : "*alarm*:");
1762 }
1763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001765 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001766 StringBuilder sb = new StringBuilder(128);
1767 sb.append("Alarm{");
1768 sb.append(Integer.toHexString(System.identityHashCode(this)));
1769 sb.append(" type ");
1770 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001771 sb.append(" when ");
1772 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001773 sb.append(" ");
1774 sb.append(operation.getTargetPackage());
1775 sb.append('}');
1776 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 }
1778
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001779 public void dump(PrintWriter pw, String prefix, long nowRTC, long nowELAPSED,
1780 SimpleDateFormat sdf) {
1781 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
1782 pw.print(prefix); pw.print("tag="); pw.println(tag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001783 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001784 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
1785 nowELAPSED, pw);
1786 if (isRtc) {
1787 pw.print(" when="); pw.print(sdf.format(new Date(when)));
1788 } else {
1789 pw.print(" when="); TimeUtils.formatDuration(when, nowELAPSED, pw);
1790 }
1791 pw.println();
1792 pw.print(prefix); pw.print("window="); pw.print(windowLength);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001793 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001794 pw.print(" count="); pw.print(count);
1795 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001796 if (alarmClock != null) {
1797 pw.print(prefix); pw.println("Alarm clock:");
1798 pw.print(prefix); pw.print(" triggerTime=");
1799 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
1800 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
1801 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001802 pw.print(prefix); pw.print("operation="); pw.println(operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 }
1804 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001805
Christopher Tatee0a22b32013-07-11 14:43:13 -07001806 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
1807 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07001808 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
1809 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001810 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07001811 break;
1812 }
1813
Christopher Tatee0a22b32013-07-11 14:43:13 -07001814 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07001815 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
1816 Alarm a = b.alarms.get(nextAlarm);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001817 WakeupEvent e = new WakeupEvent(nowRTC,
1818 a.operation.getCreatorUid(),
1819 a.operation.getIntent().getAction());
1820 mRecentWakeups.add(e);
1821 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001822 }
1823 }
1824
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001825 long currentNonWakeupFuzzLocked(long nowELAPSED) {
1826 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
1827 if (timeSinceOn < 5*60*1000) {
1828 // If the screen has been off for 5 minutes, only delay by at most two minutes.
1829 return 2*60*1000;
1830 } else if (timeSinceOn < 30*60*1000) {
1831 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
1832 return 15*60*1000;
1833 } else {
1834 // Otherwise, we will delay by at most an hour.
1835 return 60*60*1000;
1836 }
1837 }
1838
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001839 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001840 if (duration < 15*60*1000) {
1841 // If the duration until the time is less than 15 minutes, the maximum fuzz
1842 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001843 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001844 } else if (duration < 90*60*1000) {
1845 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
1846 return 15*60*1000;
1847 } else {
1848 // Otherwise, we will fuzz by at most half an hour.
1849 return 30*60*1000;
1850 }
1851 }
1852
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001853 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
1854 if (mInteractive) {
1855 return false;
1856 }
1857 if (mLastAlarmDeliveryTime <= 0) {
1858 return false;
1859 }
minho.choo649acab2014-12-12 16:13:55 +09001860 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001861 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
1862 // and the next delivery time is in the past, then just deliver them all. This
1863 // avoids bugs where we get stuck in a loop trying to poll for alarms.
1864 return false;
1865 }
1866 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
1867 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
1868 }
1869
1870 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
1871 mLastAlarmDeliveryTime = nowELAPSED;
1872 for (int i=0; i<triggerList.size(); i++) {
1873 Alarm alarm = triggerList.get(i);
1874 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07001875 if (localLOGV) {
1876 Slog.v(TAG, "sending alarm " + alarm);
1877 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07001878 if (RECORD_ALARMS_IN_HISTORY) {
1879 if (alarm.workSource != null && alarm.workSource.size() > 0) {
1880 for (int wi=0; wi<alarm.workSource.size(); wi++) {
1881 ActivityManagerNative.noteAlarmStart(
1882 alarm.operation, alarm.workSource.get(wi), alarm.tag);
1883 }
1884 } else {
1885 ActivityManagerNative.noteAlarmStart(
1886 alarm.operation, -1, alarm.tag);
1887 }
1888 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001889 alarm.operation.send(getContext(), 0,
1890 mBackgroundIntent.putExtra(
1891 Intent.EXTRA_ALARM_COUNT, alarm.count),
1892 mResultReceiver, mHandler);
1893
1894 // we have an active broadcast so stay awake.
1895 if (mBroadcastRefCount == 0) {
1896 setWakelockWorkSource(alarm.operation, alarm.workSource,
1897 alarm.type, alarm.tag, true);
1898 mWakeLock.acquire();
1899 }
1900 final InFlight inflight = new InFlight(AlarmManagerService.this,
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001901 alarm.operation, alarm.workSource, alarm.type, alarm.tag, nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001902 mInFlight.add(inflight);
1903 mBroadcastRefCount++;
1904
1905 final BroadcastStats bs = inflight.mBroadcastStats;
1906 bs.count++;
1907 if (bs.nesting == 0) {
1908 bs.nesting = 1;
1909 bs.startTime = nowELAPSED;
1910 } else {
1911 bs.nesting++;
1912 }
1913 final FilterStats fs = inflight.mFilterStats;
1914 fs.count++;
1915 if (fs.nesting == 0) {
1916 fs.nesting = 1;
1917 fs.startTime = nowELAPSED;
1918 } else {
1919 fs.nesting++;
1920 }
1921 if (alarm.type == ELAPSED_REALTIME_WAKEUP
1922 || alarm.type == RTC_WAKEUP) {
1923 bs.numWakeup++;
1924 fs.numWakeup++;
1925 if (alarm.workSource != null && alarm.workSource.size() > 0) {
1926 for (int wi=0; wi<alarm.workSource.size(); wi++) {
1927 ActivityManagerNative.noteWakeupAlarm(
1928 alarm.operation, alarm.workSource.get(wi),
Dianne Hackborn1e383822015-04-10 14:02:33 -07001929 alarm.workSource.getName(wi), alarm.tag);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001930 }
1931 } else {
1932 ActivityManagerNative.noteWakeupAlarm(
Dianne Hackborn1e383822015-04-10 14:02:33 -07001933 alarm.operation, -1, null, alarm.tag);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001934 }
1935 }
1936 } catch (PendingIntent.CanceledException e) {
1937 if (alarm.repeatInterval > 0) {
1938 // This IntentSender is no longer valid, but this
1939 // is a repeating alarm, so toss the hoser.
1940 removeImpl(alarm.operation);
1941 }
1942 } catch (RuntimeException e) {
1943 Slog.w(TAG, "Failure sending alarm.", e);
1944 }
1945 }
1946 }
1947
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 private class AlarmThread extends Thread
1949 {
1950 public AlarmThread()
1951 {
1952 super("AlarmManager");
1953 }
1954
1955 public void run()
1956 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07001957 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
1958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959 while (true)
1960 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001961 int result = waitForAlarm(mNativeData);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001962
1963 triggerList.clear();
1964
Dianne Hackbornc3527222015-05-13 14:03:20 -07001965 final long nowRTC = System.currentTimeMillis();
1966 final long nowELAPSED = SystemClock.elapsedRealtime();
1967
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001968 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07001969 // The kernel can give us spurious time change notifications due to
1970 // small adjustments it makes internally; we want to filter those out.
1971 final long lastTimeChangeClockTime;
1972 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07001973 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07001974 lastTimeChangeClockTime = mLastTimeChangeClockTime;
1975 expectedClockTime = lastTimeChangeClockTime
1976 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07001977 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07001978 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-500)
1979 || nowRTC > (expectedClockTime+500)) {
1980 // The change is by at least +/- 500 ms (or this is the first change),
1981 // let's do it!
1982 if (DEBUG_BATCH) {
1983 Slog.v(TAG, "Time changed notification from kernel; rebatching");
1984 }
1985 removeImpl(mTimeTickSender);
1986 rebatchAllAlarms();
1987 mClockReceiver.scheduleTimeTickEvent();
1988 synchronized (mLock) {
1989 mNumTimeChanged++;
1990 mLastTimeChangeClockTime = nowRTC;
1991 mLastTimeChangeRealtime = nowELAPSED;
1992 }
1993 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
1994 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1995 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1996 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1997
1998 // The world has changed on us, so we need to re-evaluate alarms
1999 // regardless of whether the kernel has told us one went off.
2000 result |= IS_WAKEUP_MASK;
2001 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003
Dianne Hackbornc3527222015-05-13 14:03:20 -07002004 if (result != TIME_CHANGED_MASK) {
2005 // If this was anything besides just a time change, then figure what if
2006 // anything to do about alarms.
2007 synchronized (mLock) {
2008 if (localLOGV) Slog.v(
2009 TAG, "Checking for alarms... rtc=" + nowRTC
2010 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07002011
Dianne Hackbornc3527222015-05-13 14:03:20 -07002012 if (WAKEUP_STATS) {
2013 if ((result & IS_WAKEUP_MASK) != 0) {
2014 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
2015 int n = 0;
2016 for (WakeupEvent event : mRecentWakeups) {
2017 if (event.when > newEarliest) break;
2018 n++; // number of now-stale entries at the list head
2019 }
2020 for (int i = 0; i < n; i++) {
2021 mRecentWakeups.remove();
2022 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002023
Dianne Hackbornc3527222015-05-13 14:03:20 -07002024 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002025 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002026 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002027
2028 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2029 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
2030 // if there are no wakeup alarms and the screen is off, we can
2031 // delay what we have so far until the future.
2032 if (mPendingNonWakeupAlarms.size() == 0) {
2033 mStartCurrentDelayTime = nowELAPSED;
2034 mNextNonWakeupDeliveryTime = nowELAPSED
2035 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
2036 }
2037 mPendingNonWakeupAlarms.addAll(triggerList);
2038 mNumDelayedAlarms += triggerList.size();
2039 rescheduleKernelAlarmsLocked();
2040 updateNextAlarmClockLocked();
2041 } else {
2042 // now deliver the alarm intents; if there are pending non-wakeup
2043 // alarms, we need to merge them in to the list. note we don't
2044 // just deliver them first because we generally want non-wakeup
2045 // alarms delivered after wakeup alarms.
2046 rescheduleKernelAlarmsLocked();
2047 updateNextAlarmClockLocked();
2048 if (mPendingNonWakeupAlarms.size() > 0) {
2049 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
2050 triggerList.addAll(mPendingNonWakeupAlarms);
2051 Collections.sort(triggerList, mAlarmDispatchComparator);
2052 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2053 mTotalDelayTime += thisDelayTime;
2054 if (mMaxDelayTime < thisDelayTime) {
2055 mMaxDelayTime = thisDelayTime;
2056 }
2057 mPendingNonWakeupAlarms.clear();
2058 }
2059 deliverAlarmsLocked(triggerList, nowELAPSED);
2060 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002061 }
2062 }
2063 }
2064 }
2065 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002066
David Christieebe51fc2013-07-26 13:23:29 -07002067 /**
2068 * Attribute blame for a WakeLock.
2069 * @param pi PendingIntent to attribute blame to if ws is null.
2070 * @param ws WorkSource to attribute blame.
2071 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002072 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
2073 boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07002074 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002075 final boolean unimportant = pi == mTimeTickSender;
2076 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002077 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002078 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002079 } else {
2080 mWakeLock.setHistoryTag(null);
2081 }
2082 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07002083 if (ws != null) {
2084 mWakeLock.setWorkSource(ws);
2085 return;
2086 }
2087
Christopher Tatec4a07d12012-04-06 14:19:13 -07002088 final int uid = ActivityManagerNative.getDefault()
2089 .getUidForIntentSender(pi.getTarget());
2090 if (uid >= 0) {
2091 mWakeLock.setWorkSource(new WorkSource(uid));
2092 return;
2093 }
2094 } catch (Exception e) {
2095 }
2096
2097 // Something went wrong; fall back to attributing the lock to the OS
2098 mWakeLock.setWorkSource(null);
2099 }
2100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002101 private class AlarmHandler extends Handler {
2102 public static final int ALARM_EVENT = 1;
2103 public static final int MINUTE_CHANGE_EVENT = 2;
2104 public static final int DATE_CHANGE_EVENT = 3;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002105 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002106
2107 public AlarmHandler() {
2108 }
2109
2110 public void handleMessage(Message msg) {
2111 if (msg.what == ALARM_EVENT) {
2112 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2113 synchronized (mLock) {
2114 final long nowRTC = System.currentTimeMillis();
Christopher Tatee0a22b32013-07-11 14:43:13 -07002115 final long nowELAPSED = SystemClock.elapsedRealtime();
2116 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002117 updateNextAlarmClockLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002118 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002119
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120 // now trigger the alarms without the lock held
Dianne Hackborn390517b2013-05-30 15:03:32 -07002121 for (int i=0; i<triggerList.size(); i++) {
2122 Alarm alarm = triggerList.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002123 try {
2124 alarm.operation.send();
2125 } catch (PendingIntent.CanceledException e) {
2126 if (alarm.repeatInterval > 0) {
2127 // This IntentSender is no longer valid, but this
2128 // is a repeating alarm, so toss the hoser.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002129 removeImpl(alarm.operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130 }
2131 }
2132 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002133 } else if (msg.what == SEND_NEXT_ALARM_CLOCK_CHANGED) {
2134 sendNextAlarmClockChanged();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002135 }
2136 }
2137 }
2138
2139 class ClockReceiver extends BroadcastReceiver {
2140 public ClockReceiver() {
2141 IntentFilter filter = new IntentFilter();
2142 filter.addAction(Intent.ACTION_TIME_TICK);
2143 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002144 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002145 }
2146
2147 @Override
2148 public void onReceive(Context context, Intent intent) {
2149 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07002150 if (DEBUG_BATCH) {
2151 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
2152 }
2153 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002154 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
2155 // Since the kernel does not keep track of DST, we need to
2156 // reset the TZ information at the beginning of each day
2157 // based off of the current Zone gmt offset + userspace tracked
2158 // daylight savings information.
2159 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02002160 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002161 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07002162 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002163 }
2164 }
2165
2166 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07002167 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09002168 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07002169
2170 // Schedule this event for the amount of time that it would take to get to
2171 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09002172 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07002173
David Christieebe51fc2013-07-26 13:23:29 -07002174 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002175 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002176 0, mTimeTickSender, AlarmManager.FLAG_STANDALONE, workSource, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002177 }
Christopher Tate385e4982013-07-23 18:22:29 -07002178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002179 public void scheduleDateChangedEvent() {
2180 Calendar calendar = Calendar.getInstance();
2181 calendar.setTimeInMillis(System.currentTimeMillis());
2182 calendar.set(Calendar.HOUR, 0);
2183 calendar.set(Calendar.MINUTE, 0);
2184 calendar.set(Calendar.SECOND, 0);
2185 calendar.set(Calendar.MILLISECOND, 0);
2186 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07002187
2188 final WorkSource workSource = null; // Let system take blame for date change events.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002189 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender,
2190 AlarmManager.FLAG_STANDALONE, workSource, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002191 }
2192 }
2193
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002194 class InteractiveStateReceiver extends BroadcastReceiver {
2195 public InteractiveStateReceiver() {
2196 IntentFilter filter = new IntentFilter();
2197 filter.addAction(Intent.ACTION_SCREEN_OFF);
2198 filter.addAction(Intent.ACTION_SCREEN_ON);
2199 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
2200 getContext().registerReceiver(this, filter);
2201 }
2202
2203 @Override
2204 public void onReceive(Context context, Intent intent) {
2205 synchronized (mLock) {
2206 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
2207 }
2208 }
2209 }
2210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002211 class UninstallReceiver extends BroadcastReceiver {
2212 public UninstallReceiver() {
2213 IntentFilter filter = new IntentFilter();
2214 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2215 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002216 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002217 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08002218 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002219 // Register for events related to sdcard installation.
2220 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08002221 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002222 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002223 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002224 }
2225
2226 @Override
2227 public void onReceive(Context context, Intent intent) {
2228 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002229 String action = intent.getAction();
2230 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002231 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
2232 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
2233 for (String packageName : pkgList) {
2234 if (lookForPackageLocked(packageName)) {
2235 setResultCode(Activity.RESULT_OK);
2236 return;
2237 }
2238 }
2239 return;
2240 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002241 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002242 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
2243 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
2244 if (userHandle >= 0) {
2245 removeUserLocked(userHandle);
2246 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002247 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08002248 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
2249 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
2250 // This package is being updated; don't kill its alarms.
2251 return;
2252 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002253 Uri data = intent.getData();
2254 if (data != null) {
2255 String pkg = data.getSchemeSpecificPart();
2256 if (pkg != null) {
2257 pkgList = new String[]{pkg};
2258 }
2259 }
2260 }
2261 if (pkgList != null && (pkgList.length > 0)) {
2262 for (String pkg : pkgList) {
2263 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07002264 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002265 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
2266 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
2267 if (uidStats.remove(pkg) != null) {
2268 if (uidStats.size() <= 0) {
2269 mBroadcastStats.removeAt(i);
2270 }
2271 }
2272 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002273 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002274 }
2275 }
2276 }
2277 }
2278
2279 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002280 String pkg = pi.getCreatorPackage();
2281 int uid = pi.getCreatorUid();
2282 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
2283 if (uidStats == null) {
2284 uidStats = new ArrayMap<String, BroadcastStats>();
2285 mBroadcastStats.put(uid, uidStats);
2286 }
2287 BroadcastStats bs = uidStats.get(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002288 if (bs == null) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002289 bs = new BroadcastStats(uid, pkg);
2290 uidStats.put(pkg, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002291 }
2292 return bs;
2293 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002295 class ResultReceiver implements PendingIntent.OnFinished {
2296 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
2297 String resultData, Bundle resultExtras) {
2298 synchronized (mLock) {
Dianne Hackborn81038902012-11-26 17:04:09 -08002299 InFlight inflight = null;
2300 for (int i=0; i<mInFlight.size(); i++) {
2301 if (mInFlight.get(i).mPendingIntent == pi) {
2302 inflight = mInFlight.remove(i);
2303 break;
2304 }
2305 }
2306 if (inflight != null) {
2307 final long nowELAPSED = SystemClock.elapsedRealtime();
2308 BroadcastStats bs = inflight.mBroadcastStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002309 bs.nesting--;
2310 if (bs.nesting <= 0) {
2311 bs.nesting = 0;
Dianne Hackborn81038902012-11-26 17:04:09 -08002312 bs.aggregateTime += nowELAPSED - bs.startTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002313 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002314 FilterStats fs = inflight.mFilterStats;
2315 fs.nesting--;
2316 if (fs.nesting <= 0) {
2317 fs.nesting = 0;
2318 fs.aggregateTime += nowELAPSED - fs.startTime;
2319 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07002320 if (RECORD_ALARMS_IN_HISTORY) {
2321 if (inflight.mWorkSource != null && inflight.mWorkSource.size() > 0) {
2322 for (int wi=0; wi<inflight.mWorkSource.size(); wi++) {
2323 ActivityManagerNative.noteAlarmFinish(
2324 pi, inflight.mWorkSource.get(wi), inflight.mTag);
2325 }
2326 } else {
2327 ActivityManagerNative.noteAlarmFinish(
2328 pi, -1, inflight.mTag);
2329 }
2330 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002331 } else {
2332 mLog.w("No in-flight alarm for " + pi + " " + intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002333 }
2334 mBroadcastRefCount--;
2335 if (mBroadcastRefCount == 0) {
2336 mWakeLock.release();
Dianne Hackborn81038902012-11-26 17:04:09 -08002337 if (mInFlight.size() > 0) {
2338 mLog.w("Finished all broadcasts with " + mInFlight.size()
2339 + " remaining inflights");
2340 for (int i=0; i<mInFlight.size(); i++) {
2341 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
2342 }
2343 mInFlight.clear();
2344 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002345 } else {
2346 // the next of our alarms is now in flight. reattribute the wakelock.
Dianne Hackborn81038902012-11-26 17:04:09 -08002347 if (mInFlight.size() > 0) {
David Christieebe51fc2013-07-26 13:23:29 -07002348 InFlight inFlight = mInFlight.get(0);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08002349 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002350 inFlight.mAlarmType, inFlight.mTag, false);
Christopher Tatec4a07d12012-04-06 14:19:13 -07002351 } else {
2352 // should never happen
Dianne Hackborn81038902012-11-26 17:04:09 -08002353 mLog.w("Alarm wakelock still held but sent queue empty");
Christopher Tatec4a07d12012-04-06 14:19:13 -07002354 mWakeLock.setWorkSource(null);
2355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002356 }
2357 }
2358 }
2359 }
2360}