blob: 34e8b7867f10970991bce3701f6a48436ba2acbe [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;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800102 static final int ALARM_EVENT = 1;
103 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200104
Adam Lesinski182f73f2013-12-05 16:48:06 -0800105 static final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800107 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108
Adam Lesinski182f73f2013-12-05 16:48:06 -0800109 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700110
Adrian Roosc42a1e12014-07-07 23:35:53 +0200111 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT = new Intent(
112 AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED);
113
Adam Lesinski182f73f2013-12-05 16:48:06 -0800114 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800115
Adam Lesinski182f73f2013-12-05 16:48:06 -0800116 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800117
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800118 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800119 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700120 private long mNextNonWakeup;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800121 int mBroadcastRefCount = 0;
122 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700123 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700124 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<Alarm>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800125 ArrayList<InFlight> mInFlight = new ArrayList<InFlight>();
126 final AlarmHandler mHandler = new AlarmHandler();
127 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700128 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129 private UninstallReceiver mUninstallReceiver;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800130 final ResultReceiver mResultReceiver = new ResultReceiver();
131 PendingIntent mTimeTickSender;
132 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700133 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700134 boolean mInteractive = true;
135 long mNonInteractiveStartTime;
136 long mNonInteractiveTime;
137 long mLastAlarmDeliveryTime;
138 long mStartCurrentDelayTime;
139 long mNextNonWakeupDeliveryTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700140 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800141
Jose Lima235510e2014-08-13 12:50:01 -0700142 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
143 new SparseArray<>();
144 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
145 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200146 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
147 new SparseBooleanArray();
148 private boolean mNextAlarmClockMayChange;
149
150 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700151 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
152 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200153
Christopher Tate1590f1e2014-10-02 17:27:57 -0700154 // Alarm delivery ordering bookkeeping
155 static final int PRIO_TICK = 0;
156 static final int PRIO_WAKEUP = 1;
157 static final int PRIO_NORMAL = 2;
158
159 class PriorityClass {
160 int seq;
161 int priority;
162
163 PriorityClass() {
164 seq = mCurrentSeq - 1;
165 priority = PRIO_NORMAL;
166 }
167 }
168
169 final HashMap<String, PriorityClass> mPriorities =
170 new HashMap<String, PriorityClass>();
171 int mCurrentSeq = 0;
172
Christopher Tate18a75f12013-07-01 18:18:59 -0700173 class WakeupEvent {
174 public long when;
175 public int uid;
176 public String action;
177
178 public WakeupEvent(long theTime, int theUid, String theAction) {
179 when = theTime;
180 uid = theUid;
181 action = theAction;
182 }
183 }
184
Adam Lesinski182f73f2013-12-05 16:48:06 -0800185 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
186 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700187
Adrian Roosc42a1e12014-07-07 23:35:53 +0200188 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700189 long start; // These endpoints are always in ELAPSED
190 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700191 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700192
193 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
194
195 Batch() {
196 start = 0;
197 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700198 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700199 }
200
201 Batch(Alarm seed) {
202 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700203 end = seed.maxWhenElapsed;
204 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700205 alarms.add(seed);
206 }
207
208 int size() {
209 return alarms.size();
210 }
211
212 Alarm get(int index) {
213 return alarms.get(index);
214 }
215
216 boolean canHold(long whenElapsed, long maxWhen) {
217 return (end >= whenElapsed) && (start <= maxWhen);
218 }
219
220 boolean add(Alarm alarm) {
221 boolean newStart = false;
222 // narrows the batch if necessary; presumes that canHold(alarm) is true
223 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
224 if (index < 0) {
225 index = 0 - index - 1;
226 }
227 alarms.add(index, alarm);
228 if (DEBUG_BATCH) {
229 Slog.v(TAG, "Adding " + alarm + " to " + this);
230 }
231 if (alarm.whenElapsed > start) {
232 start = alarm.whenElapsed;
233 newStart = true;
234 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700235 if (alarm.maxWhenElapsed < end) {
236 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700237 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700238 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700239
240 if (DEBUG_BATCH) {
241 Slog.v(TAG, " => now " + this);
242 }
243 return newStart;
244 }
245
246 boolean remove(final PendingIntent operation) {
247 boolean didRemove = false;
248 long newStart = 0; // recalculate endpoints as we go
249 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700250 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700251 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700252 Alarm alarm = alarms.get(i);
253 if (alarm.operation.equals(operation)) {
254 alarms.remove(i);
255 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200256 if (alarm.alarmClock != null) {
257 mNextAlarmClockMayChange = true;
258 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700259 } else {
260 if (alarm.whenElapsed > newStart) {
261 newStart = alarm.whenElapsed;
262 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700263 if (alarm.maxWhenElapsed < newEnd) {
264 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700265 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700266 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700267 i++;
268 }
269 }
270 if (didRemove) {
271 // commit the new batch bounds
272 start = newStart;
273 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700274 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700275 }
276 return didRemove;
277 }
278
279 boolean remove(final String packageName) {
280 boolean didRemove = false;
281 long newStart = 0; // recalculate endpoints as we go
282 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700283 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700284 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700285 Alarm alarm = alarms.get(i);
286 if (alarm.operation.getTargetPackage().equals(packageName)) {
287 alarms.remove(i);
288 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200289 if (alarm.alarmClock != null) {
290 mNextAlarmClockMayChange = true;
291 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700292 } else {
293 if (alarm.whenElapsed > newStart) {
294 newStart = alarm.whenElapsed;
295 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700296 if (alarm.maxWhenElapsed < newEnd) {
297 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700298 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700299 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700300 i++;
301 }
302 }
303 if (didRemove) {
304 // commit the new batch bounds
305 start = newStart;
306 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700307 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700308 }
309 return didRemove;
310 }
311
312 boolean remove(final int userHandle) {
313 boolean didRemove = false;
314 long newStart = 0; // recalculate endpoints as we go
315 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700316 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700317 Alarm alarm = alarms.get(i);
318 if (UserHandle.getUserId(alarm.operation.getCreatorUid()) == userHandle) {
319 alarms.remove(i);
320 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200321 if (alarm.alarmClock != null) {
322 mNextAlarmClockMayChange = true;
323 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700324 } else {
325 if (alarm.whenElapsed > newStart) {
326 newStart = alarm.whenElapsed;
327 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700328 if (alarm.maxWhenElapsed < newEnd) {
329 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700330 }
331 i++;
332 }
333 }
334 if (didRemove) {
335 // commit the new batch bounds
336 start = newStart;
337 end = newEnd;
338 }
339 return didRemove;
340 }
341
342 boolean hasPackage(final String packageName) {
343 final int N = alarms.size();
344 for (int i = 0; i < N; i++) {
345 Alarm a = alarms.get(i);
346 if (a.operation.getTargetPackage().equals(packageName)) {
347 return true;
348 }
349 }
350 return false;
351 }
352
353 boolean hasWakeups() {
354 final int N = alarms.size();
355 for (int i = 0; i < N; i++) {
356 Alarm a = alarms.get(i);
357 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
358 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
359 return true;
360 }
361 }
362 return false;
363 }
364
365 @Override
366 public String toString() {
367 StringBuilder b = new StringBuilder(40);
368 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
369 b.append(" num="); b.append(size());
370 b.append(" start="); b.append(start);
371 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700372 if (flags != 0) {
373 b.append(" flgs=0x");
374 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700375 }
376 b.append('}');
377 return b.toString();
378 }
379 }
380
381 static class BatchTimeOrder implements Comparator<Batch> {
382 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800383 long when1 = b1.start;
384 long when2 = b2.start;
385 if (when1 - when2 > 0) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700386 return 1;
387 }
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800388 if (when1 - when2 < 0) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700389 return -1;
390 }
391 return 0;
392 }
393 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800394
395 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
396 @Override
397 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700398 // priority class trumps everything. TICK < WAKEUP < NORMAL
399 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
400 return -1;
401 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
402 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800403 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700404
405 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800406 if (lhs.whenElapsed < rhs.whenElapsed) {
407 return -1;
408 } else if (lhs.whenElapsed > rhs.whenElapsed) {
409 return 1;
410 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700411
412 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800413 return 0;
414 }
415 };
416
Christopher Tate1590f1e2014-10-02 17:27:57 -0700417 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
418 final int N = alarms.size();
419 for (int i = 0; i < N; i++) {
420 Alarm a = alarms.get(i);
421
422 final int alarmPrio;
423 if (Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
424 alarmPrio = PRIO_TICK;
425 } else if (a.wakeup) {
426 alarmPrio = PRIO_WAKEUP;
427 } else {
428 alarmPrio = PRIO_NORMAL;
429 }
430
431 PriorityClass packagePrio = a.priorityClass;
432 if (packagePrio == null) packagePrio = mPriorities.get(a.operation.getCreatorPackage());
433 if (packagePrio == null) {
434 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
435 mPriorities.put(a.operation.getCreatorPackage(), packagePrio);
436 }
437 a.priorityClass = packagePrio;
438
439 if (packagePrio.seq != mCurrentSeq) {
440 // first alarm we've seen in the current delivery generation from this package
441 packagePrio.priority = alarmPrio;
442 packagePrio.seq = mCurrentSeq;
443 } else {
444 // Multiple alarms from this package being delivered in this generation;
445 // bump the package's delivery class if it's warranted.
446 // TICK < WAKEUP < NORMAL
447 if (alarmPrio < packagePrio.priority) {
448 packagePrio.priority = alarmPrio;
449 }
450 }
451 }
452 }
453
Christopher Tatee0a22b32013-07-11 14:43:13 -0700454 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800455 static final long MIN_FUZZABLE_INTERVAL = 10000;
456 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700457 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
458
459 // set to null if in idle mode; while in this mode, any alarms we don't want
460 // to run during this time are placed in mPendingWhileIdleAlarms
461 Alarm mPendingIdleUntil = null;
462 final ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700463
Jeff Brownb880d882014-02-10 19:47:07 -0800464 public AlarmManagerService(Context context) {
465 super(context);
466 }
467
Christopher Tatee0a22b32013-07-11 14:43:13 -0700468 static long convertToElapsed(long when, int type) {
469 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
470 if (isRtc) {
471 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
472 }
473 return when;
474 }
475
476 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
477 // calculate the end of our nominal delivery window for the alarm.
478 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
479 // Current heuristic: batchable window is 75% of either the recurrence interval
480 // [for a periodic alarm] or of the time from now to the desired delivery time,
481 // with a minimum delay/interval of 10 seconds, under which we will simply not
482 // defer the alarm.
483 long futurity = (interval == 0)
484 ? (triggerAtTime - now)
485 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700486 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700487 futurity = 0;
488 }
489 return triggerAtTime + (long)(.75 * futurity);
490 }
491
492 // returns true if the batch was added at the head
493 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
494 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
495 if (index < 0) {
496 index = 0 - index - 1;
497 }
498 list.add(index, newBatch);
499 return (index == 0);
500 }
501
Christopher Tate385e4982013-07-23 18:22:29 -0700502 // Return the index of the matching batch, or -1 if none found.
503 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700504 final int N = mAlarmBatches.size();
505 for (int i = 0; i < N; i++) {
506 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700507 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700508 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700509 }
510 }
Christopher Tate385e4982013-07-23 18:22:29 -0700511 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700512 }
513
514 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
515 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700516 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700517 rebatchAllAlarmsLocked(true);
518 }
519 }
520
521 void rebatchAllAlarmsLocked(boolean doValidate) {
522 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
523 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700524 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700525 final long nowElapsed = SystemClock.elapsedRealtime();
526 final int oldBatches = oldSet.size();
527 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
528 Batch batch = oldSet.get(batchNum);
529 final int N = batch.size();
530 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700531 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700532 }
533 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700534 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
535 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
536 + " to " + mPendingIdleUntil);
537 if (mPendingIdleUntil == null) {
538 // Somehow we lost this... we need to restore all of the pending alarms.
539 restorePendingWhileIdleAlarmsLocked();
540 }
541 }
542 rescheduleKernelAlarmsLocked();
543 updateNextAlarmClockLocked();
544 }
545
546 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
547 a.when = a.origWhen;
548 long whenElapsed = convertToElapsed(a.when, a.type);
549 final long maxElapsed;
550 if (a.whenElapsed == a.maxWhenElapsed) {
551 // Exact
552 maxElapsed = whenElapsed;
553 } else {
554 // Not exact. Preserve any explicit window, otherwise recalculate
555 // the window based on the alarm's new futurity. Note that this
556 // reflects a policy of preferring timely to deferred delivery.
557 maxElapsed = (a.windowLength > 0)
558 ? (whenElapsed + a.windowLength)
559 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
560 }
561 a.whenElapsed = whenElapsed;
562 a.maxWhenElapsed = maxElapsed;
563 setImplLocked(a, true, doValidate);
564 }
565
566 void restorePendingWhileIdleAlarmsLocked() {
567 final long nowElapsed = SystemClock.elapsedRealtime();
568 for (int i=mPendingWhileIdleAlarms.size() - 1; i >= 0 && mPendingIdleUntil != null; i --) {
569 Alarm a = mPendingWhileIdleAlarms.remove(i);
570 reAddAlarmLocked(a, nowElapsed, false);
571 }
572 rescheduleKernelAlarmsLocked();
573 updateNextAlarmClockLocked();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700574 }
575
Adam Lesinski182f73f2013-12-05 16:48:06 -0800576 static final class InFlight extends Intent {
Dianne Hackborn81038902012-11-26 17:04:09 -0800577 final PendingIntent mPendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700578 final WorkSource mWorkSource;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700579 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800580 final BroadcastStats mBroadcastStats;
581 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800582 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800583
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800584 InFlight(AlarmManagerService service, PendingIntent pendingIntent, WorkSource workSource,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700585 int alarmType, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800586 mPendingIntent = pendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700587 mWorkSource = workSource;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700588 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800589 mBroadcastStats = service.getStatsLocked(pendingIntent);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700590 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -0800591 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700592 fs = new FilterStats(mBroadcastStats, mTag);
593 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -0800594 }
595 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800596 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800597 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800598 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800599
Adam Lesinski182f73f2013-12-05 16:48:06 -0800600 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -0800601 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700602 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800605 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606 int numWakeup;
607 long startTime;
608 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -0800609
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700610 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800611 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700612 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800613 }
614 }
615
Adam Lesinski182f73f2013-12-05 16:48:06 -0800616 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800617 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800618 final String mPackageName;
619
620 long aggregateTime;
621 int count;
622 int numWakeup;
623 long startTime;
624 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700625 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -0800626
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800627 BroadcastStats(int uid, String packageName) {
628 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800629 mPackageName = packageName;
630 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800631 }
632
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800633 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
634 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700635
636 int mNumDelayedAlarms = 0;
637 long mTotalDelayTime = 0;
638 long mMaxDelayTime = 0;
639
Adam Lesinski182f73f2013-12-05 16:48:06 -0800640 @Override
641 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800642 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800643 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800644
645 // We have to set current TimeZone info to kernel
646 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -0800647 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800648
Adam Lesinski182f73f2013-12-05 16:48:06 -0800649 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800650 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800651
Adam Lesinski182f73f2013-12-05 16:48:06 -0800652 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700654 Intent.FLAG_RECEIVER_REGISTERED_ONLY
655 | Intent.FLAG_RECEIVER_FOREGROUND), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700656 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800657 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
658 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800659 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700660 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661
662 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -0800663 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664 mClockReceiver.scheduleTimeTickEvent();
665 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700666 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 mUninstallReceiver = new UninstallReceiver();
668
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800669 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800670 AlarmThread waitThread = new AlarmThread();
671 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800673 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800675
676 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800677 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800678
679 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680 protected void finalize() throws Throwable {
681 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800682 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 } finally {
684 super.finalize();
685 }
686 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700687
Adam Lesinski182f73f2013-12-05 16:48:06 -0800688 void setTimeZoneImpl(String tz) {
689 if (TextUtils.isEmpty(tz)) {
690 return;
David Christieebe51fc2013-07-26 13:23:29 -0700691 }
692
Adam Lesinski182f73f2013-12-05 16:48:06 -0800693 TimeZone zone = TimeZone.getTimeZone(tz);
694 // Prevent reentrant calls from stepping on each other when writing
695 // the time zone property
696 boolean timeZoneWasChanged = false;
697 synchronized (this) {
698 String current = SystemProperties.get(TIMEZONE_PROPERTY);
699 if (current == null || !current.equals(zone.getID())) {
700 if (localLOGV) {
701 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
702 }
703 timeZoneWasChanged = true;
704 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
705 }
706
707 // Update the kernel timezone information
708 // Kernel tracks time offsets as 'minutes west of GMT'
709 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800710 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -0800711 }
712
713 TimeZone.setDefault(null);
714
715 if (timeZoneWasChanged) {
716 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
717 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
718 intent.putExtra("time-zone", zone.getID());
719 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
720 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700722
Adam Lesinski182f73f2013-12-05 16:48:06 -0800723 void removeImpl(PendingIntent operation) {
724 if (operation == null) {
725 return;
726 }
727 synchronized (mLock) {
728 removeLocked(operation);
729 }
730 }
731
732 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700733 PendingIntent operation, int flags, WorkSource workSource,
Jose Lima235510e2014-08-13 12:50:01 -0700734 AlarmManager.AlarmClockInfo alarmClock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 if (operation == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800736 Slog.w(TAG, "set/setRepeating ignored because there is no intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737 return;
738 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700739
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700740 // Sanity check the window length. This will catch people mistakenly
741 // trying to pass an end-of-window timestamp rather than a duration.
742 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
743 Slog.w(TAG, "Window length " + windowLength
744 + "ms suspiciously long; limiting to 1 hour");
745 windowLength = AlarmManager.INTERVAL_HOUR;
746 }
747
Christopher Tate498c6cb2014-11-17 16:09:27 -0800748 // Sanity check the recurrence interval. This will catch people who supply
749 // seconds when the API expects milliseconds.
750 if (interval > 0 && interval < MIN_INTERVAL) {
751 Slog.w(TAG, "Suspiciously short interval " + interval
752 + " millis; expanding to " + (int)(MIN_INTERVAL/1000)
753 + " seconds");
754 interval = MIN_INTERVAL;
755 }
756
Christopher Tatee0a22b32013-07-11 14:43:13 -0700757 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
758 throw new IllegalArgumentException("Invalid alarm type " + type);
759 }
760
Christopher Tate5f221e82013-07-30 17:13:15 -0700761 if (triggerAtTime < 0) {
762 final long who = Binder.getCallingUid();
763 final long what = Binder.getCallingPid();
764 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + who
765 + " pid=" + what);
766 triggerAtTime = 0;
767 }
768
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700769 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -0800770 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
771 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
772 final long minTrigger = nowElapsed + MIN_FUTURITY;
773 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
774
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700775 final long maxElapsed;
776 if (windowLength == AlarmManager.WINDOW_EXACT) {
777 maxElapsed = triggerElapsed;
778 } else if (windowLength < 0) {
779 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
780 } else {
781 maxElapsed = triggerElapsed + windowLength;
782 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700783
Adrian Roosc42a1e12014-07-07 23:35:53 +0200784 final int userId = UserHandle.getCallingUserId();
785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700787 if (DEBUG_BATCH) {
788 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700789 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -0700790 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700791 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792 }
Christopher Tate3e04b472013-10-21 17:51:31 -0700793 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700794 interval, operation, flags, true, workSource, alarmClock, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795 }
796 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800797
Christopher Tate3e04b472013-10-21 17:51:31 -0700798 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700799 long maxWhen, long interval, PendingIntent operation, int flags,
Jose Lima235510e2014-08-13 12:50:01 -0700800 boolean doValidate, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
801 int userId) {
Christopher Tate3e04b472013-10-21 17:51:31 -0700802 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700803 operation, workSource, flags, alarmClock, userId);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700804 removeLocked(operation);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700805 setImplLocked(a, false, doValidate);
806 }
Christopher Tateb8849c12011-02-08 13:39:01 -0800807
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700808 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
809 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
810 // This is a special alarm that will put the system idle until it goes off.
811 // The caller has given the time they want this to happen at, however we need
812 // to pull that earlier if there are existing alarms that have requested to
813 // bring us out of idle.
814 final int N = mAlarmBatches.size();
815 for (int i = 0; i < N; i++) {
816 Batch b = mAlarmBatches.get(i);
817 if (a.whenElapsed > b.end) {
818 // There are no interesting things happening before our idle until,
819 // so keep the requested time.
820 break;
821 }
822 if ((b.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
823 a.when = a.whenElapsed = a.maxWhenElapsed = b.end;
824 break;
825 }
826 }
827 // Add fuzz to make the alarm go off some time before the actual desired time.
828 final long nowElapsed = SystemClock.elapsedRealtime();
829 long fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
830 if (fuzz > 0) {
831 if (mRandom == null) {
832 mRandom = new Random();
833 }
834 a.whenElapsed -= mRandom.nextLong() % fuzz;
835 }
836
837 } else if (mPendingIdleUntil != null) {
838 // We currently have an idle until alarm scheduled; if the new alarm has
839 // not explicitly stated it wants to run while idle, then put it on hold.
840 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE|AlarmManager.FLAG_WAKE_FROM_IDLE))
841 == 0) {
842 mPendingWhileIdleAlarms.add(a);
843 return;
844 }
845 }
846
847 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
848 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -0700849 if (whichBatch < 0) {
850 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -0700851 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852 } else {
Christopher Tate385e4982013-07-23 18:22:29 -0700853 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -0700854 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700855 // The start time of this batch advanced, so batch ordering may
856 // have just been broken. Move it to where it now belongs.
857 mAlarmBatches.remove(whichBatch);
858 addBatchLocked(mAlarmBatches, batch);
859 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 }
861
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700862 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +0200863 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200864 }
865
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700866 boolean needRebatch = false;
867
868 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
869 mPendingIdleUntil = a;
870 needRebatch = true;
871 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0 && mPendingIdleUntil != null) {
872 // If we are adding an alarm that asks to wake from idle, and we are currently
873 // idling, then we need to rebatch alarms in case the idle until time needs to
874 // be updated.
875 needRebatch = true;
876 }
877
878 if (!rebatching) {
879 if (DEBUG_VALIDATE) {
880 if (doValidate && !validateConsistencyLocked()) {
881 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
882 + " when(hex)=" + Long.toHexString(a.when)
883 + " whenElapsed=" + a.whenElapsed
884 + " maxWhenElapsed=" + a.maxWhenElapsed
885 + " interval=" + a.repeatInterval + " op=" + a.operation
886 + " flags=0x" + Integer.toHexString(a.flags));
887 rebatchAllAlarmsLocked(false);
888 needRebatch = false;
889 }
890 }
891
892 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700893 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -0700894 }
Christopher Tate4cb338d2013-07-26 13:11:31 -0700895
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700896 rescheduleKernelAlarmsLocked();
897 updateNextAlarmClockLocked();
898 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700899 }
900
Adam Lesinski182f73f2013-12-05 16:48:06 -0800901 private final IBinder mService = new IAlarmManager.Stub() {
902 @Override
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700903 public void set(int type, long triggerAtTime, long windowLength, long interval, int flags,
Jose Lima235510e2014-08-13 12:50:01 -0700904 PendingIntent operation, WorkSource workSource,
905 AlarmManager.AlarmClockInfo alarmClock) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800906 if (workSource != null) {
907 getContext().enforceCallingPermission(
908 android.Manifest.permission.UPDATE_DEVICE_STATS,
909 "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -0700910 }
911
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700912 if (windowLength == AlarmManager.WINDOW_EXACT) {
913 flags |= AlarmManager.FLAG_STANDALONE;
914 }
915 if (alarmClock != null) {
916 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
917 }
918 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
919 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE;
920 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800921 setImpl(type, triggerAtTime, windowLength, interval, operation,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700922 flags, workSource, alarmClock);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800923 }
Christopher Tate89779822012-08-31 14:40:03 -0700924
Adam Lesinski182f73f2013-12-05 16:48:06 -0800925 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -0800926 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800927 getContext().enforceCallingOrSelfPermission(
928 "android.permission.SET_TIME",
929 "setTime");
930
Greg Hackmann0cab8962014-02-21 16:35:52 -0800931 if (mNativeData == 0) {
932 Slog.w(TAG, "Not setting time since no alarm driver is available.");
933 return false;
Christopher Tate89779822012-08-31 14:40:03 -0700934 }
Greg Hackmann0cab8962014-02-21 16:35:52 -0800935
936 synchronized (mLock) {
937 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800938 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800939 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800940
941 @Override
942 public void setTimeZone(String tz) {
943 getContext().enforceCallingOrSelfPermission(
944 "android.permission.SET_TIME_ZONE",
945 "setTimeZone");
946
947 final long oldId = Binder.clearCallingIdentity();
948 try {
949 setTimeZoneImpl(tz);
950 } finally {
951 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 }
953 }
Christopher Tate4cb338d2013-07-26 13:11:31 -0700954
Adam Lesinski182f73f2013-12-05 16:48:06 -0800955 @Override
956 public void remove(PendingIntent operation) {
957 removeImpl(operation);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 }
Christopher Tate4cb338d2013-07-26 13:11:31 -0700960
Adam Lesinski182f73f2013-12-05 16:48:06 -0800961 @Override
Jose Lima235510e2014-08-13 12:50:01 -0700962 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +0200963 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
964 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
965 "getNextAlarmClock", null);
966
967 return getNextAlarmClockImpl(userId);
968 }
969
970 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -0800971 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
972 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
973 != PackageManager.PERMISSION_GRANTED) {
974 pw.println("Permission Denial: can't dump AlarmManager from from pid="
975 + Binder.getCallingPid()
976 + ", uid=" + Binder.getCallingUid());
977 return;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700978 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700979
Adam Lesinski182f73f2013-12-05 16:48:06 -0800980 dumpImpl(pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700981 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800982 };
Christopher Tate4cb338d2013-07-26 13:11:31 -0700983
Adam Lesinski182f73f2013-12-05 16:48:06 -0800984 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 synchronized (mLock) {
986 pw.println("Current Alarm Manager state:");
Christopher Tatee0a22b32013-07-11 14:43:13 -0700987 final long nowRTC = System.currentTimeMillis();
988 final long nowELAPSED = SystemClock.elapsedRealtime();
989 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
990
991 pw.print("nowRTC="); pw.print(nowRTC);
992 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800993 pw.print(" nowELAPSED="); TimeUtils.formatDuration(nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700994 pw.println();
995 if (!mInteractive) {
996 pw.print("Time since non-interactive: ");
997 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
998 pw.println();
999 pw.print("Max wakeup delay: ");
1000 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1001 pw.println();
1002 pw.print("Time since last dispatch: ");
1003 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1004 pw.println();
1005 pw.print("Next non-wakeup delivery time: ");
1006 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1007 pw.println();
1008 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001009
1010 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1011 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001012 pw.print("Next non-wakeup alarm: ");
1013 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001014 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001015 pw.print("Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001016 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackborn998e6082014-09-11 19:13:23 -07001017 pw.print("Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001018
1019 if (mAlarmBatches.size() > 0) {
1020 pw.println();
1021 pw.print("Pending alarm batches: ");
1022 pw.println(mAlarmBatches.size());
1023 for (Batch b : mAlarmBatches) {
1024 pw.print(b); pw.println(':');
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001025 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001026 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001028 if (mPendingIdleUntil != null) {
1029 pw.println();
1030 pw.println("Idle mode state:");
1031 pw.print(" Idling until: "); pw.println(mPendingIdleUntil);
1032 mPendingIdleUntil.dump(pw, " ", nowELAPSED, nowRTC, sdf);
1033 pw.println(" Pending alarms:");
1034 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
1035 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001036
1037 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001038 pw.print("Past-due non-wakeup alarms: ");
1039 if (mPendingNonWakeupAlarms.size() > 0) {
1040 pw.println(mPendingNonWakeupAlarms.size());
1041 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
1042 } else {
1043 pw.println("(none)");
1044 }
1045 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
1046 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1047 pw.println();
1048 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
1049 pw.print(", max non-interactive time: ");
1050 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1051 pw.println();
1052
1053 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001054 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001055 pw.println();
1056
1057 if (mLog.dump(pw, " Recent problems", " ")) {
1058 pw.println();
1059 }
1060
1061 final FilterStats[] topFilters = new FilterStats[10];
1062 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1063 @Override
1064 public int compare(FilterStats lhs, FilterStats rhs) {
1065 if (lhs.aggregateTime < rhs.aggregateTime) {
1066 return 1;
1067 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1068 return -1;
1069 }
1070 return 0;
1071 }
1072 };
1073 int len = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001074 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1075 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1076 for (int ip=0; ip<uidStats.size(); ip++) {
1077 BroadcastStats bs = uidStats.valueAt(ip);
1078 for (int is=0; is<bs.filterStats.size(); is++) {
1079 FilterStats fs = bs.filterStats.valueAt(is);
1080 int pos = len > 0
1081 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1082 if (pos < 0) {
1083 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001084 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001085 if (pos < topFilters.length) {
1086 int copylen = topFilters.length - pos - 1;
1087 if (copylen > 0) {
1088 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1089 }
1090 topFilters[pos] = fs;
1091 if (len < topFilters.length) {
1092 len++;
1093 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001094 }
1095 }
1096 }
1097 }
1098 if (len > 0) {
1099 pw.println(" Top Alarms:");
1100 for (int i=0; i<len; i++) {
1101 FilterStats fs = topFilters[i];
1102 pw.print(" ");
1103 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1104 TimeUtils.formatDuration(fs.aggregateTime, pw);
1105 pw.print(" running, "); pw.print(fs.numWakeup);
1106 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001107 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1108 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001109 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001110 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001111 pw.println();
1112 }
1113 }
1114
1115 pw.println(" ");
1116 pw.println(" Alarm Stats:");
1117 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001118 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1119 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1120 for (int ip=0; ip<uidStats.size(); ip++) {
1121 BroadcastStats bs = uidStats.valueAt(ip);
1122 pw.print(" ");
1123 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1124 UserHandle.formatUid(pw, bs.mUid);
1125 pw.print(":");
1126 pw.print(bs.mPackageName);
1127 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1128 pw.print(" running, "); pw.print(bs.numWakeup);
1129 pw.println(" wakeups:");
1130 tmpFilters.clear();
1131 for (int is=0; is<bs.filterStats.size(); is++) {
1132 tmpFilters.add(bs.filterStats.valueAt(is));
1133 }
1134 Collections.sort(tmpFilters, comparator);
1135 for (int i=0; i<tmpFilters.size(); i++) {
1136 FilterStats fs = tmpFilters.get(i);
1137 pw.print(" ");
1138 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1139 TimeUtils.formatDuration(fs.aggregateTime, pw);
1140 pw.print(" "); pw.print(fs.numWakeup);
1141 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001142 pw.print(" alarms: ");
1143 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001144 pw.println();
1145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 }
1147 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001148
1149 if (WAKEUP_STATS) {
1150 pw.println();
1151 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001152 long last = -1;
1153 for (WakeupEvent event : mRecentWakeups) {
1154 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1155 pw.print('|');
1156 if (last < 0) {
1157 pw.print('0');
1158 } else {
1159 pw.print(event.when - last);
1160 }
1161 last = event.when;
1162 pw.print('|'); pw.print(event.uid);
1163 pw.print('|'); pw.print(event.action);
1164 pw.println();
1165 }
1166 pw.println();
1167 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 }
1169 }
1170
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001171 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001172 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
1173 PrintWriter pw = new PrintWriter(bs);
1174 final long nowRTC = System.currentTimeMillis();
1175 final long nowELAPSED = SystemClock.elapsedRealtime();
1176 final int NZ = mAlarmBatches.size();
1177 for (int iz = 0; iz < NZ; iz++) {
1178 Batch bz = mAlarmBatches.get(iz);
1179 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001180 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001181 pw.flush();
1182 Slog.v(TAG, bs.toString());
1183 bs.reset();
1184 }
1185 }
1186
1187 private boolean validateConsistencyLocked() {
1188 if (DEBUG_VALIDATE) {
1189 long lastTime = Long.MIN_VALUE;
1190 final int N = mAlarmBatches.size();
1191 for (int i = 0; i < N; i++) {
1192 Batch b = mAlarmBatches.get(i);
1193 if (b.start >= lastTime) {
1194 // duplicate start times are okay because of standalone batches
1195 lastTime = b.start;
1196 } else {
1197 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001198 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1199 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001200 return false;
1201 }
1202 }
1203 }
1204 return true;
1205 }
1206
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001207 private Batch findFirstWakeupBatchLocked() {
1208 final int N = mAlarmBatches.size();
1209 for (int i = 0; i < N; i++) {
1210 Batch b = mAlarmBatches.get(i);
1211 if (b.hasWakeups()) {
1212 return b;
1213 }
1214 }
1215 return null;
1216 }
1217
Jose Lima235510e2014-08-13 12:50:01 -07001218 private AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001219 synchronized (mLock) {
1220 return mNextAlarmClockForUser.get(userId);
1221 }
1222 }
1223
1224 /**
1225 * Recomputes the next alarm clock for all users.
1226 */
1227 private void updateNextAlarmClockLocked() {
1228 if (!mNextAlarmClockMayChange) {
1229 return;
1230 }
1231 mNextAlarmClockMayChange = false;
1232
Jose Lima235510e2014-08-13 12:50:01 -07001233 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001234 nextForUser.clear();
1235
1236 final int N = mAlarmBatches.size();
1237 for (int i = 0; i < N; i++) {
1238 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
1239 final int M = alarms.size();
1240
1241 for (int j = 0; j < M; j++) {
1242 Alarm a = alarms.get(j);
1243 if (a.alarmClock != null) {
1244 final int userId = a.userId;
1245
1246 if (DEBUG_ALARM_CLOCK) {
1247 Log.v(TAG, "Found AlarmClockInfo at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001248 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02001249 " for user " + userId);
1250 }
1251
1252 // Alarms and batches are sorted by time, no need to compare times here.
1253 if (nextForUser.get(userId) == null) {
1254 nextForUser.put(userId, a.alarmClock);
1255 }
1256 }
1257 }
1258 }
1259
1260 // Update mNextAlarmForUser with new values.
1261 final int NN = nextForUser.size();
1262 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07001263 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001264 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001265 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001266 if (!newAlarm.equals(currentAlarm)) {
1267 updateNextAlarmInfoForUserLocked(userId, newAlarm);
1268 }
1269 }
1270
1271 // Remove users without any alarm clocks scheduled.
1272 final int NNN = mNextAlarmClockForUser.size();
1273 for (int i = NNN - 1; i >= 0; i--) {
1274 int userId = mNextAlarmClockForUser.keyAt(i);
1275 if (nextForUser.get(userId) == null) {
1276 updateNextAlarmInfoForUserLocked(userId, null);
1277 }
1278 }
1279 }
1280
Jose Lima235510e2014-08-13 12:50:01 -07001281 private void updateNextAlarmInfoForUserLocked(int userId,
1282 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001283 if (alarmClock != null) {
1284 if (DEBUG_ALARM_CLOCK) {
1285 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001286 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02001287 }
1288 mNextAlarmClockForUser.put(userId, alarmClock);
1289 } else {
1290 if (DEBUG_ALARM_CLOCK) {
1291 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
1292 }
1293 mNextAlarmClockForUser.remove(userId);
1294 }
1295
1296 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
1297 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1298 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1299 }
1300
1301 /**
1302 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
1303 * for which alarm clocks have changed since the last call to this.
1304 *
1305 * Do not call with a lock held. Only call from mHandler's thread.
1306 *
1307 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
1308 */
1309 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07001310 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001311 pendingUsers.clear();
1312
1313 synchronized (mLock) {
1314 final int N = mPendingSendNextAlarmClockChangedForUser.size();
1315 for (int i = 0; i < N; i++) {
1316 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
1317 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
1318 }
1319 mPendingSendNextAlarmClockChangedForUser.clear();
1320 }
1321
1322 final int N = pendingUsers.size();
1323 for (int i = 0; i < N; i++) {
1324 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001325 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001326 Settings.System.putStringForUser(getContext().getContentResolver(),
1327 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01001328 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02001329 userId);
1330
1331 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
1332 new UserHandle(userId));
1333 }
1334 }
1335
1336 /**
1337 * Formats an alarm like platform/packages/apps/DeskClock used to.
1338 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01001339 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
1340 int userId) {
1341 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02001342 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
1343 return (info == null) ? "" :
1344 DateFormat.format(pattern, info.getTriggerTime()).toString();
1345 }
1346
Adam Lesinski182f73f2013-12-05 16:48:06 -08001347 void rescheduleKernelAlarmsLocked() {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001348 if (mPendingIdleUntil != null) {
1349 // If we have a pending "idle until" alarm, we will just blindly wait until
1350 // it is time for that alarm to go off. We don't want to wake up for any
1351 // other reasons.
1352 mNextWakeup = mNextNonWakeup = mPendingIdleUntil.whenElapsed;
1353 setLocked(ELAPSED_REALTIME_WAKEUP, mNextWakeup);
1354 setLocked(ELAPSED_REALTIME, mNextNonWakeup);
1355 return;
1356 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001357 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
1358 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001359 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001360 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001361 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001362 final Batch firstBatch = mAlarmBatches.get(0);
Christopher Tatec83d3e42015-02-04 13:48:29 -08001363 // always update the kernel alarms, as a backstop against missed wakeups
1364 if (firstWakeup != null) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001365 mNextWakeup = firstWakeup.start;
1366 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001367 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001368 if (firstBatch != firstWakeup) {
1369 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001370 }
1371 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001372 if (mPendingNonWakeupAlarms.size() > 0) {
1373 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
1374 nextNonWakeup = mNextNonWakeupDeliveryTime;
1375 }
1376 }
Christopher Tatec83d3e42015-02-04 13:48:29 -08001377 // always update the kernel alarm, as a backstop against missed wakeups
1378 if (nextNonWakeup != 0) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001379 mNextNonWakeup = nextNonWakeup;
1380 setLocked(ELAPSED_REALTIME, nextNonWakeup);
1381 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001382 }
1383
1384 private void removeLocked(PendingIntent operation) {
1385 boolean didRemove = false;
1386 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1387 Batch b = mAlarmBatches.get(i);
1388 didRemove |= b.remove(operation);
1389 if (b.size() == 0) {
1390 mAlarmBatches.remove(i);
1391 }
1392 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001393 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1394 if (mPendingWhileIdleAlarms.get(i).operation.equals(operation)) {
1395 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1396 mPendingWhileIdleAlarms.remove(i);
1397 }
1398 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001399
1400 if (didRemove) {
1401 if (DEBUG_BATCH) {
1402 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
1403 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001404 boolean restorePending = false;
1405 if (mPendingIdleUntil != null && mPendingIdleUntil.operation.equals(operation)) {
1406 mPendingIdleUntil = null;
1407 restorePending = true;
1408 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001409 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001410 if (restorePending) {
1411 restorePendingWhileIdleAlarmsLocked();
1412 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001413 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001414 }
1415 }
1416
1417 void removeLocked(String packageName) {
1418 boolean didRemove = false;
1419 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1420 Batch b = mAlarmBatches.get(i);
1421 didRemove |= b.remove(packageName);
1422 if (b.size() == 0) {
1423 mAlarmBatches.remove(i);
1424 }
1425 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001426 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1427 if (mPendingWhileIdleAlarms.get(i).operation.getTargetPackage().equals(packageName)) {
1428 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1429 mPendingWhileIdleAlarms.remove(i);
1430 }
1431 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001432
1433 if (didRemove) {
1434 if (DEBUG_BATCH) {
1435 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1436 }
1437 rebatchAllAlarmsLocked(true);
1438 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001439 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001440 }
1441 }
1442
1443 void removeUserLocked(int userHandle) {
1444 boolean didRemove = false;
1445 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1446 Batch b = mAlarmBatches.get(i);
1447 didRemove |= b.remove(userHandle);
1448 if (b.size() == 0) {
1449 mAlarmBatches.remove(i);
1450 }
1451 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001452 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1453 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).operation.getCreatorUid())
1454 == userHandle) {
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(user) 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
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001470 void interactiveStateChangedLocked(boolean interactive) {
1471 if (mInteractive != interactive) {
1472 mInteractive = interactive;
1473 final long nowELAPSED = SystemClock.elapsedRealtime();
1474 if (interactive) {
1475 if (mPendingNonWakeupAlarms.size() > 0) {
1476 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1477 mTotalDelayTime += thisDelayTime;
1478 if (mMaxDelayTime < thisDelayTime) {
1479 mMaxDelayTime = thisDelayTime;
1480 }
1481 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
1482 mPendingNonWakeupAlarms.clear();
1483 }
1484 if (mNonInteractiveStartTime > 0) {
1485 long dur = nowELAPSED - mNonInteractiveStartTime;
1486 if (dur > mNonInteractiveTime) {
1487 mNonInteractiveTime = dur;
1488 }
1489 }
1490 } else {
1491 mNonInteractiveStartTime = nowELAPSED;
1492 }
1493 }
1494 }
1495
Adam Lesinski182f73f2013-12-05 16:48:06 -08001496 boolean lookForPackageLocked(String packageName) {
1497 for (int i = 0; i < mAlarmBatches.size(); i++) {
1498 Batch b = mAlarmBatches.get(i);
1499 if (b.hasPackage(packageName)) {
1500 return true;
1501 }
1502 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001503 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
1504 if (mPendingWhileIdleAlarms.get(i).operation.getTargetPackage().equals(packageName)) {
1505 return true;
1506 }
1507 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001508 return false;
1509 }
1510
1511 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001512 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001513 // The kernel never triggers alarms with negative wakeup times
1514 // so we ensure they are positive.
1515 long alarmSeconds, alarmNanoseconds;
1516 if (when < 0) {
1517 alarmSeconds = 0;
1518 alarmNanoseconds = 0;
1519 } else {
1520 alarmSeconds = when / 1000;
1521 alarmNanoseconds = (when % 1000) * 1000 * 1000;
1522 }
1523
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001524 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001525 } else {
1526 Message msg = Message.obtain();
1527 msg.what = ALARM_EVENT;
1528
1529 mHandler.removeMessages(ALARM_EVENT);
1530 mHandler.sendMessageAtTime(msg, when);
1531 }
1532 }
1533
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001534 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001535 String prefix, String label, long nowRTC, long nowELAPSED, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 for (int i=list.size()-1; i>=0; i--) {
1537 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001538 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1539 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001540 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 }
1542 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001543
1544 private static final String labelForType(int type) {
1545 switch (type) {
1546 case RTC: return "RTC";
1547 case RTC_WAKEUP : return "RTC_WAKEUP";
1548 case ELAPSED_REALTIME : return "ELAPSED";
1549 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
1550 default:
1551 break;
1552 }
1553 return "--unknown--";
1554 }
1555
1556 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001557 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001558 for (int i=list.size()-1; i>=0; i--) {
1559 Alarm a = list.get(i);
1560 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001561 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1562 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001563 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001564 }
1565 }
1566
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001567 private native long init();
1568 private native void close(long nativeData);
1569 private native void set(long nativeData, int type, long seconds, long nanoseconds);
1570 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08001571 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001572 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001574 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001575 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001576 boolean hasWakeup = false;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001577 if (mPendingIdleUntil != null) {
1578 // If we have a pending "idle until" alarm, don't trigger any alarms
1579 // until we are past the idle period.
1580 if (nowELAPSED < mPendingIdleUntil.whenElapsed) {
1581 return false;
1582 }
1583 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001584 // batches are temporally sorted, so we need only pull from the
1585 // start of the list until we either empty it or hit a batch
1586 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07001587 while (mAlarmBatches.size() > 0) {
1588 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001589 if (batch.start > nowELAPSED) {
1590 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001591 break;
1592 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001593
Christopher Tatee0a22b32013-07-11 14:43:13 -07001594 // We will (re)schedule some alarms now; don't let that interfere
1595 // with delivery of this current batch
1596 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001597
Christopher Tatee0a22b32013-07-11 14:43:13 -07001598 final int N = batch.size();
1599 for (int i = 0; i < N; i++) {
1600 Alarm alarm = batch.get(i);
1601 alarm.count = 1;
1602 triggerList.add(alarm);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001603 if (mPendingIdleUntil == alarm) {
1604 mPendingIdleUntil = null;
1605 rebatchAllAlarmsLocked(false);
1606 restorePendingWhileIdleAlarmsLocked();
1607 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001608
1609 // Recurring alarms may have passed several alarm intervals while the
1610 // phone was asleep or off, so pass a trigger count when sending them.
1611 if (alarm.repeatInterval > 0) {
1612 // this adjustment will be zero if we're late by
1613 // less than one full repeat interval
1614 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
1615
1616 // Also schedule its next recurrence
1617 final long delta = alarm.count * alarm.repeatInterval;
1618 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07001619 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07001620 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001621 alarm.repeatInterval, alarm.operation, alarm.flags, true,
Adrian Roosc42a1e12014-07-07 23:35:53 +02001622 alarm.workSource, alarm.alarmClock, alarm.userId);
Christopher Tate864d42e2014-12-02 11:48:53 -08001623 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624
Christopher Tate864d42e2014-12-02 11:48:53 -08001625 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001626 hasWakeup = true;
1627 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001628
1629 // We removed an alarm clock. Let the caller recompute the next alarm clock.
1630 if (alarm.alarmClock != null) {
1631 mNextAlarmClockMayChange = true;
1632 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07001633 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001635
Christopher Tate1590f1e2014-10-02 17:27:57 -07001636 // This is a new alarm delivery set; bump the sequence number to indicate that
1637 // all apps' alarm delivery classes should be recalculated.
1638 mCurrentSeq++;
1639 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001640 Collections.sort(triggerList, mAlarmDispatchComparator);
1641
1642 if (localLOGV) {
1643 for (int i=0; i<triggerList.size(); i++) {
1644 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
1645 }
1646 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001647
1648 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 /**
1652 * This Comparator sorts Alarms into increasing time order.
1653 */
1654 public static class IncreasingTimeOrder implements Comparator<Alarm> {
1655 public int compare(Alarm a1, Alarm a2) {
1656 long when1 = a1.when;
1657 long when2 = a2.when;
1658 if (when1 - when2 > 0) {
1659 return 1;
1660 }
1661 if (when1 - when2 < 0) {
1662 return -1;
1663 }
1664 return 0;
1665 }
1666 }
1667
1668 private static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001669 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001670 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001671 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001672 public final PendingIntent operation;
1673 public final String tag;
1674 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001675 public final int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 public int count;
1677 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07001678 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001679 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001680 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 public long repeatInterval;
Jose Lima235510e2014-08-13 12:50:01 -07001682 public final AlarmManager.AlarmClockInfo alarmClock;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001683 public final int userId;
Christopher Tate1590f1e2014-10-02 17:27:57 -07001684 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001685
Christopher Tate3e04b472013-10-21 17:51:31 -07001686 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001687 long _interval, PendingIntent _op, WorkSource _ws, int _flags,
Jose Lima235510e2014-08-13 12:50:01 -07001688 AlarmManager.AlarmClockInfo _info, int _userId) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001689 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001690 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001691 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
1692 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001693 when = _when;
1694 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07001695 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001696 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001697 repeatInterval = _interval;
1698 operation = _op;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001699 tag = makeTag(_op, _type);
David Christieebe51fc2013-07-26 13:23:29 -07001700 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001701 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001702 alarmClock = _info;
1703 userId = _userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001705
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001706 public static String makeTag(PendingIntent pi, int type) {
1707 return pi.getTag(type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
1708 ? "*walarm*:" : "*alarm*:");
1709 }
1710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001712 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001713 StringBuilder sb = new StringBuilder(128);
1714 sb.append("Alarm{");
1715 sb.append(Integer.toHexString(System.identityHashCode(this)));
1716 sb.append(" type ");
1717 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001718 sb.append(" when ");
1719 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001720 sb.append(" ");
1721 sb.append(operation.getTargetPackage());
1722 sb.append('}');
1723 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 }
1725
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001726 public void dump(PrintWriter pw, String prefix, long nowRTC, long nowELAPSED,
1727 SimpleDateFormat sdf) {
1728 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
1729 pw.print(prefix); pw.print("tag="); pw.println(tag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001730 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001731 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
1732 nowELAPSED, pw);
1733 if (isRtc) {
1734 pw.print(" when="); pw.print(sdf.format(new Date(when)));
1735 } else {
1736 pw.print(" when="); TimeUtils.formatDuration(when, nowELAPSED, pw);
1737 }
1738 pw.println();
1739 pw.print(prefix); pw.print("window="); pw.print(windowLength);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001740 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001741 pw.print(" count="); pw.print(count);
1742 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001743 pw.print(prefix); pw.print("operation="); pw.println(operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001744 }
1745 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001746
Christopher Tatee0a22b32013-07-11 14:43:13 -07001747 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
1748 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07001749 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
1750 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001751 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07001752 break;
1753 }
1754
Christopher Tatee0a22b32013-07-11 14:43:13 -07001755 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07001756 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
1757 Alarm a = b.alarms.get(nextAlarm);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001758 WakeupEvent e = new WakeupEvent(nowRTC,
1759 a.operation.getCreatorUid(),
1760 a.operation.getIntent().getAction());
1761 mRecentWakeups.add(e);
1762 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001763 }
1764 }
1765
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001766 long currentNonWakeupFuzzLocked(long nowELAPSED) {
1767 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
1768 if (timeSinceOn < 5*60*1000) {
1769 // If the screen has been off for 5 minutes, only delay by at most two minutes.
1770 return 2*60*1000;
1771 } else if (timeSinceOn < 30*60*1000) {
1772 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
1773 return 15*60*1000;
1774 } else {
1775 // Otherwise, we will delay by at most an hour.
1776 return 60*60*1000;
1777 }
1778 }
1779
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001780 static long fuzzForDuration(long duration) {
1781 if (duration < 15*60*1000) {
1782 // If the duration until the time is less than 15 minutes, the maximum fuzz
1783 // is the duration.
1784 return duration;
1785 } else if (duration < 90*60*1000) {
1786 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
1787 return 15*60*1000;
1788 } else {
1789 // Otherwise, we will fuzz by at most half an hour.
1790 return 30*60*1000;
1791 }
1792 }
1793
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001794 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
1795 if (mInteractive) {
1796 return false;
1797 }
1798 if (mLastAlarmDeliveryTime <= 0) {
1799 return false;
1800 }
minho.choo649acab2014-12-12 16:13:55 +09001801 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001802 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
1803 // and the next delivery time is in the past, then just deliver them all. This
1804 // avoids bugs where we get stuck in a loop trying to poll for alarms.
1805 return false;
1806 }
1807 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
1808 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
1809 }
1810
1811 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
1812 mLastAlarmDeliveryTime = nowELAPSED;
1813 for (int i=0; i<triggerList.size(); i++) {
1814 Alarm alarm = triggerList.get(i);
1815 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07001816 if (localLOGV) {
1817 Slog.v(TAG, "sending alarm " + alarm);
1818 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001819 alarm.operation.send(getContext(), 0,
1820 mBackgroundIntent.putExtra(
1821 Intent.EXTRA_ALARM_COUNT, alarm.count),
1822 mResultReceiver, mHandler);
1823
1824 // we have an active broadcast so stay awake.
1825 if (mBroadcastRefCount == 0) {
1826 setWakelockWorkSource(alarm.operation, alarm.workSource,
1827 alarm.type, alarm.tag, true);
1828 mWakeLock.acquire();
1829 }
1830 final InFlight inflight = new InFlight(AlarmManagerService.this,
1831 alarm.operation, alarm.workSource, alarm.type, alarm.tag);
1832 mInFlight.add(inflight);
1833 mBroadcastRefCount++;
1834
1835 final BroadcastStats bs = inflight.mBroadcastStats;
1836 bs.count++;
1837 if (bs.nesting == 0) {
1838 bs.nesting = 1;
1839 bs.startTime = nowELAPSED;
1840 } else {
1841 bs.nesting++;
1842 }
1843 final FilterStats fs = inflight.mFilterStats;
1844 fs.count++;
1845 if (fs.nesting == 0) {
1846 fs.nesting = 1;
1847 fs.startTime = nowELAPSED;
1848 } else {
1849 fs.nesting++;
1850 }
1851 if (alarm.type == ELAPSED_REALTIME_WAKEUP
1852 || alarm.type == RTC_WAKEUP) {
1853 bs.numWakeup++;
1854 fs.numWakeup++;
1855 if (alarm.workSource != null && alarm.workSource.size() > 0) {
1856 for (int wi=0; wi<alarm.workSource.size(); wi++) {
1857 ActivityManagerNative.noteWakeupAlarm(
1858 alarm.operation, alarm.workSource.get(wi),
1859 alarm.workSource.getName(wi));
1860 }
1861 } else {
1862 ActivityManagerNative.noteWakeupAlarm(
1863 alarm.operation, -1, null);
1864 }
1865 }
1866 } catch (PendingIntent.CanceledException e) {
1867 if (alarm.repeatInterval > 0) {
1868 // This IntentSender is no longer valid, but this
1869 // is a repeating alarm, so toss the hoser.
1870 removeImpl(alarm.operation);
1871 }
1872 } catch (RuntimeException e) {
1873 Slog.w(TAG, "Failure sending alarm.", e);
1874 }
1875 }
1876 }
1877
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001878 private class AlarmThread extends Thread
1879 {
1880 public AlarmThread()
1881 {
1882 super("AlarmManager");
1883 }
1884
1885 public void run()
1886 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07001887 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
1888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001889 while (true)
1890 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001891 int result = waitForAlarm(mNativeData);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001892
1893 triggerList.clear();
1894
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001895 if ((result & TIME_CHANGED_MASK) != 0) {
Christopher Tate385e4982013-07-23 18:22:29 -07001896 if (DEBUG_BATCH) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001897 Slog.v(TAG, "Time changed notification from kernel; rebatching");
Christopher Tate385e4982013-07-23 18:22:29 -07001898 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001899 removeImpl(mTimeTickSender);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001900 rebatchAllAlarms();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 mClockReceiver.scheduleTimeTickEvent();
Dianne Hackborn998e6082014-09-11 19:13:23 -07001902 synchronized (mLock) {
1903 mNumTimeChanged++;
1904 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001905 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
Dianne Hackborn89ba6752011-01-23 16:51:16 -08001906 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1907 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001908 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 }
1910
1911 synchronized (mLock) {
1912 final long nowRTC = System.currentTimeMillis();
1913 final long nowELAPSED = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001914 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915 TAG, "Checking for alarms... rtc=" + nowRTC
1916 + ", elapsed=" + nowELAPSED);
1917
Christopher Tate18a75f12013-07-01 18:18:59 -07001918 if (WAKEUP_STATS) {
1919 if ((result & IS_WAKEUP_MASK) != 0) {
1920 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
1921 int n = 0;
1922 for (WakeupEvent event : mRecentWakeups) {
1923 if (event.when > newEarliest) break;
1924 n++; // number of now-stale entries at the list head
1925 }
1926 for (int i = 0; i < n; i++) {
1927 mRecentWakeups.remove();
1928 }
1929
Christopher Tatee0a22b32013-07-11 14:43:13 -07001930 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Christopher Tate18a75f12013-07-01 18:18:59 -07001931 }
1932 }
1933
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001934 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
1935 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
1936 // if there are no wakeup alarms and the screen is off, we can
1937 // delay what we have so far until the future.
1938 if (mPendingNonWakeupAlarms.size() == 0) {
1939 mStartCurrentDelayTime = nowELAPSED;
1940 mNextNonWakeupDeliveryTime = nowELAPSED
1941 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001942 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001943 mPendingNonWakeupAlarms.addAll(triggerList);
1944 mNumDelayedAlarms += triggerList.size();
1945 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001946 updateNextAlarmClockLocked();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001947 } else {
1948 // now deliver the alarm intents; if there are pending non-wakeup
1949 // alarms, we need to merge them in to the list. note we don't
1950 // just deliver them first because we generally want non-wakeup
1951 // alarms delivered after wakeup alarms.
1952 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001953 updateNextAlarmClockLocked();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001954 if (mPendingNonWakeupAlarms.size() > 0) {
Christopher Tate1590f1e2014-10-02 17:27:57 -07001955 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001956 triggerList.addAll(mPendingNonWakeupAlarms);
1957 Collections.sort(triggerList, mAlarmDispatchComparator);
1958 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1959 mTotalDelayTime += thisDelayTime;
1960 if (mMaxDelayTime < thisDelayTime) {
1961 mMaxDelayTime = thisDelayTime;
1962 }
1963 mPendingNonWakeupAlarms.clear();
1964 }
1965 deliverAlarmsLocked(triggerList, nowELAPSED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001966 }
1967 }
1968 }
1969 }
1970 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07001971
David Christieebe51fc2013-07-26 13:23:29 -07001972 /**
1973 * Attribute blame for a WakeLock.
1974 * @param pi PendingIntent to attribute blame to if ws is null.
1975 * @param ws WorkSource to attribute blame.
1976 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001977 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
1978 boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07001979 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001980 final boolean unimportant = pi == mTimeTickSender;
1981 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07001982 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001983 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07001984 } else {
1985 mWakeLock.setHistoryTag(null);
1986 }
1987 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07001988 if (ws != null) {
1989 mWakeLock.setWorkSource(ws);
1990 return;
1991 }
1992
Christopher Tatec4a07d12012-04-06 14:19:13 -07001993 final int uid = ActivityManagerNative.getDefault()
1994 .getUidForIntentSender(pi.getTarget());
1995 if (uid >= 0) {
1996 mWakeLock.setWorkSource(new WorkSource(uid));
1997 return;
1998 }
1999 } catch (Exception e) {
2000 }
2001
2002 // Something went wrong; fall back to attributing the lock to the OS
2003 mWakeLock.setWorkSource(null);
2004 }
2005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002006 private class AlarmHandler extends Handler {
2007 public static final int ALARM_EVENT = 1;
2008 public static final int MINUTE_CHANGE_EVENT = 2;
2009 public static final int DATE_CHANGE_EVENT = 3;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002010 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002011
2012 public AlarmHandler() {
2013 }
2014
2015 public void handleMessage(Message msg) {
2016 if (msg.what == ALARM_EVENT) {
2017 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2018 synchronized (mLock) {
2019 final long nowRTC = System.currentTimeMillis();
Christopher Tatee0a22b32013-07-11 14:43:13 -07002020 final long nowELAPSED = SystemClock.elapsedRealtime();
2021 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002022 updateNextAlarmClockLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002023 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002024
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002025 // now trigger the alarms without the lock held
Dianne Hackborn390517b2013-05-30 15:03:32 -07002026 for (int i=0; i<triggerList.size(); i++) {
2027 Alarm alarm = triggerList.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002028 try {
2029 alarm.operation.send();
2030 } catch (PendingIntent.CanceledException e) {
2031 if (alarm.repeatInterval > 0) {
2032 // This IntentSender is no longer valid, but this
2033 // is a repeating alarm, so toss the hoser.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002034 removeImpl(alarm.operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035 }
2036 }
2037 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002038 } else if (msg.what == SEND_NEXT_ALARM_CLOCK_CHANGED) {
2039 sendNextAlarmClockChanged();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002040 }
2041 }
2042 }
2043
2044 class ClockReceiver extends BroadcastReceiver {
2045 public ClockReceiver() {
2046 IntentFilter filter = new IntentFilter();
2047 filter.addAction(Intent.ACTION_TIME_TICK);
2048 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002049 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 }
2051
2052 @Override
2053 public void onReceive(Context context, Intent intent) {
2054 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07002055 if (DEBUG_BATCH) {
2056 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
2057 }
2058 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002059 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
2060 // Since the kernel does not keep track of DST, we need to
2061 // reset the TZ information at the beginning of each day
2062 // based off of the current Zone gmt offset + userspace tracked
2063 // daylight savings information.
2064 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02002065 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002066 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07002067 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002068 }
2069 }
2070
2071 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07002072 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09002073 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07002074
2075 // Schedule this event for the amount of time that it would take to get to
2076 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09002077 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07002078
David Christieebe51fc2013-07-26 13:23:29 -07002079 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002080 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002081 0, mTimeTickSender, AlarmManager.FLAG_STANDALONE, workSource, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002082 }
Christopher Tate385e4982013-07-23 18:22:29 -07002083
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002084 public void scheduleDateChangedEvent() {
2085 Calendar calendar = Calendar.getInstance();
2086 calendar.setTimeInMillis(System.currentTimeMillis());
2087 calendar.set(Calendar.HOUR, 0);
2088 calendar.set(Calendar.MINUTE, 0);
2089 calendar.set(Calendar.SECOND, 0);
2090 calendar.set(Calendar.MILLISECOND, 0);
2091 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07002092
2093 final WorkSource workSource = null; // Let system take blame for date change events.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002094 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender,
2095 AlarmManager.FLAG_STANDALONE, workSource, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002096 }
2097 }
2098
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002099 class InteractiveStateReceiver extends BroadcastReceiver {
2100 public InteractiveStateReceiver() {
2101 IntentFilter filter = new IntentFilter();
2102 filter.addAction(Intent.ACTION_SCREEN_OFF);
2103 filter.addAction(Intent.ACTION_SCREEN_ON);
2104 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
2105 getContext().registerReceiver(this, filter);
2106 }
2107
2108 @Override
2109 public void onReceive(Context context, Intent intent) {
2110 synchronized (mLock) {
2111 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
2112 }
2113 }
2114 }
2115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002116 class UninstallReceiver extends BroadcastReceiver {
2117 public UninstallReceiver() {
2118 IntentFilter filter = new IntentFilter();
2119 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2120 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002121 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002122 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08002123 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002124 // Register for events related to sdcard installation.
2125 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08002126 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002127 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002128 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002129 }
2130
2131 @Override
2132 public void onReceive(Context context, Intent intent) {
2133 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002134 String action = intent.getAction();
2135 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002136 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
2137 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
2138 for (String packageName : pkgList) {
2139 if (lookForPackageLocked(packageName)) {
2140 setResultCode(Activity.RESULT_OK);
2141 return;
2142 }
2143 }
2144 return;
2145 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002146 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002147 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
2148 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
2149 if (userHandle >= 0) {
2150 removeUserLocked(userHandle);
2151 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002152 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08002153 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
2154 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
2155 // This package is being updated; don't kill its alarms.
2156 return;
2157 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002158 Uri data = intent.getData();
2159 if (data != null) {
2160 String pkg = data.getSchemeSpecificPart();
2161 if (pkg != null) {
2162 pkgList = new String[]{pkg};
2163 }
2164 }
2165 }
2166 if (pkgList != null && (pkgList.length > 0)) {
2167 for (String pkg : pkgList) {
2168 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07002169 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002170 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
2171 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
2172 if (uidStats.remove(pkg) != null) {
2173 if (uidStats.size() <= 0) {
2174 mBroadcastStats.removeAt(i);
2175 }
2176 }
2177 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002179 }
2180 }
2181 }
2182 }
2183
2184 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002185 String pkg = pi.getCreatorPackage();
2186 int uid = pi.getCreatorUid();
2187 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
2188 if (uidStats == null) {
2189 uidStats = new ArrayMap<String, BroadcastStats>();
2190 mBroadcastStats.put(uid, uidStats);
2191 }
2192 BroadcastStats bs = uidStats.get(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002193 if (bs == null) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002194 bs = new BroadcastStats(uid, pkg);
2195 uidStats.put(pkg, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002196 }
2197 return bs;
2198 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002200 class ResultReceiver implements PendingIntent.OnFinished {
2201 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
2202 String resultData, Bundle resultExtras) {
2203 synchronized (mLock) {
Dianne Hackborn81038902012-11-26 17:04:09 -08002204 InFlight inflight = null;
2205 for (int i=0; i<mInFlight.size(); i++) {
2206 if (mInFlight.get(i).mPendingIntent == pi) {
2207 inflight = mInFlight.remove(i);
2208 break;
2209 }
2210 }
2211 if (inflight != null) {
2212 final long nowELAPSED = SystemClock.elapsedRealtime();
2213 BroadcastStats bs = inflight.mBroadcastStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002214 bs.nesting--;
2215 if (bs.nesting <= 0) {
2216 bs.nesting = 0;
Dianne Hackborn81038902012-11-26 17:04:09 -08002217 bs.aggregateTime += nowELAPSED - bs.startTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002218 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002219 FilterStats fs = inflight.mFilterStats;
2220 fs.nesting--;
2221 if (fs.nesting <= 0) {
2222 fs.nesting = 0;
2223 fs.aggregateTime += nowELAPSED - fs.startTime;
2224 }
2225 } else {
2226 mLog.w("No in-flight alarm for " + pi + " " + intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002227 }
2228 mBroadcastRefCount--;
2229 if (mBroadcastRefCount == 0) {
2230 mWakeLock.release();
Dianne Hackborn81038902012-11-26 17:04:09 -08002231 if (mInFlight.size() > 0) {
2232 mLog.w("Finished all broadcasts with " + mInFlight.size()
2233 + " remaining inflights");
2234 for (int i=0; i<mInFlight.size(); i++) {
2235 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
2236 }
2237 mInFlight.clear();
2238 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002239 } else {
2240 // the next of our alarms is now in flight. reattribute the wakelock.
Dianne Hackborn81038902012-11-26 17:04:09 -08002241 if (mInFlight.size() > 0) {
David Christieebe51fc2013-07-26 13:23:29 -07002242 InFlight inFlight = mInFlight.get(0);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08002243 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002244 inFlight.mAlarmType, inFlight.mTag, false);
Christopher Tatec4a07d12012-04-06 14:19:13 -07002245 } else {
2246 // should never happen
Dianne Hackborn81038902012-11-26 17:04:09 -08002247 mLog.w("Alarm wakelock still held but sent queue empty");
Christopher Tatec4a07d12012-04-06 14:19:13 -07002248 mWakeLock.setWorkSource(null);
2249 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002250 }
2251 }
2252 }
2253 }
2254}