blob: 5d025764704bfd8cf7756015f23b0e983e8fd6ae [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 Hackborn998e6082014-09-11 19:13:23 -0700141 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800142
Jose Lima235510e2014-08-13 12:50:01 -0700143 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
144 new SparseArray<>();
145 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
146 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200147 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
148 new SparseBooleanArray();
149 private boolean mNextAlarmClockMayChange;
150
151 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700152 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
153 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200154
Christopher Tate1590f1e2014-10-02 17:27:57 -0700155 // Alarm delivery ordering bookkeeping
156 static final int PRIO_TICK = 0;
157 static final int PRIO_WAKEUP = 1;
158 static final int PRIO_NORMAL = 2;
159
160 class PriorityClass {
161 int seq;
162 int priority;
163
164 PriorityClass() {
165 seq = mCurrentSeq - 1;
166 priority = PRIO_NORMAL;
167 }
168 }
169
170 final HashMap<String, PriorityClass> mPriorities =
171 new HashMap<String, PriorityClass>();
172 int mCurrentSeq = 0;
173
Christopher Tate18a75f12013-07-01 18:18:59 -0700174 class WakeupEvent {
175 public long when;
176 public int uid;
177 public String action;
178
179 public WakeupEvent(long theTime, int theUid, String theAction) {
180 when = theTime;
181 uid = theUid;
182 action = theAction;
183 }
184 }
185
Adam Lesinski182f73f2013-12-05 16:48:06 -0800186 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
187 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700188
Adrian Roosc42a1e12014-07-07 23:35:53 +0200189 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700190 long start; // These endpoints are always in ELAPSED
191 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700192 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700193
194 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
195
196 Batch() {
197 start = 0;
198 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700199 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700200 }
201
202 Batch(Alarm seed) {
203 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700204 end = seed.maxWhenElapsed;
205 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700206 alarms.add(seed);
207 }
208
209 int size() {
210 return alarms.size();
211 }
212
213 Alarm get(int index) {
214 return alarms.get(index);
215 }
216
217 boolean canHold(long whenElapsed, long maxWhen) {
218 return (end >= whenElapsed) && (start <= maxWhen);
219 }
220
221 boolean add(Alarm alarm) {
222 boolean newStart = false;
223 // narrows the batch if necessary; presumes that canHold(alarm) is true
224 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
225 if (index < 0) {
226 index = 0 - index - 1;
227 }
228 alarms.add(index, alarm);
229 if (DEBUG_BATCH) {
230 Slog.v(TAG, "Adding " + alarm + " to " + this);
231 }
232 if (alarm.whenElapsed > start) {
233 start = alarm.whenElapsed;
234 newStart = true;
235 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700236 if (alarm.maxWhenElapsed < end) {
237 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700238 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700239 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700240
241 if (DEBUG_BATCH) {
242 Slog.v(TAG, " => now " + this);
243 }
244 return newStart;
245 }
246
247 boolean remove(final PendingIntent operation) {
248 boolean didRemove = false;
249 long newStart = 0; // recalculate endpoints as we go
250 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700251 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700252 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700253 Alarm alarm = alarms.get(i);
254 if (alarm.operation.equals(operation)) {
255 alarms.remove(i);
256 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200257 if (alarm.alarmClock != null) {
258 mNextAlarmClockMayChange = true;
259 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700260 } else {
261 if (alarm.whenElapsed > newStart) {
262 newStart = alarm.whenElapsed;
263 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700264 if (alarm.maxWhenElapsed < newEnd) {
265 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700266 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700267 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700268 i++;
269 }
270 }
271 if (didRemove) {
272 // commit the new batch bounds
273 start = newStart;
274 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700275 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700276 }
277 return didRemove;
278 }
279
280 boolean remove(final String packageName) {
281 boolean didRemove = false;
282 long newStart = 0; // recalculate endpoints as we go
283 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700284 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700285 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700286 Alarm alarm = alarms.get(i);
287 if (alarm.operation.getTargetPackage().equals(packageName)) {
288 alarms.remove(i);
289 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200290 if (alarm.alarmClock != null) {
291 mNextAlarmClockMayChange = true;
292 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700293 } else {
294 if (alarm.whenElapsed > newStart) {
295 newStart = alarm.whenElapsed;
296 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700297 if (alarm.maxWhenElapsed < newEnd) {
298 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700299 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700300 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700301 i++;
302 }
303 }
304 if (didRemove) {
305 // commit the new batch bounds
306 start = newStart;
307 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700308 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700309 }
310 return didRemove;
311 }
312
313 boolean remove(final int userHandle) {
314 boolean didRemove = false;
315 long newStart = 0; // recalculate endpoints as we go
316 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700317 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700318 Alarm alarm = alarms.get(i);
319 if (UserHandle.getUserId(alarm.operation.getCreatorUid()) == userHandle) {
320 alarms.remove(i);
321 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200322 if (alarm.alarmClock != null) {
323 mNextAlarmClockMayChange = true;
324 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700325 } else {
326 if (alarm.whenElapsed > newStart) {
327 newStart = alarm.whenElapsed;
328 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700329 if (alarm.maxWhenElapsed < newEnd) {
330 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700331 }
332 i++;
333 }
334 }
335 if (didRemove) {
336 // commit the new batch bounds
337 start = newStart;
338 end = newEnd;
339 }
340 return didRemove;
341 }
342
343 boolean hasPackage(final String packageName) {
344 final int N = alarms.size();
345 for (int i = 0; i < N; i++) {
346 Alarm a = alarms.get(i);
347 if (a.operation.getTargetPackage().equals(packageName)) {
348 return true;
349 }
350 }
351 return false;
352 }
353
354 boolean hasWakeups() {
355 final int N = alarms.size();
356 for (int i = 0; i < N; i++) {
357 Alarm a = alarms.get(i);
358 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
359 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
360 return true;
361 }
362 }
363 return false;
364 }
365
366 @Override
367 public String toString() {
368 StringBuilder b = new StringBuilder(40);
369 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
370 b.append(" num="); b.append(size());
371 b.append(" start="); b.append(start);
372 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700373 if (flags != 0) {
374 b.append(" flgs=0x");
375 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700376 }
377 b.append('}');
378 return b.toString();
379 }
380 }
381
382 static class BatchTimeOrder implements Comparator<Batch> {
383 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800384 long when1 = b1.start;
385 long when2 = b2.start;
386 if (when1 - when2 > 0) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700387 return 1;
388 }
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800389 if (when1 - when2 < 0) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700390 return -1;
391 }
392 return 0;
393 }
394 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800395
396 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
397 @Override
398 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700399 // priority class trumps everything. TICK < WAKEUP < NORMAL
400 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
401 return -1;
402 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
403 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800404 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700405
406 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800407 if (lhs.whenElapsed < rhs.whenElapsed) {
408 return -1;
409 } else if (lhs.whenElapsed > rhs.whenElapsed) {
410 return 1;
411 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700412
413 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800414 return 0;
415 }
416 };
417
Christopher Tate1590f1e2014-10-02 17:27:57 -0700418 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
419 final int N = alarms.size();
420 for (int i = 0; i < N; i++) {
421 Alarm a = alarms.get(i);
422
423 final int alarmPrio;
424 if (Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
425 alarmPrio = PRIO_TICK;
426 } else if (a.wakeup) {
427 alarmPrio = PRIO_WAKEUP;
428 } else {
429 alarmPrio = PRIO_NORMAL;
430 }
431
432 PriorityClass packagePrio = a.priorityClass;
433 if (packagePrio == null) packagePrio = mPriorities.get(a.operation.getCreatorPackage());
434 if (packagePrio == null) {
435 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
436 mPriorities.put(a.operation.getCreatorPackage(), packagePrio);
437 }
438 a.priorityClass = packagePrio;
439
440 if (packagePrio.seq != mCurrentSeq) {
441 // first alarm we've seen in the current delivery generation from this package
442 packagePrio.priority = alarmPrio;
443 packagePrio.seq = mCurrentSeq;
444 } else {
445 // Multiple alarms from this package being delivered in this generation;
446 // bump the package's delivery class if it's warranted.
447 // TICK < WAKEUP < NORMAL
448 if (alarmPrio < packagePrio.priority) {
449 packagePrio.priority = alarmPrio;
450 }
451 }
452 }
453 }
454
Christopher Tatee0a22b32013-07-11 14:43:13 -0700455 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800456 static final long MIN_FUZZABLE_INTERVAL = 10000;
457 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700458 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
459
460 // set to null if in idle mode; while in this mode, any alarms we don't want
461 // to run during this time are placed in mPendingWhileIdleAlarms
462 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700463 Alarm mNextWakeFromIdle = null;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700464 final ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700465
Jeff Brownb880d882014-02-10 19:47:07 -0800466 public AlarmManagerService(Context context) {
467 super(context);
468 }
469
Christopher Tatee0a22b32013-07-11 14:43:13 -0700470 static long convertToElapsed(long when, int type) {
471 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
472 if (isRtc) {
473 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
474 }
475 return when;
476 }
477
478 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
479 // calculate the end of our nominal delivery window for the alarm.
480 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
481 // Current heuristic: batchable window is 75% of either the recurrence interval
482 // [for a periodic alarm] or of the time from now to the desired delivery time,
483 // with a minimum delay/interval of 10 seconds, under which we will simply not
484 // defer the alarm.
485 long futurity = (interval == 0)
486 ? (triggerAtTime - now)
487 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700488 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700489 futurity = 0;
490 }
491 return triggerAtTime + (long)(.75 * futurity);
492 }
493
494 // returns true if the batch was added at the head
495 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
496 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
497 if (index < 0) {
498 index = 0 - index - 1;
499 }
500 list.add(index, newBatch);
501 return (index == 0);
502 }
503
Christopher Tate385e4982013-07-23 18:22:29 -0700504 // Return the index of the matching batch, or -1 if none found.
505 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700506 final int N = mAlarmBatches.size();
507 for (int i = 0; i < N; i++) {
508 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700509 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700510 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700511 }
512 }
Christopher Tate385e4982013-07-23 18:22:29 -0700513 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700514 }
515
516 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
517 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700518 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700519 rebatchAllAlarmsLocked(true);
520 }
521 }
522
523 void rebatchAllAlarmsLocked(boolean doValidate) {
524 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
525 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700526 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700527 final long nowElapsed = SystemClock.elapsedRealtime();
528 final int oldBatches = oldSet.size();
529 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
530 Batch batch = oldSet.get(batchNum);
531 final int N = batch.size();
532 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700533 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700534 }
535 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700536 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
537 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
538 + " to " + mPendingIdleUntil);
539 if (mPendingIdleUntil == null) {
540 // Somehow we lost this... we need to restore all of the pending alarms.
541 restorePendingWhileIdleAlarmsLocked();
542 }
543 }
544 rescheduleKernelAlarmsLocked();
545 updateNextAlarmClockLocked();
546 }
547
548 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
549 a.when = a.origWhen;
550 long whenElapsed = convertToElapsed(a.when, a.type);
551 final long maxElapsed;
552 if (a.whenElapsed == a.maxWhenElapsed) {
553 // Exact
554 maxElapsed = whenElapsed;
555 } else {
556 // Not exact. Preserve any explicit window, otherwise recalculate
557 // the window based on the alarm's new futurity. Note that this
558 // reflects a policy of preferring timely to deferred delivery.
559 maxElapsed = (a.windowLength > 0)
560 ? (whenElapsed + a.windowLength)
561 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
562 }
563 a.whenElapsed = whenElapsed;
564 a.maxWhenElapsed = maxElapsed;
565 setImplLocked(a, true, doValidate);
566 }
567
568 void restorePendingWhileIdleAlarmsLocked() {
569 final long nowElapsed = SystemClock.elapsedRealtime();
570 for (int i=mPendingWhileIdleAlarms.size() - 1; i >= 0 && mPendingIdleUntil != null; i --) {
571 Alarm a = mPendingWhileIdleAlarms.remove(i);
572 reAddAlarmLocked(a, nowElapsed, false);
573 }
574 rescheduleKernelAlarmsLocked();
575 updateNextAlarmClockLocked();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700576 }
577
Adam Lesinski182f73f2013-12-05 16:48:06 -0800578 static final class InFlight extends Intent {
Dianne Hackborn81038902012-11-26 17:04:09 -0800579 final PendingIntent mPendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700580 final WorkSource mWorkSource;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700581 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800582 final BroadcastStats mBroadcastStats;
583 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800584 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800585
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800586 InFlight(AlarmManagerService service, PendingIntent pendingIntent, WorkSource workSource,
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700587 int alarmType, String tag, long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800588 mPendingIntent = pendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700589 mWorkSource = workSource;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700590 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800591 mBroadcastStats = service.getStatsLocked(pendingIntent);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700592 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -0800593 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700594 fs = new FilterStats(mBroadcastStats, mTag);
595 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -0800596 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700597 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -0800598 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800599 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800600 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800601 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800602
Adam Lesinski182f73f2013-12-05 16:48:06 -0800603 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -0800604 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700605 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800606
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700607 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800609 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 int numWakeup;
611 long startTime;
612 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -0800613
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700614 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800615 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700616 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800617 }
618 }
619
Adam Lesinski182f73f2013-12-05 16:48:06 -0800620 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800621 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800622 final String mPackageName;
623
624 long aggregateTime;
625 int count;
626 int numWakeup;
627 long startTime;
628 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700629 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -0800630
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800631 BroadcastStats(int uid, String packageName) {
632 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800633 mPackageName = packageName;
634 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 }
636
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800637 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
638 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700639
640 int mNumDelayedAlarms = 0;
641 long mTotalDelayTime = 0;
642 long mMaxDelayTime = 0;
643
Adam Lesinski182f73f2013-12-05 16:48:06 -0800644 @Override
645 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800646 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800647 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800648
649 // We have to set current TimeZone info to kernel
650 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -0800651 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800652
Adam Lesinski182f73f2013-12-05 16:48:06 -0800653 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800654 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800655
Adam Lesinski182f73f2013-12-05 16:48:06 -0800656 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700658 Intent.FLAG_RECEIVER_REGISTERED_ONLY
659 | Intent.FLAG_RECEIVER_FOREGROUND), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700660 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800661 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
662 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800663 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700664 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665
666 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -0800667 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800668 mClockReceiver.scheduleTimeTickEvent();
669 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700670 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 mUninstallReceiver = new UninstallReceiver();
672
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800673 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800674 AlarmThread waitThread = new AlarmThread();
675 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800676 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800677 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800679
680 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800682
683 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 protected void finalize() throws Throwable {
685 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800686 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687 } finally {
688 super.finalize();
689 }
690 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700691
Adam Lesinski182f73f2013-12-05 16:48:06 -0800692 void setTimeZoneImpl(String tz) {
693 if (TextUtils.isEmpty(tz)) {
694 return;
David Christieebe51fc2013-07-26 13:23:29 -0700695 }
696
Adam Lesinski182f73f2013-12-05 16:48:06 -0800697 TimeZone zone = TimeZone.getTimeZone(tz);
698 // Prevent reentrant calls from stepping on each other when writing
699 // the time zone property
700 boolean timeZoneWasChanged = false;
701 synchronized (this) {
702 String current = SystemProperties.get(TIMEZONE_PROPERTY);
703 if (current == null || !current.equals(zone.getID())) {
704 if (localLOGV) {
705 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
706 }
707 timeZoneWasChanged = true;
708 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
709 }
710
711 // Update the kernel timezone information
712 // Kernel tracks time offsets as 'minutes west of GMT'
713 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800714 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -0800715 }
716
717 TimeZone.setDefault(null);
718
719 if (timeZoneWasChanged) {
720 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
721 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
722 intent.putExtra("time-zone", zone.getID());
723 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
724 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700726
Adam Lesinski182f73f2013-12-05 16:48:06 -0800727 void removeImpl(PendingIntent operation) {
728 if (operation == null) {
729 return;
730 }
731 synchronized (mLock) {
732 removeLocked(operation);
733 }
734 }
735
736 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700737 PendingIntent operation, int flags, WorkSource workSource,
Jose Lima235510e2014-08-13 12:50:01 -0700738 AlarmManager.AlarmClockInfo alarmClock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739 if (operation == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800740 Slog.w(TAG, "set/setRepeating ignored because there is no intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741 return;
742 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700743
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700744 // Sanity check the window length. This will catch people mistakenly
745 // trying to pass an end-of-window timestamp rather than a duration.
746 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
747 Slog.w(TAG, "Window length " + windowLength
748 + "ms suspiciously long; limiting to 1 hour");
749 windowLength = AlarmManager.INTERVAL_HOUR;
750 }
751
Christopher Tate498c6cb2014-11-17 16:09:27 -0800752 // Sanity check the recurrence interval. This will catch people who supply
753 // seconds when the API expects milliseconds.
754 if (interval > 0 && interval < MIN_INTERVAL) {
755 Slog.w(TAG, "Suspiciously short interval " + interval
756 + " millis; expanding to " + (int)(MIN_INTERVAL/1000)
757 + " seconds");
758 interval = MIN_INTERVAL;
759 }
760
Christopher Tatee0a22b32013-07-11 14:43:13 -0700761 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
762 throw new IllegalArgumentException("Invalid alarm type " + type);
763 }
764
Christopher Tate5f221e82013-07-30 17:13:15 -0700765 if (triggerAtTime < 0) {
766 final long who = Binder.getCallingUid();
767 final long what = Binder.getCallingPid();
768 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + who
769 + " pid=" + what);
770 triggerAtTime = 0;
771 }
772
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700773 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -0800774 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
775 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
776 final long minTrigger = nowElapsed + MIN_FUTURITY;
777 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
778
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700779 final long maxElapsed;
780 if (windowLength == AlarmManager.WINDOW_EXACT) {
781 maxElapsed = triggerElapsed;
782 } else if (windowLength < 0) {
783 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
784 } else {
785 maxElapsed = triggerElapsed + windowLength;
786 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700787
Adrian Roosc42a1e12014-07-07 23:35:53 +0200788 final int userId = UserHandle.getCallingUserId();
789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700791 if (DEBUG_BATCH) {
792 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700793 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -0700794 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700795 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 }
Christopher Tate3e04b472013-10-21 17:51:31 -0700797 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700798 interval, operation, flags, true, workSource, alarmClock, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 }
800 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801
Christopher Tate3e04b472013-10-21 17:51:31 -0700802 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700803 long maxWhen, long interval, PendingIntent operation, int flags,
Jose Lima235510e2014-08-13 12:50:01 -0700804 boolean doValidate, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
805 int userId) {
Christopher Tate3e04b472013-10-21 17:51:31 -0700806 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700807 operation, workSource, flags, alarmClock, userId);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700808 removeLocked(operation);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700809 setImplLocked(a, false, doValidate);
810 }
Christopher Tateb8849c12011-02-08 13:39:01 -0800811
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700812 private void updateNextWakeFromIdleFuzzLocked() {
813 if (mNextWakeFromIdle != null) {
814
815 }
816 }
817
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700818 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
819 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700820 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700821 // The caller has given the time they want this to happen at, however we need
822 // to pull that earlier if there are existing alarms that have requested to
823 // bring us out of idle.
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700824 if (mNextWakeFromIdle != null) {
825 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700826 }
827 // Add fuzz to make the alarm go off some time before the actual desired time.
828 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700829 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700830 if (fuzz > 0) {
831 if (mRandom == null) {
832 mRandom = new Random();
833 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700834 final int delta = mRandom.nextInt(fuzz);
835 a.whenElapsed -= delta;
836 if (false) {
837 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
838 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
839 Slog.d(TAG, "Applied fuzz: " + fuzz);
840 Slog.d(TAG, "Final delta: " + delta);
841 Slog.d(TAG, "Final when: " + a.whenElapsed);
842 }
843 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700844 }
845
846 } else if (mPendingIdleUntil != null) {
847 // We currently have an idle until alarm scheduled; if the new alarm has
848 // not explicitly stated it wants to run while idle, then put it on hold.
849 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE|AlarmManager.FLAG_WAKE_FROM_IDLE))
850 == 0) {
851 mPendingWhileIdleAlarms.add(a);
852 return;
853 }
854 }
855
856 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
857 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -0700858 if (whichBatch < 0) {
859 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -0700860 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861 } else {
Christopher Tate385e4982013-07-23 18:22:29 -0700862 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -0700863 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700864 // The start time of this batch advanced, so batch ordering may
865 // have just been broken. Move it to where it now belongs.
866 mAlarmBatches.remove(whichBatch);
867 addBatchLocked(mAlarmBatches, batch);
868 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 }
870
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700871 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +0200872 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200873 }
874
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700875 boolean needRebatch = false;
876
877 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
878 mPendingIdleUntil = a;
879 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700880 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
881 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
882 mNextWakeFromIdle = a;
883 // If this wake from idle is earlier than whatever was previously scheduled,
884 // and we are currently idling, then we need to rebatch alarms in case the idle
885 // until time needs to be updated.
886 if (mPendingIdleUntil != null) {
887 needRebatch = true;
888 }
889 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700890 }
891
892 if (!rebatching) {
893 if (DEBUG_VALIDATE) {
894 if (doValidate && !validateConsistencyLocked()) {
895 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
896 + " when(hex)=" + Long.toHexString(a.when)
897 + " whenElapsed=" + a.whenElapsed
898 + " maxWhenElapsed=" + a.maxWhenElapsed
899 + " interval=" + a.repeatInterval + " op=" + a.operation
900 + " flags=0x" + Integer.toHexString(a.flags));
901 rebatchAllAlarmsLocked(false);
902 needRebatch = false;
903 }
904 }
905
906 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700907 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -0700908 }
Christopher Tate4cb338d2013-07-26 13:11:31 -0700909
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700910 rescheduleKernelAlarmsLocked();
911 updateNextAlarmClockLocked();
912 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700913 }
914
Adam Lesinski182f73f2013-12-05 16:48:06 -0800915 private final IBinder mService = new IAlarmManager.Stub() {
916 @Override
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700917 public void set(int type, long triggerAtTime, long windowLength, long interval, int flags,
Jose Lima235510e2014-08-13 12:50:01 -0700918 PendingIntent operation, WorkSource workSource,
919 AlarmManager.AlarmClockInfo alarmClock) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800920 if (workSource != null) {
921 getContext().enforceCallingPermission(
922 android.Manifest.permission.UPDATE_DEVICE_STATS,
923 "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -0700924 }
925
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700926 if (windowLength == AlarmManager.WINDOW_EXACT) {
927 flags |= AlarmManager.FLAG_STANDALONE;
928 }
929 if (alarmClock != null) {
930 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
931 }
932 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
933 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE;
934 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800935 setImpl(type, triggerAtTime, windowLength, interval, operation,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700936 flags, workSource, alarmClock);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800937 }
Christopher Tate89779822012-08-31 14:40:03 -0700938
Adam Lesinski182f73f2013-12-05 16:48:06 -0800939 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -0800940 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800941 getContext().enforceCallingOrSelfPermission(
942 "android.permission.SET_TIME",
943 "setTime");
944
Greg Hackmann0cab8962014-02-21 16:35:52 -0800945 if (mNativeData == 0) {
946 Slog.w(TAG, "Not setting time since no alarm driver is available.");
947 return false;
Christopher Tate89779822012-08-31 14:40:03 -0700948 }
Greg Hackmann0cab8962014-02-21 16:35:52 -0800949
950 synchronized (mLock) {
951 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800953 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800954
955 @Override
956 public void setTimeZone(String tz) {
957 getContext().enforceCallingOrSelfPermission(
958 "android.permission.SET_TIME_ZONE",
959 "setTimeZone");
960
961 final long oldId = Binder.clearCallingIdentity();
962 try {
963 setTimeZoneImpl(tz);
964 } finally {
965 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 }
967 }
Christopher Tate4cb338d2013-07-26 13:11:31 -0700968
Adam Lesinski182f73f2013-12-05 16:48:06 -0800969 @Override
970 public void remove(PendingIntent operation) {
971 removeImpl(operation);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700972
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 }
Christopher Tate4cb338d2013-07-26 13:11:31 -0700974
Adam Lesinski182f73f2013-12-05 16:48:06 -0800975 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700976 public long getNextWakeFromIdleTime() {
977 return getNextWakeFromIdleTimeImpl();
978 }
979
980 @Override
Jose Lima235510e2014-08-13 12:50:01 -0700981 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +0200982 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
983 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
984 "getNextAlarmClock", null);
985
986 return getNextAlarmClockImpl(userId);
987 }
988
989 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -0800990 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
991 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
992 != PackageManager.PERMISSION_GRANTED) {
993 pw.println("Permission Denial: can't dump AlarmManager from from pid="
994 + Binder.getCallingPid()
995 + ", uid=" + Binder.getCallingUid());
996 return;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700997 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700998
Adam Lesinski182f73f2013-12-05 16:48:06 -0800999 dumpImpl(pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001000 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001001 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001002
Adam Lesinski182f73f2013-12-05 16:48:06 -08001003 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004 synchronized (mLock) {
1005 pw.println("Current Alarm Manager state:");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001006 final long nowRTC = System.currentTimeMillis();
1007 final long nowELAPSED = SystemClock.elapsedRealtime();
1008 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1009
1010 pw.print("nowRTC="); pw.print(nowRTC);
1011 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001012 pw.print(" nowELAPSED="); TimeUtils.formatDuration(nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001013 pw.println();
1014 if (!mInteractive) {
1015 pw.print("Time since non-interactive: ");
1016 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1017 pw.println();
1018 pw.print("Max wakeup delay: ");
1019 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1020 pw.println();
1021 pw.print("Time since last dispatch: ");
1022 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1023 pw.println();
1024 pw.print("Next non-wakeup delivery time: ");
1025 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1026 pw.println();
1027 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001028
1029 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1030 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001031 pw.print("Next non-wakeup alarm: ");
1032 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001033 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001034 pw.print("Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001035 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackborn998e6082014-09-11 19:13:23 -07001036 pw.print("Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001037
1038 if (mAlarmBatches.size() > 0) {
1039 pw.println();
1040 pw.print("Pending alarm batches: ");
1041 pw.println(mAlarmBatches.size());
1042 for (Batch b : mAlarmBatches) {
1043 pw.print(b); pw.println(':');
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001044 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001045 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001047 if (mPendingIdleUntil != null) {
1048 pw.println();
1049 pw.println("Idle mode state:");
1050 pw.print(" Idling until: "); pw.println(mPendingIdleUntil);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001051 mPendingIdleUntil.dump(pw, " ", nowRTC, nowELAPSED, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001052 pw.println(" Pending alarms:");
1053 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
1054 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001055 if (mNextWakeFromIdle != null) {
1056 pw.println();
1057 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
1058 mNextWakeFromIdle.dump(pw, " ", nowRTC, nowELAPSED, sdf);
1059 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001060
1061 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001062 pw.print("Past-due non-wakeup alarms: ");
1063 if (mPendingNonWakeupAlarms.size() > 0) {
1064 pw.println(mPendingNonWakeupAlarms.size());
1065 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
1066 } else {
1067 pw.println("(none)");
1068 }
1069 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
1070 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1071 pw.println();
1072 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
1073 pw.print(", max non-interactive time: ");
1074 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1075 pw.println();
1076
1077 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001078 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001079 pw.println();
1080
1081 if (mLog.dump(pw, " Recent problems", " ")) {
1082 pw.println();
1083 }
1084
1085 final FilterStats[] topFilters = new FilterStats[10];
1086 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1087 @Override
1088 public int compare(FilterStats lhs, FilterStats rhs) {
1089 if (lhs.aggregateTime < rhs.aggregateTime) {
1090 return 1;
1091 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1092 return -1;
1093 }
1094 return 0;
1095 }
1096 };
1097 int len = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001098 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1099 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1100 for (int ip=0; ip<uidStats.size(); ip++) {
1101 BroadcastStats bs = uidStats.valueAt(ip);
1102 for (int is=0; is<bs.filterStats.size(); is++) {
1103 FilterStats fs = bs.filterStats.valueAt(is);
1104 int pos = len > 0
1105 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1106 if (pos < 0) {
1107 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001108 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001109 if (pos < topFilters.length) {
1110 int copylen = topFilters.length - pos - 1;
1111 if (copylen > 0) {
1112 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1113 }
1114 topFilters[pos] = fs;
1115 if (len < topFilters.length) {
1116 len++;
1117 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001118 }
1119 }
1120 }
1121 }
1122 if (len > 0) {
1123 pw.println(" Top Alarms:");
1124 for (int i=0; i<len; i++) {
1125 FilterStats fs = topFilters[i];
1126 pw.print(" ");
1127 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1128 TimeUtils.formatDuration(fs.aggregateTime, pw);
1129 pw.print(" running, "); pw.print(fs.numWakeup);
1130 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001131 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1132 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001133 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001134 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001135 pw.println();
1136 }
1137 }
1138
1139 pw.println(" ");
1140 pw.println(" Alarm Stats:");
1141 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001142 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1143 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1144 for (int ip=0; ip<uidStats.size(); ip++) {
1145 BroadcastStats bs = uidStats.valueAt(ip);
1146 pw.print(" ");
1147 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1148 UserHandle.formatUid(pw, bs.mUid);
1149 pw.print(":");
1150 pw.print(bs.mPackageName);
1151 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1152 pw.print(" running, "); pw.print(bs.numWakeup);
1153 pw.println(" wakeups:");
1154 tmpFilters.clear();
1155 for (int is=0; is<bs.filterStats.size(); is++) {
1156 tmpFilters.add(bs.filterStats.valueAt(is));
1157 }
1158 Collections.sort(tmpFilters, comparator);
1159 for (int i=0; i<tmpFilters.size(); i++) {
1160 FilterStats fs = tmpFilters.get(i);
1161 pw.print(" ");
1162 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1163 TimeUtils.formatDuration(fs.aggregateTime, pw);
1164 pw.print(" "); pw.print(fs.numWakeup);
1165 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001166 pw.print(" alarms, last ");
1167 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1168 pw.println(":");
1169 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001170 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001171 pw.println();
1172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001173 }
1174 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001175
1176 if (WAKEUP_STATS) {
1177 pw.println();
1178 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001179 long last = -1;
1180 for (WakeupEvent event : mRecentWakeups) {
1181 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1182 pw.print('|');
1183 if (last < 0) {
1184 pw.print('0');
1185 } else {
1186 pw.print(event.when - last);
1187 }
1188 last = event.when;
1189 pw.print('|'); pw.print(event.uid);
1190 pw.print('|'); pw.print(event.action);
1191 pw.println();
1192 }
1193 pw.println();
1194 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 }
1196 }
1197
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001198 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001199 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
1200 PrintWriter pw = new PrintWriter(bs);
1201 final long nowRTC = System.currentTimeMillis();
1202 final long nowELAPSED = SystemClock.elapsedRealtime();
1203 final int NZ = mAlarmBatches.size();
1204 for (int iz = 0; iz < NZ; iz++) {
1205 Batch bz = mAlarmBatches.get(iz);
1206 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001207 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001208 pw.flush();
1209 Slog.v(TAG, bs.toString());
1210 bs.reset();
1211 }
1212 }
1213
1214 private boolean validateConsistencyLocked() {
1215 if (DEBUG_VALIDATE) {
1216 long lastTime = Long.MIN_VALUE;
1217 final int N = mAlarmBatches.size();
1218 for (int i = 0; i < N; i++) {
1219 Batch b = mAlarmBatches.get(i);
1220 if (b.start >= lastTime) {
1221 // duplicate start times are okay because of standalone batches
1222 lastTime = b.start;
1223 } else {
1224 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001225 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1226 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001227 return false;
1228 }
1229 }
1230 }
1231 return true;
1232 }
1233
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001234 private Batch findFirstWakeupBatchLocked() {
1235 final int N = mAlarmBatches.size();
1236 for (int i = 0; i < N; i++) {
1237 Batch b = mAlarmBatches.get(i);
1238 if (b.hasWakeups()) {
1239 return b;
1240 }
1241 }
1242 return null;
1243 }
1244
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001245 long getNextWakeFromIdleTimeImpl() {
1246 synchronized (mLock) {
1247 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
1248 }
1249 }
1250
1251 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001252 synchronized (mLock) {
1253 return mNextAlarmClockForUser.get(userId);
1254 }
1255 }
1256
1257 /**
1258 * Recomputes the next alarm clock for all users.
1259 */
1260 private void updateNextAlarmClockLocked() {
1261 if (!mNextAlarmClockMayChange) {
1262 return;
1263 }
1264 mNextAlarmClockMayChange = false;
1265
Jose Lima235510e2014-08-13 12:50:01 -07001266 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001267 nextForUser.clear();
1268
1269 final int N = mAlarmBatches.size();
1270 for (int i = 0; i < N; i++) {
1271 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
1272 final int M = alarms.size();
1273
1274 for (int j = 0; j < M; j++) {
1275 Alarm a = alarms.get(j);
1276 if (a.alarmClock != null) {
1277 final int userId = a.userId;
1278
1279 if (DEBUG_ALARM_CLOCK) {
1280 Log.v(TAG, "Found AlarmClockInfo at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001281 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02001282 " for user " + userId);
1283 }
1284
1285 // Alarms and batches are sorted by time, no need to compare times here.
1286 if (nextForUser.get(userId) == null) {
1287 nextForUser.put(userId, a.alarmClock);
1288 }
1289 }
1290 }
1291 }
1292
1293 // Update mNextAlarmForUser with new values.
1294 final int NN = nextForUser.size();
1295 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07001296 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001297 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001298 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001299 if (!newAlarm.equals(currentAlarm)) {
1300 updateNextAlarmInfoForUserLocked(userId, newAlarm);
1301 }
1302 }
1303
1304 // Remove users without any alarm clocks scheduled.
1305 final int NNN = mNextAlarmClockForUser.size();
1306 for (int i = NNN - 1; i >= 0; i--) {
1307 int userId = mNextAlarmClockForUser.keyAt(i);
1308 if (nextForUser.get(userId) == null) {
1309 updateNextAlarmInfoForUserLocked(userId, null);
1310 }
1311 }
1312 }
1313
Jose Lima235510e2014-08-13 12:50:01 -07001314 private void updateNextAlarmInfoForUserLocked(int userId,
1315 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001316 if (alarmClock != null) {
1317 if (DEBUG_ALARM_CLOCK) {
1318 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001319 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02001320 }
1321 mNextAlarmClockForUser.put(userId, alarmClock);
1322 } else {
1323 if (DEBUG_ALARM_CLOCK) {
1324 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
1325 }
1326 mNextAlarmClockForUser.remove(userId);
1327 }
1328
1329 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
1330 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1331 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1332 }
1333
1334 /**
1335 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
1336 * for which alarm clocks have changed since the last call to this.
1337 *
1338 * Do not call with a lock held. Only call from mHandler's thread.
1339 *
1340 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
1341 */
1342 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07001343 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001344 pendingUsers.clear();
1345
1346 synchronized (mLock) {
1347 final int N = mPendingSendNextAlarmClockChangedForUser.size();
1348 for (int i = 0; i < N; i++) {
1349 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
1350 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
1351 }
1352 mPendingSendNextAlarmClockChangedForUser.clear();
1353 }
1354
1355 final int N = pendingUsers.size();
1356 for (int i = 0; i < N; i++) {
1357 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001358 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001359 Settings.System.putStringForUser(getContext().getContentResolver(),
1360 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01001361 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02001362 userId);
1363
1364 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
1365 new UserHandle(userId));
1366 }
1367 }
1368
1369 /**
1370 * Formats an alarm like platform/packages/apps/DeskClock used to.
1371 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01001372 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
1373 int userId) {
1374 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02001375 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
1376 return (info == null) ? "" :
1377 DateFormat.format(pattern, info.getTriggerTime()).toString();
1378 }
1379
Adam Lesinski182f73f2013-12-05 16:48:06 -08001380 void rescheduleKernelAlarmsLocked() {
1381 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
1382 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001383 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001384 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001385 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001386 final Batch firstBatch = mAlarmBatches.get(0);
Christopher Tatec83d3e42015-02-04 13:48:29 -08001387 // always update the kernel alarms, as a backstop against missed wakeups
1388 if (firstWakeup != null) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001389 mNextWakeup = firstWakeup.start;
1390 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001391 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001392 if (firstBatch != firstWakeup) {
1393 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001394 }
1395 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001396 if (mPendingNonWakeupAlarms.size() > 0) {
1397 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
1398 nextNonWakeup = mNextNonWakeupDeliveryTime;
1399 }
1400 }
Christopher Tatec83d3e42015-02-04 13:48:29 -08001401 // always update the kernel alarm, as a backstop against missed wakeups
1402 if (nextNonWakeup != 0) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001403 mNextNonWakeup = nextNonWakeup;
1404 setLocked(ELAPSED_REALTIME, nextNonWakeup);
1405 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001406 }
1407
1408 private void removeLocked(PendingIntent operation) {
1409 boolean didRemove = false;
1410 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1411 Batch b = mAlarmBatches.get(i);
1412 didRemove |= b.remove(operation);
1413 if (b.size() == 0) {
1414 mAlarmBatches.remove(i);
1415 }
1416 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001417 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1418 if (mPendingWhileIdleAlarms.get(i).operation.equals(operation)) {
1419 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1420 mPendingWhileIdleAlarms.remove(i);
1421 }
1422 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001423
1424 if (didRemove) {
1425 if (DEBUG_BATCH) {
1426 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
1427 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001428 boolean restorePending = false;
1429 if (mPendingIdleUntil != null && mPendingIdleUntil.operation.equals(operation)) {
1430 mPendingIdleUntil = null;
1431 restorePending = true;
1432 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001433 if (mNextWakeFromIdle != null && mNextWakeFromIdle.operation.equals(operation)) {
1434 mNextWakeFromIdle = null;
1435 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001436 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001437 if (restorePending) {
1438 restorePendingWhileIdleAlarmsLocked();
1439 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001440 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001441 }
1442 }
1443
1444 void removeLocked(String packageName) {
1445 boolean didRemove = false;
1446 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1447 Batch b = mAlarmBatches.get(i);
1448 didRemove |= b.remove(packageName);
1449 if (b.size() == 0) {
1450 mAlarmBatches.remove(i);
1451 }
1452 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001453 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1454 if (mPendingWhileIdleAlarms.get(i).operation.getTargetPackage().equals(packageName)) {
1455 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1456 mPendingWhileIdleAlarms.remove(i);
1457 }
1458 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001459
1460 if (didRemove) {
1461 if (DEBUG_BATCH) {
1462 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1463 }
1464 rebatchAllAlarmsLocked(true);
1465 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001466 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001467 }
1468 }
1469
1470 void removeUserLocked(int userHandle) {
1471 boolean didRemove = false;
1472 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1473 Batch b = mAlarmBatches.get(i);
1474 didRemove |= b.remove(userHandle);
1475 if (b.size() == 0) {
1476 mAlarmBatches.remove(i);
1477 }
1478 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001479 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1480 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).operation.getCreatorUid())
1481 == userHandle) {
1482 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1483 mPendingWhileIdleAlarms.remove(i);
1484 }
1485 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001486
1487 if (didRemove) {
1488 if (DEBUG_BATCH) {
1489 Slog.v(TAG, "remove(user) changed bounds; rebatching");
1490 }
1491 rebatchAllAlarmsLocked(true);
1492 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001493 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001494 }
1495 }
1496
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001497 void interactiveStateChangedLocked(boolean interactive) {
1498 if (mInteractive != interactive) {
1499 mInteractive = interactive;
1500 final long nowELAPSED = SystemClock.elapsedRealtime();
1501 if (interactive) {
1502 if (mPendingNonWakeupAlarms.size() > 0) {
1503 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1504 mTotalDelayTime += thisDelayTime;
1505 if (mMaxDelayTime < thisDelayTime) {
1506 mMaxDelayTime = thisDelayTime;
1507 }
1508 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
1509 mPendingNonWakeupAlarms.clear();
1510 }
1511 if (mNonInteractiveStartTime > 0) {
1512 long dur = nowELAPSED - mNonInteractiveStartTime;
1513 if (dur > mNonInteractiveTime) {
1514 mNonInteractiveTime = dur;
1515 }
1516 }
1517 } else {
1518 mNonInteractiveStartTime = nowELAPSED;
1519 }
1520 }
1521 }
1522
Adam Lesinski182f73f2013-12-05 16:48:06 -08001523 boolean lookForPackageLocked(String packageName) {
1524 for (int i = 0; i < mAlarmBatches.size(); i++) {
1525 Batch b = mAlarmBatches.get(i);
1526 if (b.hasPackage(packageName)) {
1527 return true;
1528 }
1529 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001530 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
1531 if (mPendingWhileIdleAlarms.get(i).operation.getTargetPackage().equals(packageName)) {
1532 return true;
1533 }
1534 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001535 return false;
1536 }
1537
1538 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001539 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001540 // The kernel never triggers alarms with negative wakeup times
1541 // so we ensure they are positive.
1542 long alarmSeconds, alarmNanoseconds;
1543 if (when < 0) {
1544 alarmSeconds = 0;
1545 alarmNanoseconds = 0;
1546 } else {
1547 alarmSeconds = when / 1000;
1548 alarmNanoseconds = (when % 1000) * 1000 * 1000;
1549 }
1550
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001551 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001552 } else {
1553 Message msg = Message.obtain();
1554 msg.what = ALARM_EVENT;
1555
1556 mHandler.removeMessages(ALARM_EVENT);
1557 mHandler.sendMessageAtTime(msg, when);
1558 }
1559 }
1560
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001561 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001562 String prefix, String label, long nowRTC, long nowELAPSED, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 for (int i=list.size()-1; i>=0; i--) {
1564 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001565 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1566 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001567 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 }
1569 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001570
1571 private static final String labelForType(int type) {
1572 switch (type) {
1573 case RTC: return "RTC";
1574 case RTC_WAKEUP : return "RTC_WAKEUP";
1575 case ELAPSED_REALTIME : return "ELAPSED";
1576 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
1577 default:
1578 break;
1579 }
1580 return "--unknown--";
1581 }
1582
1583 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001584 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001585 for (int i=list.size()-1; i>=0; i--) {
1586 Alarm a = list.get(i);
1587 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001588 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1589 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001590 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001591 }
1592 }
1593
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001594 private native long init();
1595 private native void close(long nativeData);
1596 private native void set(long nativeData, int type, long seconds, long nanoseconds);
1597 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08001598 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001599 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001601 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001602 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001603 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001604 // batches are temporally sorted, so we need only pull from the
1605 // start of the list until we either empty it or hit a batch
1606 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07001607 while (mAlarmBatches.size() > 0) {
1608 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001609 if (batch.start > nowELAPSED) {
1610 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 break;
1612 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613
Christopher Tatee0a22b32013-07-11 14:43:13 -07001614 // We will (re)schedule some alarms now; don't let that interfere
1615 // with delivery of this current batch
1616 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001617
Christopher Tatee0a22b32013-07-11 14:43:13 -07001618 final int N = batch.size();
1619 for (int i = 0; i < N; i++) {
1620 Alarm alarm = batch.get(i);
1621 alarm.count = 1;
1622 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001623 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1624 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
1625 alarm.tag);
1626 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001627 if (mPendingIdleUntil == alarm) {
1628 mPendingIdleUntil = null;
1629 rebatchAllAlarmsLocked(false);
1630 restorePendingWhileIdleAlarmsLocked();
1631 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001632 if (mNextWakeFromIdle == alarm) {
1633 mNextWakeFromIdle = null;
1634 rebatchAllAlarmsLocked(false);
1635 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001636
1637 // Recurring alarms may have passed several alarm intervals while the
1638 // phone was asleep or off, so pass a trigger count when sending them.
1639 if (alarm.repeatInterval > 0) {
1640 // this adjustment will be zero if we're late by
1641 // less than one full repeat interval
1642 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
1643
1644 // Also schedule its next recurrence
1645 final long delta = alarm.count * alarm.repeatInterval;
1646 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07001647 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07001648 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001649 alarm.repeatInterval, alarm.operation, alarm.flags, true,
Adrian Roosc42a1e12014-07-07 23:35:53 +02001650 alarm.workSource, alarm.alarmClock, alarm.userId);
Christopher Tate864d42e2014-12-02 11:48:53 -08001651 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652
Christopher Tate864d42e2014-12-02 11:48:53 -08001653 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001654 hasWakeup = true;
1655 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001656
1657 // We removed an alarm clock. Let the caller recompute the next alarm clock.
1658 if (alarm.alarmClock != null) {
1659 mNextAlarmClockMayChange = true;
1660 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07001661 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001663
Christopher Tate1590f1e2014-10-02 17:27:57 -07001664 // This is a new alarm delivery set; bump the sequence number to indicate that
1665 // all apps' alarm delivery classes should be recalculated.
1666 mCurrentSeq++;
1667 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001668 Collections.sort(triggerList, mAlarmDispatchComparator);
1669
1670 if (localLOGV) {
1671 for (int i=0; i<triggerList.size(); i++) {
1672 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
1673 }
1674 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001675
1676 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 /**
1680 * This Comparator sorts Alarms into increasing time order.
1681 */
1682 public static class IncreasingTimeOrder implements Comparator<Alarm> {
1683 public int compare(Alarm a1, Alarm a2) {
1684 long when1 = a1.when;
1685 long when2 = a2.when;
1686 if (when1 - when2 > 0) {
1687 return 1;
1688 }
1689 if (when1 - when2 < 0) {
1690 return -1;
1691 }
1692 return 0;
1693 }
1694 }
1695
1696 private static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001697 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001698 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001699 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001700 public final PendingIntent operation;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001701 public final String tag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001702 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001703 public final int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 public int count;
1705 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07001706 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001707 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001708 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 public long repeatInterval;
Jose Lima235510e2014-08-13 12:50:01 -07001710 public final AlarmManager.AlarmClockInfo alarmClock;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001711 public final int userId;
Christopher Tate1590f1e2014-10-02 17:27:57 -07001712 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001713
Christopher Tate3e04b472013-10-21 17:51:31 -07001714 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001715 long _interval, PendingIntent _op, WorkSource _ws, int _flags,
Jose Lima235510e2014-08-13 12:50:01 -07001716 AlarmManager.AlarmClockInfo _info, int _userId) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001717 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001718 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001719 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
1720 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001721 when = _when;
1722 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07001723 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001724 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001725 repeatInterval = _interval;
1726 operation = _op;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001727 tag = makeTag(_op, _type);
David Christieebe51fc2013-07-26 13:23:29 -07001728 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001729 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001730 alarmClock = _info;
1731 userId = _userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001733
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001734 public static String makeTag(PendingIntent pi, int type) {
1735 return pi.getTag(type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
1736 ? "*walarm*:" : "*alarm*:");
1737 }
1738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001740 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001741 StringBuilder sb = new StringBuilder(128);
1742 sb.append("Alarm{");
1743 sb.append(Integer.toHexString(System.identityHashCode(this)));
1744 sb.append(" type ");
1745 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001746 sb.append(" when ");
1747 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001748 sb.append(" ");
1749 sb.append(operation.getTargetPackage());
1750 sb.append('}');
1751 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 }
1753
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001754 public void dump(PrintWriter pw, String prefix, long nowRTC, long nowELAPSED,
1755 SimpleDateFormat sdf) {
1756 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
1757 pw.print(prefix); pw.print("tag="); pw.println(tag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001758 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001759 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
1760 nowELAPSED, pw);
1761 if (isRtc) {
1762 pw.print(" when="); pw.print(sdf.format(new Date(when)));
1763 } else {
1764 pw.print(" when="); TimeUtils.formatDuration(when, nowELAPSED, pw);
1765 }
1766 pw.println();
1767 pw.print(prefix); pw.print("window="); pw.print(windowLength);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001768 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001769 pw.print(" count="); pw.print(count);
1770 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001771 if (alarmClock != null) {
1772 pw.print(prefix); pw.println("Alarm clock:");
1773 pw.print(prefix); pw.print(" triggerTime=");
1774 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
1775 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
1776 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001777 pw.print(prefix); pw.print("operation="); pw.println(operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001778 }
1779 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001780
Christopher Tatee0a22b32013-07-11 14:43:13 -07001781 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
1782 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07001783 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
1784 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001785 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07001786 break;
1787 }
1788
Christopher Tatee0a22b32013-07-11 14:43:13 -07001789 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07001790 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
1791 Alarm a = b.alarms.get(nextAlarm);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001792 WakeupEvent e = new WakeupEvent(nowRTC,
1793 a.operation.getCreatorUid(),
1794 a.operation.getIntent().getAction());
1795 mRecentWakeups.add(e);
1796 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001797 }
1798 }
1799
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001800 long currentNonWakeupFuzzLocked(long nowELAPSED) {
1801 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
1802 if (timeSinceOn < 5*60*1000) {
1803 // If the screen has been off for 5 minutes, only delay by at most two minutes.
1804 return 2*60*1000;
1805 } else if (timeSinceOn < 30*60*1000) {
1806 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
1807 return 15*60*1000;
1808 } else {
1809 // Otherwise, we will delay by at most an hour.
1810 return 60*60*1000;
1811 }
1812 }
1813
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001814 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001815 if (duration < 15*60*1000) {
1816 // If the duration until the time is less than 15 minutes, the maximum fuzz
1817 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001818 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001819 } else if (duration < 90*60*1000) {
1820 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
1821 return 15*60*1000;
1822 } else {
1823 // Otherwise, we will fuzz by at most half an hour.
1824 return 30*60*1000;
1825 }
1826 }
1827
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001828 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
1829 if (mInteractive) {
1830 return false;
1831 }
1832 if (mLastAlarmDeliveryTime <= 0) {
1833 return false;
1834 }
minho.choo649acab2014-12-12 16:13:55 +09001835 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001836 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
1837 // and the next delivery time is in the past, then just deliver them all. This
1838 // avoids bugs where we get stuck in a loop trying to poll for alarms.
1839 return false;
1840 }
1841 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
1842 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
1843 }
1844
1845 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
1846 mLastAlarmDeliveryTime = nowELAPSED;
1847 for (int i=0; i<triggerList.size(); i++) {
1848 Alarm alarm = triggerList.get(i);
1849 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07001850 if (localLOGV) {
1851 Slog.v(TAG, "sending alarm " + alarm);
1852 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07001853 if (RECORD_ALARMS_IN_HISTORY) {
1854 if (alarm.workSource != null && alarm.workSource.size() > 0) {
1855 for (int wi=0; wi<alarm.workSource.size(); wi++) {
1856 ActivityManagerNative.noteAlarmStart(
1857 alarm.operation, alarm.workSource.get(wi), alarm.tag);
1858 }
1859 } else {
1860 ActivityManagerNative.noteAlarmStart(
1861 alarm.operation, -1, alarm.tag);
1862 }
1863 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001864 alarm.operation.send(getContext(), 0,
1865 mBackgroundIntent.putExtra(
1866 Intent.EXTRA_ALARM_COUNT, alarm.count),
1867 mResultReceiver, mHandler);
1868
1869 // we have an active broadcast so stay awake.
1870 if (mBroadcastRefCount == 0) {
1871 setWakelockWorkSource(alarm.operation, alarm.workSource,
1872 alarm.type, alarm.tag, true);
1873 mWakeLock.acquire();
1874 }
1875 final InFlight inflight = new InFlight(AlarmManagerService.this,
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001876 alarm.operation, alarm.workSource, alarm.type, alarm.tag, nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001877 mInFlight.add(inflight);
1878 mBroadcastRefCount++;
1879
1880 final BroadcastStats bs = inflight.mBroadcastStats;
1881 bs.count++;
1882 if (bs.nesting == 0) {
1883 bs.nesting = 1;
1884 bs.startTime = nowELAPSED;
1885 } else {
1886 bs.nesting++;
1887 }
1888 final FilterStats fs = inflight.mFilterStats;
1889 fs.count++;
1890 if (fs.nesting == 0) {
1891 fs.nesting = 1;
1892 fs.startTime = nowELAPSED;
1893 } else {
1894 fs.nesting++;
1895 }
1896 if (alarm.type == ELAPSED_REALTIME_WAKEUP
1897 || alarm.type == RTC_WAKEUP) {
1898 bs.numWakeup++;
1899 fs.numWakeup++;
1900 if (alarm.workSource != null && alarm.workSource.size() > 0) {
1901 for (int wi=0; wi<alarm.workSource.size(); wi++) {
1902 ActivityManagerNative.noteWakeupAlarm(
1903 alarm.operation, alarm.workSource.get(wi),
Dianne Hackborn1e383822015-04-10 14:02:33 -07001904 alarm.workSource.getName(wi), alarm.tag);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001905 }
1906 } else {
1907 ActivityManagerNative.noteWakeupAlarm(
Dianne Hackborn1e383822015-04-10 14:02:33 -07001908 alarm.operation, -1, null, alarm.tag);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001909 }
1910 }
1911 } catch (PendingIntent.CanceledException e) {
1912 if (alarm.repeatInterval > 0) {
1913 // This IntentSender is no longer valid, but this
1914 // is a repeating alarm, so toss the hoser.
1915 removeImpl(alarm.operation);
1916 }
1917 } catch (RuntimeException e) {
1918 Slog.w(TAG, "Failure sending alarm.", e);
1919 }
1920 }
1921 }
1922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 private class AlarmThread extends Thread
1924 {
1925 public AlarmThread()
1926 {
1927 super("AlarmManager");
1928 }
1929
1930 public void run()
1931 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07001932 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
1933
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 while (true)
1935 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001936 int result = waitForAlarm(mNativeData);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001937
1938 triggerList.clear();
1939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940 if ((result & TIME_CHANGED_MASK) != 0) {
Christopher Tate385e4982013-07-23 18:22:29 -07001941 if (DEBUG_BATCH) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001942 Slog.v(TAG, "Time changed notification from kernel; rebatching");
Christopher Tate385e4982013-07-23 18:22:29 -07001943 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001944 removeImpl(mTimeTickSender);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001945 rebatchAllAlarms();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 mClockReceiver.scheduleTimeTickEvent();
Dianne Hackborn998e6082014-09-11 19:13:23 -07001947 synchronized (mLock) {
1948 mNumTimeChanged++;
1949 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001950 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
Dianne Hackborn89ba6752011-01-23 16:51:16 -08001951 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1952 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001953 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001954 }
1955
1956 synchronized (mLock) {
1957 final long nowRTC = System.currentTimeMillis();
1958 final long nowELAPSED = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001959 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 TAG, "Checking for alarms... rtc=" + nowRTC
1961 + ", elapsed=" + nowELAPSED);
1962
Christopher Tate18a75f12013-07-01 18:18:59 -07001963 if (WAKEUP_STATS) {
1964 if ((result & IS_WAKEUP_MASK) != 0) {
1965 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
1966 int n = 0;
1967 for (WakeupEvent event : mRecentWakeups) {
1968 if (event.when > newEarliest) break;
1969 n++; // number of now-stale entries at the list head
1970 }
1971 for (int i = 0; i < n; i++) {
1972 mRecentWakeups.remove();
1973 }
1974
Christopher Tatee0a22b32013-07-11 14:43:13 -07001975 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Christopher Tate18a75f12013-07-01 18:18:59 -07001976 }
1977 }
1978
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001979 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
1980 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
1981 // if there are no wakeup alarms and the screen is off, we can
1982 // delay what we have so far until the future.
1983 if (mPendingNonWakeupAlarms.size() == 0) {
1984 mStartCurrentDelayTime = nowELAPSED;
1985 mNextNonWakeupDeliveryTime = nowELAPSED
1986 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001988 mPendingNonWakeupAlarms.addAll(triggerList);
1989 mNumDelayedAlarms += triggerList.size();
1990 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001991 updateNextAlarmClockLocked();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001992 } else {
1993 // now deliver the alarm intents; if there are pending non-wakeup
1994 // alarms, we need to merge them in to the list. note we don't
1995 // just deliver them first because we generally want non-wakeup
1996 // alarms delivered after wakeup alarms.
1997 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001998 updateNextAlarmClockLocked();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001999 if (mPendingNonWakeupAlarms.size() > 0) {
Christopher Tate1590f1e2014-10-02 17:27:57 -07002000 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002001 triggerList.addAll(mPendingNonWakeupAlarms);
2002 Collections.sort(triggerList, mAlarmDispatchComparator);
2003 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2004 mTotalDelayTime += thisDelayTime;
2005 if (mMaxDelayTime < thisDelayTime) {
2006 mMaxDelayTime = thisDelayTime;
2007 }
2008 mPendingNonWakeupAlarms.clear();
2009 }
2010 deliverAlarmsLocked(triggerList, nowELAPSED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002011 }
2012 }
2013 }
2014 }
2015 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002016
David Christieebe51fc2013-07-26 13:23:29 -07002017 /**
2018 * Attribute blame for a WakeLock.
2019 * @param pi PendingIntent to attribute blame to if ws is null.
2020 * @param ws WorkSource to attribute blame.
2021 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002022 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
2023 boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07002024 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002025 final boolean unimportant = pi == mTimeTickSender;
2026 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002027 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002028 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002029 } else {
2030 mWakeLock.setHistoryTag(null);
2031 }
2032 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07002033 if (ws != null) {
2034 mWakeLock.setWorkSource(ws);
2035 return;
2036 }
2037
Christopher Tatec4a07d12012-04-06 14:19:13 -07002038 final int uid = ActivityManagerNative.getDefault()
2039 .getUidForIntentSender(pi.getTarget());
2040 if (uid >= 0) {
2041 mWakeLock.setWorkSource(new WorkSource(uid));
2042 return;
2043 }
2044 } catch (Exception e) {
2045 }
2046
2047 // Something went wrong; fall back to attributing the lock to the OS
2048 mWakeLock.setWorkSource(null);
2049 }
2050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051 private class AlarmHandler extends Handler {
2052 public static final int ALARM_EVENT = 1;
2053 public static final int MINUTE_CHANGE_EVENT = 2;
2054 public static final int DATE_CHANGE_EVENT = 3;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002055 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002056
2057 public AlarmHandler() {
2058 }
2059
2060 public void handleMessage(Message msg) {
2061 if (msg.what == ALARM_EVENT) {
2062 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2063 synchronized (mLock) {
2064 final long nowRTC = System.currentTimeMillis();
Christopher Tatee0a22b32013-07-11 14:43:13 -07002065 final long nowELAPSED = SystemClock.elapsedRealtime();
2066 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002067 updateNextAlarmClockLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002068 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002069
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070 // now trigger the alarms without the lock held
Dianne Hackborn390517b2013-05-30 15:03:32 -07002071 for (int i=0; i<triggerList.size(); i++) {
2072 Alarm alarm = triggerList.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002073 try {
2074 alarm.operation.send();
2075 } catch (PendingIntent.CanceledException e) {
2076 if (alarm.repeatInterval > 0) {
2077 // This IntentSender is no longer valid, but this
2078 // is a repeating alarm, so toss the hoser.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002079 removeImpl(alarm.operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002080 }
2081 }
2082 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002083 } else if (msg.what == SEND_NEXT_ALARM_CLOCK_CHANGED) {
2084 sendNextAlarmClockChanged();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002085 }
2086 }
2087 }
2088
2089 class ClockReceiver extends BroadcastReceiver {
2090 public ClockReceiver() {
2091 IntentFilter filter = new IntentFilter();
2092 filter.addAction(Intent.ACTION_TIME_TICK);
2093 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002094 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002095 }
2096
2097 @Override
2098 public void onReceive(Context context, Intent intent) {
2099 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07002100 if (DEBUG_BATCH) {
2101 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
2102 }
2103 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002104 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
2105 // Since the kernel does not keep track of DST, we need to
2106 // reset the TZ information at the beginning of each day
2107 // based off of the current Zone gmt offset + userspace tracked
2108 // daylight savings information.
2109 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02002110 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002111 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07002112 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002113 }
2114 }
2115
2116 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07002117 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09002118 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07002119
2120 // Schedule this event for the amount of time that it would take to get to
2121 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09002122 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07002123
David Christieebe51fc2013-07-26 13:23:29 -07002124 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002125 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002126 0, mTimeTickSender, AlarmManager.FLAG_STANDALONE, workSource, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002127 }
Christopher Tate385e4982013-07-23 18:22:29 -07002128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002129 public void scheduleDateChangedEvent() {
2130 Calendar calendar = Calendar.getInstance();
2131 calendar.setTimeInMillis(System.currentTimeMillis());
2132 calendar.set(Calendar.HOUR, 0);
2133 calendar.set(Calendar.MINUTE, 0);
2134 calendar.set(Calendar.SECOND, 0);
2135 calendar.set(Calendar.MILLISECOND, 0);
2136 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07002137
2138 final WorkSource workSource = null; // Let system take blame for date change events.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002139 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender,
2140 AlarmManager.FLAG_STANDALONE, workSource, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002141 }
2142 }
2143
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002144 class InteractiveStateReceiver extends BroadcastReceiver {
2145 public InteractiveStateReceiver() {
2146 IntentFilter filter = new IntentFilter();
2147 filter.addAction(Intent.ACTION_SCREEN_OFF);
2148 filter.addAction(Intent.ACTION_SCREEN_ON);
2149 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
2150 getContext().registerReceiver(this, filter);
2151 }
2152
2153 @Override
2154 public void onReceive(Context context, Intent intent) {
2155 synchronized (mLock) {
2156 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
2157 }
2158 }
2159 }
2160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002161 class UninstallReceiver extends BroadcastReceiver {
2162 public UninstallReceiver() {
2163 IntentFilter filter = new IntentFilter();
2164 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2165 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002166 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002167 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08002168 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002169 // Register for events related to sdcard installation.
2170 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08002171 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002172 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002173 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002174 }
2175
2176 @Override
2177 public void onReceive(Context context, Intent intent) {
2178 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002179 String action = intent.getAction();
2180 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002181 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
2182 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
2183 for (String packageName : pkgList) {
2184 if (lookForPackageLocked(packageName)) {
2185 setResultCode(Activity.RESULT_OK);
2186 return;
2187 }
2188 }
2189 return;
2190 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002191 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002192 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
2193 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
2194 if (userHandle >= 0) {
2195 removeUserLocked(userHandle);
2196 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002197 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08002198 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
2199 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
2200 // This package is being updated; don't kill its alarms.
2201 return;
2202 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002203 Uri data = intent.getData();
2204 if (data != null) {
2205 String pkg = data.getSchemeSpecificPart();
2206 if (pkg != null) {
2207 pkgList = new String[]{pkg};
2208 }
2209 }
2210 }
2211 if (pkgList != null && (pkgList.length > 0)) {
2212 for (String pkg : pkgList) {
2213 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07002214 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002215 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
2216 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
2217 if (uidStats.remove(pkg) != null) {
2218 if (uidStats.size() <= 0) {
2219 mBroadcastStats.removeAt(i);
2220 }
2221 }
2222 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002223 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002224 }
2225 }
2226 }
2227 }
2228
2229 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002230 String pkg = pi.getCreatorPackage();
2231 int uid = pi.getCreatorUid();
2232 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
2233 if (uidStats == null) {
2234 uidStats = new ArrayMap<String, BroadcastStats>();
2235 mBroadcastStats.put(uid, uidStats);
2236 }
2237 BroadcastStats bs = uidStats.get(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002238 if (bs == null) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002239 bs = new BroadcastStats(uid, pkg);
2240 uidStats.put(pkg, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002241 }
2242 return bs;
2243 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002245 class ResultReceiver implements PendingIntent.OnFinished {
2246 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
2247 String resultData, Bundle resultExtras) {
2248 synchronized (mLock) {
Dianne Hackborn81038902012-11-26 17:04:09 -08002249 InFlight inflight = null;
2250 for (int i=0; i<mInFlight.size(); i++) {
2251 if (mInFlight.get(i).mPendingIntent == pi) {
2252 inflight = mInFlight.remove(i);
2253 break;
2254 }
2255 }
2256 if (inflight != null) {
2257 final long nowELAPSED = SystemClock.elapsedRealtime();
2258 BroadcastStats bs = inflight.mBroadcastStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002259 bs.nesting--;
2260 if (bs.nesting <= 0) {
2261 bs.nesting = 0;
Dianne Hackborn81038902012-11-26 17:04:09 -08002262 bs.aggregateTime += nowELAPSED - bs.startTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002263 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002264 FilterStats fs = inflight.mFilterStats;
2265 fs.nesting--;
2266 if (fs.nesting <= 0) {
2267 fs.nesting = 0;
2268 fs.aggregateTime += nowELAPSED - fs.startTime;
2269 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07002270 if (RECORD_ALARMS_IN_HISTORY) {
2271 if (inflight.mWorkSource != null && inflight.mWorkSource.size() > 0) {
2272 for (int wi=0; wi<inflight.mWorkSource.size(); wi++) {
2273 ActivityManagerNative.noteAlarmFinish(
2274 pi, inflight.mWorkSource.get(wi), inflight.mTag);
2275 }
2276 } else {
2277 ActivityManagerNative.noteAlarmFinish(
2278 pi, -1, inflight.mTag);
2279 }
2280 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002281 } else {
2282 mLog.w("No in-flight alarm for " + pi + " " + intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002283 }
2284 mBroadcastRefCount--;
2285 if (mBroadcastRefCount == 0) {
2286 mWakeLock.release();
Dianne Hackborn81038902012-11-26 17:04:09 -08002287 if (mInFlight.size() > 0) {
2288 mLog.w("Finished all broadcasts with " + mInFlight.size()
2289 + " remaining inflights");
2290 for (int i=0; i<mInFlight.size(); i++) {
2291 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
2292 }
2293 mInFlight.clear();
2294 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002295 } else {
2296 // the next of our alarms is now in flight. reattribute the wakelock.
Dianne Hackborn81038902012-11-26 17:04:09 -08002297 if (mInFlight.size() > 0) {
David Christieebe51fc2013-07-26 13:23:29 -07002298 InFlight inFlight = mInFlight.get(0);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08002299 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002300 inFlight.mAlarmType, inFlight.mTag, false);
Christopher Tatec4a07d12012-04-06 14:19:13 -07002301 } else {
2302 // should never happen
Dianne Hackborn81038902012-11-26 17:04:09 -08002303 mLog.w("Alarm wakelock still held but sent queue empty");
Christopher Tatec4a07d12012-04-06 14:19:13 -07002304 mWakeLock.setWorkSource(null);
2305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002306 }
2307 }
2308 }
2309 }
2310}