blob: 742f570ff0128049ed7985314e0ac31ffb4b4fb7 [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;
John Spurlock604a5ee2015-06-01 12:27:22 -040067import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068
Christopher Tatee0a22b32013-07-11 14:43:13 -070069import static android.app.AlarmManager.RTC_WAKEUP;
70import static android.app.AlarmManager.RTC;
71import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
72import static android.app.AlarmManager.ELAPSED_REALTIME;
73
Dianne Hackborn81038902012-11-26 17:04:09 -080074import com.android.internal.util.LocalLog;
75
Adam Lesinski182f73f2013-12-05 16:48:06 -080076class AlarmManagerService extends SystemService {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077 // The threshold for how long an alarm can be late before we print a
78 // warning message. The time duration is in milliseconds.
79 private static final long LATE_ALARM_THRESHOLD = 10 * 1000;
Christopher Tatee0a22b32013-07-11 14:43:13 -070080
Christopher Tate498c6cb2014-11-17 16:09:27 -080081 // Minimum futurity of a new alarm
82 private static final long MIN_FUTURITY = 5 * 1000; // 5 seconds, in millis
83
84 // Minimum alarm recurrence interval
85 private static final long MIN_INTERVAL = 60 * 1000; // one minute, in millis
86
Christopher Tatee0a22b32013-07-11 14:43:13 -070087 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
88 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -080089 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -070090 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -080091 static final int TIME_CHANGED_MASK = 1 << 16;
92 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -080093
Christopher Tatee0a22b32013-07-11 14:43:13 -070094 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -080095 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -080096
Adam Lesinski182f73f2013-12-05 16:48:06 -080097 static final String TAG = "AlarmManager";
98 static final String ClockReceiver_TAG = "ClockReceiver";
99 static final boolean localLOGV = false;
100 static final boolean DEBUG_BATCH = localLOGV || false;
101 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200102 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700103 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800104 static final int ALARM_EVENT = 1;
105 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200106
Adam Lesinski182f73f2013-12-05 16:48:06 -0800107 static final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800109 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110
Adam Lesinski182f73f2013-12-05 16:48:06 -0800111 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700112
Adrian Roosc42a1e12014-07-07 23:35:53 +0200113 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT = new Intent(
114 AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED);
115
Adam Lesinski182f73f2013-12-05 16:48:06 -0800116 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800117
Adam Lesinski182f73f2013-12-05 16:48:06 -0800118 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800119
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800120 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800121 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700122 private long mNextNonWakeup;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800123 int mBroadcastRefCount = 0;
124 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700125 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700126 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<Alarm>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800127 ArrayList<InFlight> mInFlight = new ArrayList<InFlight>();
128 final AlarmHandler mHandler = new AlarmHandler();
129 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700130 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131 private UninstallReceiver mUninstallReceiver;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800132 final ResultReceiver mResultReceiver = new ResultReceiver();
133 PendingIntent mTimeTickSender;
134 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700135 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700136 boolean mInteractive = true;
137 long mNonInteractiveStartTime;
138 long mNonInteractiveTime;
139 long mLastAlarmDeliveryTime;
140 long mStartCurrentDelayTime;
141 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700142 long mLastTimeChangeClockTime;
143 long mLastTimeChangeRealtime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700144 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800145
Jose Lima235510e2014-08-13 12:50:01 -0700146 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
147 new SparseArray<>();
148 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
149 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200150 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
151 new SparseBooleanArray();
152 private boolean mNextAlarmClockMayChange;
153
154 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700155 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
156 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200157
Christopher Tate1590f1e2014-10-02 17:27:57 -0700158 // Alarm delivery ordering bookkeeping
159 static final int PRIO_TICK = 0;
160 static final int PRIO_WAKEUP = 1;
161 static final int PRIO_NORMAL = 2;
162
163 class PriorityClass {
164 int seq;
165 int priority;
166
167 PriorityClass() {
168 seq = mCurrentSeq - 1;
169 priority = PRIO_NORMAL;
170 }
171 }
172
173 final HashMap<String, PriorityClass> mPriorities =
174 new HashMap<String, PriorityClass>();
175 int mCurrentSeq = 0;
176
Christopher Tate18a75f12013-07-01 18:18:59 -0700177 class WakeupEvent {
178 public long when;
179 public int uid;
180 public String action;
181
182 public WakeupEvent(long theTime, int theUid, String theAction) {
183 when = theTime;
184 uid = theUid;
185 action = theAction;
186 }
187 }
188
Adam Lesinski182f73f2013-12-05 16:48:06 -0800189 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
190 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700191
Adrian Roosc42a1e12014-07-07 23:35:53 +0200192 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700193 long start; // These endpoints are always in ELAPSED
194 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700195 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700196
197 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
198
199 Batch() {
200 start = 0;
201 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700202 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700203 }
204
205 Batch(Alarm seed) {
206 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700207 end = seed.maxWhenElapsed;
208 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700209 alarms.add(seed);
210 }
211
212 int size() {
213 return alarms.size();
214 }
215
216 Alarm get(int index) {
217 return alarms.get(index);
218 }
219
220 boolean canHold(long whenElapsed, long maxWhen) {
221 return (end >= whenElapsed) && (start <= maxWhen);
222 }
223
224 boolean add(Alarm alarm) {
225 boolean newStart = false;
226 // narrows the batch if necessary; presumes that canHold(alarm) is true
227 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
228 if (index < 0) {
229 index = 0 - index - 1;
230 }
231 alarms.add(index, alarm);
232 if (DEBUG_BATCH) {
233 Slog.v(TAG, "Adding " + alarm + " to " + this);
234 }
235 if (alarm.whenElapsed > start) {
236 start = alarm.whenElapsed;
237 newStart = true;
238 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700239 if (alarm.maxWhenElapsed < end) {
240 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700241 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700242 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700243
244 if (DEBUG_BATCH) {
245 Slog.v(TAG, " => now " + this);
246 }
247 return newStart;
248 }
249
250 boolean remove(final PendingIntent operation) {
251 boolean didRemove = false;
252 long newStart = 0; // recalculate endpoints as we go
253 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700254 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700255 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700256 Alarm alarm = alarms.get(i);
257 if (alarm.operation.equals(operation)) {
258 alarms.remove(i);
259 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200260 if (alarm.alarmClock != null) {
261 mNextAlarmClockMayChange = true;
262 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700263 } else {
264 if (alarm.whenElapsed > newStart) {
265 newStart = alarm.whenElapsed;
266 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700267 if (alarm.maxWhenElapsed < newEnd) {
268 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700269 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700270 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700271 i++;
272 }
273 }
274 if (didRemove) {
275 // commit the new batch bounds
276 start = newStart;
277 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700278 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700279 }
280 return didRemove;
281 }
282
283 boolean remove(final String packageName) {
284 boolean didRemove = false;
285 long newStart = 0; // recalculate endpoints as we go
286 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700287 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700288 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700289 Alarm alarm = alarms.get(i);
290 if (alarm.operation.getTargetPackage().equals(packageName)) {
291 alarms.remove(i);
292 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200293 if (alarm.alarmClock != null) {
294 mNextAlarmClockMayChange = true;
295 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700296 } else {
297 if (alarm.whenElapsed > newStart) {
298 newStart = alarm.whenElapsed;
299 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700300 if (alarm.maxWhenElapsed < newEnd) {
301 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700302 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700303 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700304 i++;
305 }
306 }
307 if (didRemove) {
308 // commit the new batch bounds
309 start = newStart;
310 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700311 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700312 }
313 return didRemove;
314 }
315
316 boolean remove(final int userHandle) {
317 boolean didRemove = false;
318 long newStart = 0; // recalculate endpoints as we go
319 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700320 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700321 Alarm alarm = alarms.get(i);
322 if (UserHandle.getUserId(alarm.operation.getCreatorUid()) == userHandle) {
323 alarms.remove(i);
324 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200325 if (alarm.alarmClock != null) {
326 mNextAlarmClockMayChange = true;
327 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700328 } else {
329 if (alarm.whenElapsed > newStart) {
330 newStart = alarm.whenElapsed;
331 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700332 if (alarm.maxWhenElapsed < newEnd) {
333 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700334 }
335 i++;
336 }
337 }
338 if (didRemove) {
339 // commit the new batch bounds
340 start = newStart;
341 end = newEnd;
342 }
343 return didRemove;
344 }
345
346 boolean hasPackage(final String packageName) {
347 final int N = alarms.size();
348 for (int i = 0; i < N; i++) {
349 Alarm a = alarms.get(i);
350 if (a.operation.getTargetPackage().equals(packageName)) {
351 return true;
352 }
353 }
354 return false;
355 }
356
357 boolean hasWakeups() {
358 final int N = alarms.size();
359 for (int i = 0; i < N; i++) {
360 Alarm a = alarms.get(i);
361 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
362 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
363 return true;
364 }
365 }
366 return false;
367 }
368
369 @Override
370 public String toString() {
371 StringBuilder b = new StringBuilder(40);
372 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
373 b.append(" num="); b.append(size());
374 b.append(" start="); b.append(start);
375 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700376 if (flags != 0) {
377 b.append(" flgs=0x");
378 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700379 }
380 b.append('}');
381 return b.toString();
382 }
383 }
384
385 static class BatchTimeOrder implements Comparator<Batch> {
386 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800387 long when1 = b1.start;
388 long when2 = b2.start;
389 if (when1 - when2 > 0) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700390 return 1;
391 }
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800392 if (when1 - when2 < 0) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700393 return -1;
394 }
395 return 0;
396 }
397 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800398
399 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
400 @Override
401 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700402 // priority class trumps everything. TICK < WAKEUP < NORMAL
403 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
404 return -1;
405 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
406 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800407 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700408
409 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800410 if (lhs.whenElapsed < rhs.whenElapsed) {
411 return -1;
412 } else if (lhs.whenElapsed > rhs.whenElapsed) {
413 return 1;
414 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700415
416 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800417 return 0;
418 }
419 };
420
Christopher Tate1590f1e2014-10-02 17:27:57 -0700421 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
422 final int N = alarms.size();
423 for (int i = 0; i < N; i++) {
424 Alarm a = alarms.get(i);
425
426 final int alarmPrio;
427 if (Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
428 alarmPrio = PRIO_TICK;
429 } else if (a.wakeup) {
430 alarmPrio = PRIO_WAKEUP;
431 } else {
432 alarmPrio = PRIO_NORMAL;
433 }
434
435 PriorityClass packagePrio = a.priorityClass;
436 if (packagePrio == null) packagePrio = mPriorities.get(a.operation.getCreatorPackage());
437 if (packagePrio == null) {
438 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
439 mPriorities.put(a.operation.getCreatorPackage(), packagePrio);
440 }
441 a.priorityClass = packagePrio;
442
443 if (packagePrio.seq != mCurrentSeq) {
444 // first alarm we've seen in the current delivery generation from this package
445 packagePrio.priority = alarmPrio;
446 packagePrio.seq = mCurrentSeq;
447 } else {
448 // Multiple alarms from this package being delivered in this generation;
449 // bump the package's delivery class if it's warranted.
450 // TICK < WAKEUP < NORMAL
451 if (alarmPrio < packagePrio.priority) {
452 packagePrio.priority = alarmPrio;
453 }
454 }
455 }
456 }
457
Christopher Tatee0a22b32013-07-11 14:43:13 -0700458 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800459 static final long MIN_FUZZABLE_INTERVAL = 10000;
460 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700461 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
462
463 // set to null if in idle mode; while in this mode, any alarms we don't want
464 // to run during this time are placed in mPendingWhileIdleAlarms
465 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700466 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700467 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700468
Jeff Brownb880d882014-02-10 19:47:07 -0800469 public AlarmManagerService(Context context) {
470 super(context);
471 }
472
Christopher Tatee0a22b32013-07-11 14:43:13 -0700473 static long convertToElapsed(long when, int type) {
474 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
475 if (isRtc) {
476 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
477 }
478 return when;
479 }
480
481 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
482 // calculate the end of our nominal delivery window for the alarm.
483 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
484 // Current heuristic: batchable window is 75% of either the recurrence interval
485 // [for a periodic alarm] or of the time from now to the desired delivery time,
486 // with a minimum delay/interval of 10 seconds, under which we will simply not
487 // defer the alarm.
488 long futurity = (interval == 0)
489 ? (triggerAtTime - now)
490 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700491 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700492 futurity = 0;
493 }
494 return triggerAtTime + (long)(.75 * futurity);
495 }
496
497 // returns true if the batch was added at the head
498 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
499 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
500 if (index < 0) {
501 index = 0 - index - 1;
502 }
503 list.add(index, newBatch);
504 return (index == 0);
505 }
506
Christopher Tate385e4982013-07-23 18:22:29 -0700507 // Return the index of the matching batch, or -1 if none found.
508 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700509 final int N = mAlarmBatches.size();
510 for (int i = 0; i < N; i++) {
511 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700512 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700513 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700514 }
515 }
Christopher Tate385e4982013-07-23 18:22:29 -0700516 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700517 }
518
519 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
520 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700521 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700522 rebatchAllAlarmsLocked(true);
523 }
524 }
525
526 void rebatchAllAlarmsLocked(boolean doValidate) {
527 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
528 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700529 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700530 final long nowElapsed = SystemClock.elapsedRealtime();
531 final int oldBatches = oldSet.size();
532 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
533 Batch batch = oldSet.get(batchNum);
534 final int N = batch.size();
535 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700536 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700537 }
538 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700539 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
540 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
541 + " to " + mPendingIdleUntil);
542 if (mPendingIdleUntil == null) {
543 // Somehow we lost this... we need to restore all of the pending alarms.
544 restorePendingWhileIdleAlarmsLocked();
545 }
546 }
547 rescheduleKernelAlarmsLocked();
548 updateNextAlarmClockLocked();
549 }
550
551 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
552 a.when = a.origWhen;
553 long whenElapsed = convertToElapsed(a.when, a.type);
554 final long maxElapsed;
555 if (a.whenElapsed == a.maxWhenElapsed) {
556 // Exact
557 maxElapsed = whenElapsed;
558 } else {
559 // Not exact. Preserve any explicit window, otherwise recalculate
560 // the window based on the alarm's new futurity. Note that this
561 // reflects a policy of preferring timely to deferred delivery.
562 maxElapsed = (a.windowLength > 0)
563 ? (whenElapsed + a.windowLength)
564 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
565 }
566 a.whenElapsed = whenElapsed;
567 a.maxWhenElapsed = maxElapsed;
568 setImplLocked(a, true, doValidate);
569 }
570
571 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackborn35d54032015-04-23 10:30:43 -0700572 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700573 if (mPendingWhileIdleAlarms.size() > 0) {
574 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
575 mPendingWhileIdleAlarms = new ArrayList<>();
576 final long nowElapsed = SystemClock.elapsedRealtime();
577 for (int i=alarms.size() - 1; i >= 0; i--) {
578 Alarm a = alarms.get(i);
579 reAddAlarmLocked(a, nowElapsed, false);
580 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700581 }
Dianne Hackborn35d54032015-04-23 10:30:43 -0700582
583 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700584 rescheduleKernelAlarmsLocked();
585 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -0700586
587 // And send a TIME_TICK right now, since it is important to get the UI updated.
588 try {
589 mTimeTickSender.send();
590 } catch (PendingIntent.CanceledException e) {
591 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700592 }
593
Adam Lesinski182f73f2013-12-05 16:48:06 -0800594 static final class InFlight extends Intent {
Dianne Hackborn81038902012-11-26 17:04:09 -0800595 final PendingIntent mPendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700596 final WorkSource mWorkSource;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700597 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800598 final BroadcastStats mBroadcastStats;
599 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800600 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800601
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800602 InFlight(AlarmManagerService service, PendingIntent pendingIntent, WorkSource workSource,
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700603 int alarmType, String tag, long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800604 mPendingIntent = pendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700605 mWorkSource = workSource;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700606 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800607 mBroadcastStats = service.getStatsLocked(pendingIntent);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700608 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -0800609 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700610 fs = new FilterStats(mBroadcastStats, mTag);
611 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -0800612 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700613 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -0800614 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800615 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800616 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800617 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800618
Adam Lesinski182f73f2013-12-05 16:48:06 -0800619 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -0800620 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700621 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800622
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700623 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800625 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 int numWakeup;
627 long startTime;
628 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -0800629
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700630 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800631 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700632 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800633 }
634 }
635
Adam Lesinski182f73f2013-12-05 16:48:06 -0800636 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800637 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800638 final String mPackageName;
639
640 long aggregateTime;
641 int count;
642 int numWakeup;
643 long startTime;
644 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700645 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -0800646
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800647 BroadcastStats(int uid, String packageName) {
648 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800649 mPackageName = packageName;
650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 }
652
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800653 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
654 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700655
656 int mNumDelayedAlarms = 0;
657 long mTotalDelayTime = 0;
658 long mMaxDelayTime = 0;
659
Adam Lesinski182f73f2013-12-05 16:48:06 -0800660 @Override
661 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800662 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800663 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800664
665 // We have to set current TimeZone info to kernel
666 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -0800667 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800668
Adam Lesinski182f73f2013-12-05 16:48:06 -0800669 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800670 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800671
Adam Lesinski182f73f2013-12-05 16:48:06 -0800672 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700674 Intent.FLAG_RECEIVER_REGISTERED_ONLY
675 | Intent.FLAG_RECEIVER_FOREGROUND), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700676 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800677 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
678 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800679 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700680 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681
682 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -0800683 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 mClockReceiver.scheduleTimeTickEvent();
685 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700686 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687 mUninstallReceiver = new UninstallReceiver();
688
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800689 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800690 AlarmThread waitThread = new AlarmThread();
691 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800693 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800695
696 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800698
699 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 protected void finalize() throws Throwable {
701 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800702 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 } finally {
704 super.finalize();
705 }
706 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700707
Adam Lesinski182f73f2013-12-05 16:48:06 -0800708 void setTimeZoneImpl(String tz) {
709 if (TextUtils.isEmpty(tz)) {
710 return;
David Christieebe51fc2013-07-26 13:23:29 -0700711 }
712
Adam Lesinski182f73f2013-12-05 16:48:06 -0800713 TimeZone zone = TimeZone.getTimeZone(tz);
714 // Prevent reentrant calls from stepping on each other when writing
715 // the time zone property
716 boolean timeZoneWasChanged = false;
717 synchronized (this) {
718 String current = SystemProperties.get(TIMEZONE_PROPERTY);
719 if (current == null || !current.equals(zone.getID())) {
720 if (localLOGV) {
721 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
722 }
723 timeZoneWasChanged = true;
724 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
725 }
726
727 // Update the kernel timezone information
728 // Kernel tracks time offsets as 'minutes west of GMT'
729 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800730 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -0800731 }
732
733 TimeZone.setDefault(null);
734
735 if (timeZoneWasChanged) {
736 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
737 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
738 intent.putExtra("time-zone", zone.getID());
739 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700742
Adam Lesinski182f73f2013-12-05 16:48:06 -0800743 void removeImpl(PendingIntent operation) {
744 if (operation == null) {
745 return;
746 }
747 synchronized (mLock) {
748 removeLocked(operation);
749 }
750 }
751
752 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700753 PendingIntent operation, int flags, WorkSource workSource,
Jose Lima235510e2014-08-13 12:50:01 -0700754 AlarmManager.AlarmClockInfo alarmClock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 if (operation == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800756 Slog.w(TAG, "set/setRepeating ignored because there is no intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800757 return;
758 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700759
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700760 // Sanity check the window length. This will catch people mistakenly
761 // trying to pass an end-of-window timestamp rather than a duration.
762 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
763 Slog.w(TAG, "Window length " + windowLength
764 + "ms suspiciously long; limiting to 1 hour");
765 windowLength = AlarmManager.INTERVAL_HOUR;
766 }
767
Christopher Tate498c6cb2014-11-17 16:09:27 -0800768 // Sanity check the recurrence interval. This will catch people who supply
769 // seconds when the API expects milliseconds.
770 if (interval > 0 && interval < MIN_INTERVAL) {
771 Slog.w(TAG, "Suspiciously short interval " + interval
772 + " millis; expanding to " + (int)(MIN_INTERVAL/1000)
773 + " seconds");
774 interval = MIN_INTERVAL;
775 }
776
Christopher Tatee0a22b32013-07-11 14:43:13 -0700777 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
778 throw new IllegalArgumentException("Invalid alarm type " + type);
779 }
780
Christopher Tate5f221e82013-07-30 17:13:15 -0700781 if (triggerAtTime < 0) {
782 final long who = Binder.getCallingUid();
783 final long what = Binder.getCallingPid();
784 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + who
785 + " pid=" + what);
786 triggerAtTime = 0;
787 }
788
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700789 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -0800790 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
791 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
792 final long minTrigger = nowElapsed + MIN_FUTURITY;
793 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
794
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700795 final long maxElapsed;
796 if (windowLength == AlarmManager.WINDOW_EXACT) {
797 maxElapsed = triggerElapsed;
798 } else if (windowLength < 0) {
799 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
800 } else {
801 maxElapsed = triggerElapsed + windowLength;
802 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700803
Adrian Roosc42a1e12014-07-07 23:35:53 +0200804 final int userId = UserHandle.getCallingUserId();
805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700807 if (DEBUG_BATCH) {
808 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700809 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -0700810 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700811 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 }
Christopher Tate3e04b472013-10-21 17:51:31 -0700813 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700814 interval, operation, flags, true, workSource, alarmClock, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 }
816 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817
Christopher Tate3e04b472013-10-21 17:51:31 -0700818 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700819 long maxWhen, long interval, PendingIntent operation, int flags,
Jose Lima235510e2014-08-13 12:50:01 -0700820 boolean doValidate, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
821 int userId) {
Christopher Tate3e04b472013-10-21 17:51:31 -0700822 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700823 operation, workSource, flags, alarmClock, userId);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700824 removeLocked(operation);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700825 setImplLocked(a, false, doValidate);
826 }
Christopher Tateb8849c12011-02-08 13:39:01 -0800827
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700828 private void updateNextWakeFromIdleFuzzLocked() {
829 if (mNextWakeFromIdle != null) {
830
831 }
832 }
833
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700834 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
835 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700836 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700837 // The caller has given the time they want this to happen at, however we need
838 // to pull that earlier if there are existing alarms that have requested to
839 // bring us out of idle.
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700840 if (mNextWakeFromIdle != null) {
841 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700842 }
843 // Add fuzz to make the alarm go off some time before the actual desired time.
844 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700845 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700846 if (fuzz > 0) {
847 if (mRandom == null) {
848 mRandom = new Random();
849 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700850 final int delta = mRandom.nextInt(fuzz);
851 a.whenElapsed -= delta;
852 if (false) {
853 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
854 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
855 Slog.d(TAG, "Applied fuzz: " + fuzz);
856 Slog.d(TAG, "Final delta: " + delta);
857 Slog.d(TAG, "Final when: " + a.whenElapsed);
858 }
859 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700860 }
861
862 } else if (mPendingIdleUntil != null) {
863 // We currently have an idle until alarm scheduled; if the new alarm has
864 // not explicitly stated it wants to run while idle, then put it on hold.
865 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE|AlarmManager.FLAG_WAKE_FROM_IDLE))
866 == 0) {
867 mPendingWhileIdleAlarms.add(a);
868 return;
869 }
870 }
871
872 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
873 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -0700874 if (whichBatch < 0) {
875 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -0700876 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 } else {
Christopher Tate385e4982013-07-23 18:22:29 -0700878 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -0700879 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700880 // The start time of this batch advanced, so batch ordering may
881 // have just been broken. Move it to where it now belongs.
882 mAlarmBatches.remove(whichBatch);
883 addBatchLocked(mAlarmBatches, batch);
884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 }
886
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700887 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +0200888 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200889 }
890
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700891 boolean needRebatch = false;
892
893 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
894 mPendingIdleUntil = a;
895 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700896 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
897 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
898 mNextWakeFromIdle = a;
899 // If this wake from idle is earlier than whatever was previously scheduled,
900 // and we are currently idling, then we need to rebatch alarms in case the idle
901 // until time needs to be updated.
902 if (mPendingIdleUntil != null) {
903 needRebatch = true;
904 }
905 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700906 }
907
908 if (!rebatching) {
909 if (DEBUG_VALIDATE) {
910 if (doValidate && !validateConsistencyLocked()) {
911 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
912 + " when(hex)=" + Long.toHexString(a.when)
913 + " whenElapsed=" + a.whenElapsed
914 + " maxWhenElapsed=" + a.maxWhenElapsed
915 + " interval=" + a.repeatInterval + " op=" + a.operation
916 + " flags=0x" + Integer.toHexString(a.flags));
917 rebatchAllAlarmsLocked(false);
918 needRebatch = false;
919 }
920 }
921
922 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700923 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -0700924 }
Christopher Tate4cb338d2013-07-26 13:11:31 -0700925
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700926 rescheduleKernelAlarmsLocked();
927 updateNextAlarmClockLocked();
928 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700929 }
930
Adam Lesinski182f73f2013-12-05 16:48:06 -0800931 private final IBinder mService = new IAlarmManager.Stub() {
932 @Override
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700933 public void set(int type, long triggerAtTime, long windowLength, long interval, int flags,
Jose Lima235510e2014-08-13 12:50:01 -0700934 PendingIntent operation, WorkSource workSource,
935 AlarmManager.AlarmClockInfo alarmClock) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800936 if (workSource != null) {
937 getContext().enforceCallingPermission(
938 android.Manifest.permission.UPDATE_DEVICE_STATS,
939 "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -0700940 }
941
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700942 if (windowLength == AlarmManager.WINDOW_EXACT) {
943 flags |= AlarmManager.FLAG_STANDALONE;
944 }
945 if (alarmClock != null) {
946 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
947 }
948 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
949 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE;
950 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800951 setImpl(type, triggerAtTime, windowLength, interval, operation,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700952 flags, workSource, alarmClock);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800953 }
Christopher Tate89779822012-08-31 14:40:03 -0700954
Adam Lesinski182f73f2013-12-05 16:48:06 -0800955 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -0800956 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800957 getContext().enforceCallingOrSelfPermission(
958 "android.permission.SET_TIME",
959 "setTime");
960
Greg Hackmann0cab8962014-02-21 16:35:52 -0800961 if (mNativeData == 0) {
962 Slog.w(TAG, "Not setting time since no alarm driver is available.");
963 return false;
Christopher Tate89779822012-08-31 14:40:03 -0700964 }
Greg Hackmann0cab8962014-02-21 16:35:52 -0800965
966 synchronized (mLock) {
967 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800970
971 @Override
972 public void setTimeZone(String tz) {
973 getContext().enforceCallingOrSelfPermission(
974 "android.permission.SET_TIME_ZONE",
975 "setTimeZone");
976
977 final long oldId = Binder.clearCallingIdentity();
978 try {
979 setTimeZoneImpl(tz);
980 } finally {
981 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 }
983 }
Christopher Tate4cb338d2013-07-26 13:11:31 -0700984
Adam Lesinski182f73f2013-12-05 16:48:06 -0800985 @Override
986 public void remove(PendingIntent operation) {
987 removeImpl(operation);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700988
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 }
Christopher Tate4cb338d2013-07-26 13:11:31 -0700990
Adam Lesinski182f73f2013-12-05 16:48:06 -0800991 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700992 public long getNextWakeFromIdleTime() {
993 return getNextWakeFromIdleTimeImpl();
994 }
995
996 @Override
Jose Lima235510e2014-08-13 12:50:01 -0700997 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +0200998 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
999 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1000 "getNextAlarmClock", null);
1001
1002 return getNextAlarmClockImpl(userId);
1003 }
1004
1005 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001006 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1007 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1008 != PackageManager.PERMISSION_GRANTED) {
1009 pw.println("Permission Denial: can't dump AlarmManager from from pid="
1010 + Binder.getCallingPid()
1011 + ", uid=" + Binder.getCallingUid());
1012 return;
Christopher Tate4cb338d2013-07-26 13:11:31 -07001013 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001014
Adam Lesinski182f73f2013-12-05 16:48:06 -08001015 dumpImpl(pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001016 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001017 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001018
Adam Lesinski182f73f2013-12-05 16:48:06 -08001019 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 synchronized (mLock) {
1021 pw.println("Current Alarm Manager state:");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001022 final long nowRTC = System.currentTimeMillis();
1023 final long nowELAPSED = SystemClock.elapsedRealtime();
1024 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1025
1026 pw.print("nowRTC="); pw.print(nowRTC);
1027 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001028 pw.print(" nowELAPSED="); TimeUtils.formatDuration(nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001029 pw.println();
Dianne Hackbornc3527222015-05-13 14:03:20 -07001030 pw.print("mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
1031 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
1032 pw.print("mLastTimeChangeRealtime=");
1033 TimeUtils.formatDuration(mLastTimeChangeRealtime, pw);
1034 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001035 if (!mInteractive) {
1036 pw.print("Time since non-interactive: ");
1037 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1038 pw.println();
1039 pw.print("Max wakeup delay: ");
1040 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1041 pw.println();
1042 pw.print("Time since last dispatch: ");
1043 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1044 pw.println();
1045 pw.print("Next non-wakeup delivery time: ");
1046 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1047 pw.println();
1048 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001049
1050 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1051 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001052 pw.print("Next non-wakeup alarm: ");
1053 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001054 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001055 pw.print("Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001056 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackborn998e6082014-09-11 19:13:23 -07001057 pw.print("Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001058
John Spurlock604a5ee2015-06-01 12:27:22 -04001059 pw.println();
1060 pw.println("Next alarm clock information: ");
1061 final TreeSet<Integer> users = new TreeSet<>();
1062 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1063 users.add(mNextAlarmClockForUser.keyAt(i));
1064 }
1065 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1066 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1067 }
1068 for (int user : users) {
1069 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1070 final long time = next != null ? next.getTriggerTime() : 0;
1071 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
1072 pw.print(" user:"); pw.print(user);
1073 pw.print(" pendingSend:"); pw.print(pendingSend);
1074 pw.print(" time:"); pw.print(time);
1075 if (time > 0) {
1076 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1077 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1078 }
1079 pw.println();
1080 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001081 if (mAlarmBatches.size() > 0) {
1082 pw.println();
1083 pw.print("Pending alarm batches: ");
1084 pw.println(mAlarmBatches.size());
1085 for (Batch b : mAlarmBatches) {
1086 pw.print(b); pw.println(':');
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001087 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001088 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001090 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001091 pw.println();
1092 pw.println("Idle mode state:");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001093 pw.print(" Idling until: ");
1094 if (mPendingIdleUntil != null) {
1095 pw.println(mPendingIdleUntil);
1096 mPendingIdleUntil.dump(pw, " ", nowRTC, nowELAPSED, sdf);
1097 } else {
1098 pw.println("null");
1099 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001100 pw.println(" Pending alarms:");
1101 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
1102 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001103 if (mNextWakeFromIdle != null) {
1104 pw.println();
1105 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
1106 mNextWakeFromIdle.dump(pw, " ", nowRTC, nowELAPSED, sdf);
1107 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001108
1109 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001110 pw.print("Past-due non-wakeup alarms: ");
1111 if (mPendingNonWakeupAlarms.size() > 0) {
1112 pw.println(mPendingNonWakeupAlarms.size());
1113 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
1114 } else {
1115 pw.println("(none)");
1116 }
1117 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
1118 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1119 pw.println();
1120 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
1121 pw.print(", max non-interactive time: ");
1122 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1123 pw.println();
1124
1125 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001126 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001127 pw.println();
1128
1129 if (mLog.dump(pw, " Recent problems", " ")) {
1130 pw.println();
1131 }
1132
1133 final FilterStats[] topFilters = new FilterStats[10];
1134 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1135 @Override
1136 public int compare(FilterStats lhs, FilterStats rhs) {
1137 if (lhs.aggregateTime < rhs.aggregateTime) {
1138 return 1;
1139 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1140 return -1;
1141 }
1142 return 0;
1143 }
1144 };
1145 int len = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001146 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1147 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1148 for (int ip=0; ip<uidStats.size(); ip++) {
1149 BroadcastStats bs = uidStats.valueAt(ip);
1150 for (int is=0; is<bs.filterStats.size(); is++) {
1151 FilterStats fs = bs.filterStats.valueAt(is);
1152 int pos = len > 0
1153 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1154 if (pos < 0) {
1155 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001156 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001157 if (pos < topFilters.length) {
1158 int copylen = topFilters.length - pos - 1;
1159 if (copylen > 0) {
1160 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1161 }
1162 topFilters[pos] = fs;
1163 if (len < topFilters.length) {
1164 len++;
1165 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001166 }
1167 }
1168 }
1169 }
1170 if (len > 0) {
1171 pw.println(" Top Alarms:");
1172 for (int i=0; i<len; i++) {
1173 FilterStats fs = topFilters[i];
1174 pw.print(" ");
1175 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1176 TimeUtils.formatDuration(fs.aggregateTime, pw);
1177 pw.print(" running, "); pw.print(fs.numWakeup);
1178 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001179 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1180 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001181 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001182 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001183 pw.println();
1184 }
1185 }
1186
1187 pw.println(" ");
1188 pw.println(" Alarm Stats:");
1189 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001190 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1191 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1192 for (int ip=0; ip<uidStats.size(); ip++) {
1193 BroadcastStats bs = uidStats.valueAt(ip);
1194 pw.print(" ");
1195 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1196 UserHandle.formatUid(pw, bs.mUid);
1197 pw.print(":");
1198 pw.print(bs.mPackageName);
1199 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1200 pw.print(" running, "); pw.print(bs.numWakeup);
1201 pw.println(" wakeups:");
1202 tmpFilters.clear();
1203 for (int is=0; is<bs.filterStats.size(); is++) {
1204 tmpFilters.add(bs.filterStats.valueAt(is));
1205 }
1206 Collections.sort(tmpFilters, comparator);
1207 for (int i=0; i<tmpFilters.size(); i++) {
1208 FilterStats fs = tmpFilters.get(i);
1209 pw.print(" ");
1210 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1211 TimeUtils.formatDuration(fs.aggregateTime, pw);
1212 pw.print(" "); pw.print(fs.numWakeup);
1213 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001214 pw.print(" alarms, last ");
1215 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1216 pw.println(":");
1217 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001218 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001219 pw.println();
1220 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001221 }
1222 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001223
1224 if (WAKEUP_STATS) {
1225 pw.println();
1226 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001227 long last = -1;
1228 for (WakeupEvent event : mRecentWakeups) {
1229 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1230 pw.print('|');
1231 if (last < 0) {
1232 pw.print('0');
1233 } else {
1234 pw.print(event.when - last);
1235 }
1236 last = event.when;
1237 pw.print('|'); pw.print(event.uid);
1238 pw.print('|'); pw.print(event.action);
1239 pw.println();
1240 }
1241 pw.println();
1242 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001243 }
1244 }
1245
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001246 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001247 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
1248 PrintWriter pw = new PrintWriter(bs);
1249 final long nowRTC = System.currentTimeMillis();
1250 final long nowELAPSED = SystemClock.elapsedRealtime();
1251 final int NZ = mAlarmBatches.size();
1252 for (int iz = 0; iz < NZ; iz++) {
1253 Batch bz = mAlarmBatches.get(iz);
1254 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001255 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001256 pw.flush();
1257 Slog.v(TAG, bs.toString());
1258 bs.reset();
1259 }
1260 }
1261
1262 private boolean validateConsistencyLocked() {
1263 if (DEBUG_VALIDATE) {
1264 long lastTime = Long.MIN_VALUE;
1265 final int N = mAlarmBatches.size();
1266 for (int i = 0; i < N; i++) {
1267 Batch b = mAlarmBatches.get(i);
1268 if (b.start >= lastTime) {
1269 // duplicate start times are okay because of standalone batches
1270 lastTime = b.start;
1271 } else {
1272 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001273 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1274 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001275 return false;
1276 }
1277 }
1278 }
1279 return true;
1280 }
1281
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001282 private Batch findFirstWakeupBatchLocked() {
1283 final int N = mAlarmBatches.size();
1284 for (int i = 0; i < N; i++) {
1285 Batch b = mAlarmBatches.get(i);
1286 if (b.hasWakeups()) {
1287 return b;
1288 }
1289 }
1290 return null;
1291 }
1292
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001293 long getNextWakeFromIdleTimeImpl() {
1294 synchronized (mLock) {
1295 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
1296 }
1297 }
1298
1299 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001300 synchronized (mLock) {
1301 return mNextAlarmClockForUser.get(userId);
1302 }
1303 }
1304
1305 /**
1306 * Recomputes the next alarm clock for all users.
1307 */
1308 private void updateNextAlarmClockLocked() {
1309 if (!mNextAlarmClockMayChange) {
1310 return;
1311 }
1312 mNextAlarmClockMayChange = false;
1313
Jose Lima235510e2014-08-13 12:50:01 -07001314 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001315 nextForUser.clear();
1316
1317 final int N = mAlarmBatches.size();
1318 for (int i = 0; i < N; i++) {
1319 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
1320 final int M = alarms.size();
1321
1322 for (int j = 0; j < M; j++) {
1323 Alarm a = alarms.get(j);
1324 if (a.alarmClock != null) {
1325 final int userId = a.userId;
1326
1327 if (DEBUG_ALARM_CLOCK) {
1328 Log.v(TAG, "Found AlarmClockInfo at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001329 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02001330 " for user " + userId);
1331 }
1332
1333 // Alarms and batches are sorted by time, no need to compare times here.
1334 if (nextForUser.get(userId) == null) {
1335 nextForUser.put(userId, a.alarmClock);
1336 }
1337 }
1338 }
1339 }
1340
1341 // Update mNextAlarmForUser with new values.
1342 final int NN = nextForUser.size();
1343 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07001344 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001345 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001346 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001347 if (!newAlarm.equals(currentAlarm)) {
1348 updateNextAlarmInfoForUserLocked(userId, newAlarm);
1349 }
1350 }
1351
1352 // Remove users without any alarm clocks scheduled.
1353 final int NNN = mNextAlarmClockForUser.size();
1354 for (int i = NNN - 1; i >= 0; i--) {
1355 int userId = mNextAlarmClockForUser.keyAt(i);
1356 if (nextForUser.get(userId) == null) {
1357 updateNextAlarmInfoForUserLocked(userId, null);
1358 }
1359 }
1360 }
1361
Jose Lima235510e2014-08-13 12:50:01 -07001362 private void updateNextAlarmInfoForUserLocked(int userId,
1363 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001364 if (alarmClock != null) {
1365 if (DEBUG_ALARM_CLOCK) {
1366 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001367 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02001368 }
1369 mNextAlarmClockForUser.put(userId, alarmClock);
1370 } else {
1371 if (DEBUG_ALARM_CLOCK) {
1372 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
1373 }
1374 mNextAlarmClockForUser.remove(userId);
1375 }
1376
1377 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
1378 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1379 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1380 }
1381
1382 /**
1383 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
1384 * for which alarm clocks have changed since the last call to this.
1385 *
1386 * Do not call with a lock held. Only call from mHandler's thread.
1387 *
1388 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
1389 */
1390 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07001391 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001392 pendingUsers.clear();
1393
1394 synchronized (mLock) {
1395 final int N = mPendingSendNextAlarmClockChangedForUser.size();
1396 for (int i = 0; i < N; i++) {
1397 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
1398 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
1399 }
1400 mPendingSendNextAlarmClockChangedForUser.clear();
1401 }
1402
1403 final int N = pendingUsers.size();
1404 for (int i = 0; i < N; i++) {
1405 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001406 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001407 Settings.System.putStringForUser(getContext().getContentResolver(),
1408 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01001409 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02001410 userId);
1411
1412 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
1413 new UserHandle(userId));
1414 }
1415 }
1416
1417 /**
1418 * Formats an alarm like platform/packages/apps/DeskClock used to.
1419 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01001420 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
1421 int userId) {
1422 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02001423 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
1424 return (info == null) ? "" :
1425 DateFormat.format(pattern, info.getTriggerTime()).toString();
1426 }
1427
Adam Lesinski182f73f2013-12-05 16:48:06 -08001428 void rescheduleKernelAlarmsLocked() {
1429 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
1430 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001431 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001432 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001433 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001434 final Batch firstBatch = mAlarmBatches.get(0);
Christopher Tatec83d3e42015-02-04 13:48:29 -08001435 // always update the kernel alarms, as a backstop against missed wakeups
1436 if (firstWakeup != null) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001437 mNextWakeup = firstWakeup.start;
1438 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001439 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001440 if (firstBatch != firstWakeup) {
1441 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001442 }
1443 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001444 if (mPendingNonWakeupAlarms.size() > 0) {
1445 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
1446 nextNonWakeup = mNextNonWakeupDeliveryTime;
1447 }
1448 }
Christopher Tatec83d3e42015-02-04 13:48:29 -08001449 // always update the kernel alarm, as a backstop against missed wakeups
1450 if (nextNonWakeup != 0) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001451 mNextNonWakeup = nextNonWakeup;
1452 setLocked(ELAPSED_REALTIME, nextNonWakeup);
1453 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001454 }
1455
1456 private void removeLocked(PendingIntent operation) {
1457 boolean didRemove = false;
1458 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1459 Batch b = mAlarmBatches.get(i);
1460 didRemove |= b.remove(operation);
1461 if (b.size() == 0) {
1462 mAlarmBatches.remove(i);
1463 }
1464 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001465 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1466 if (mPendingWhileIdleAlarms.get(i).operation.equals(operation)) {
1467 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1468 mPendingWhileIdleAlarms.remove(i);
1469 }
1470 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001471
1472 if (didRemove) {
1473 if (DEBUG_BATCH) {
1474 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
1475 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001476 boolean restorePending = false;
1477 if (mPendingIdleUntil != null && mPendingIdleUntil.operation.equals(operation)) {
1478 mPendingIdleUntil = null;
1479 restorePending = true;
1480 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001481 if (mNextWakeFromIdle != null && mNextWakeFromIdle.operation.equals(operation)) {
1482 mNextWakeFromIdle = null;
1483 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001484 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001485 if (restorePending) {
1486 restorePendingWhileIdleAlarmsLocked();
1487 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001488 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001489 }
1490 }
1491
1492 void removeLocked(String packageName) {
1493 boolean didRemove = false;
1494 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1495 Batch b = mAlarmBatches.get(i);
1496 didRemove |= b.remove(packageName);
1497 if (b.size() == 0) {
1498 mAlarmBatches.remove(i);
1499 }
1500 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001501 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1502 if (mPendingWhileIdleAlarms.get(i).operation.getTargetPackage().equals(packageName)) {
1503 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1504 mPendingWhileIdleAlarms.remove(i);
1505 }
1506 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001507
1508 if (didRemove) {
1509 if (DEBUG_BATCH) {
1510 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1511 }
1512 rebatchAllAlarmsLocked(true);
1513 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001514 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001515 }
1516 }
1517
1518 void removeUserLocked(int userHandle) {
1519 boolean didRemove = false;
1520 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1521 Batch b = mAlarmBatches.get(i);
1522 didRemove |= b.remove(userHandle);
1523 if (b.size() == 0) {
1524 mAlarmBatches.remove(i);
1525 }
1526 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001527 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1528 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).operation.getCreatorUid())
1529 == userHandle) {
1530 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1531 mPendingWhileIdleAlarms.remove(i);
1532 }
1533 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001534
1535 if (didRemove) {
1536 if (DEBUG_BATCH) {
1537 Slog.v(TAG, "remove(user) changed bounds; rebatching");
1538 }
1539 rebatchAllAlarmsLocked(true);
1540 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001541 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001542 }
1543 }
1544
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001545 void interactiveStateChangedLocked(boolean interactive) {
1546 if (mInteractive != interactive) {
1547 mInteractive = interactive;
1548 final long nowELAPSED = SystemClock.elapsedRealtime();
1549 if (interactive) {
1550 if (mPendingNonWakeupAlarms.size() > 0) {
1551 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1552 mTotalDelayTime += thisDelayTime;
1553 if (mMaxDelayTime < thisDelayTime) {
1554 mMaxDelayTime = thisDelayTime;
1555 }
1556 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
1557 mPendingNonWakeupAlarms.clear();
1558 }
1559 if (mNonInteractiveStartTime > 0) {
1560 long dur = nowELAPSED - mNonInteractiveStartTime;
1561 if (dur > mNonInteractiveTime) {
1562 mNonInteractiveTime = dur;
1563 }
1564 }
1565 } else {
1566 mNonInteractiveStartTime = nowELAPSED;
1567 }
1568 }
1569 }
1570
Adam Lesinski182f73f2013-12-05 16:48:06 -08001571 boolean lookForPackageLocked(String packageName) {
1572 for (int i = 0; i < mAlarmBatches.size(); i++) {
1573 Batch b = mAlarmBatches.get(i);
1574 if (b.hasPackage(packageName)) {
1575 return true;
1576 }
1577 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001578 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
1579 if (mPendingWhileIdleAlarms.get(i).operation.getTargetPackage().equals(packageName)) {
1580 return true;
1581 }
1582 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001583 return false;
1584 }
1585
1586 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001587 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001588 // The kernel never triggers alarms with negative wakeup times
1589 // so we ensure they are positive.
1590 long alarmSeconds, alarmNanoseconds;
1591 if (when < 0) {
1592 alarmSeconds = 0;
1593 alarmNanoseconds = 0;
1594 } else {
1595 alarmSeconds = when / 1000;
1596 alarmNanoseconds = (when % 1000) * 1000 * 1000;
1597 }
1598
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001599 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001600 } else {
1601 Message msg = Message.obtain();
1602 msg.what = ALARM_EVENT;
1603
1604 mHandler.removeMessages(ALARM_EVENT);
1605 mHandler.sendMessageAtTime(msg, when);
1606 }
1607 }
1608
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001609 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001610 String prefix, String label, long nowRTC, long nowELAPSED, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 for (int i=list.size()-1; i>=0; i--) {
1612 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001613 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1614 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001615 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001616 }
1617 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001618
1619 private static final String labelForType(int type) {
1620 switch (type) {
1621 case RTC: return "RTC";
1622 case RTC_WAKEUP : return "RTC_WAKEUP";
1623 case ELAPSED_REALTIME : return "ELAPSED";
1624 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
1625 default:
1626 break;
1627 }
1628 return "--unknown--";
1629 }
1630
1631 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001632 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001633 for (int i=list.size()-1; i>=0; i--) {
1634 Alarm a = list.get(i);
1635 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001636 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1637 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001638 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001639 }
1640 }
1641
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001642 private native long init();
1643 private native void close(long nativeData);
1644 private native void set(long nativeData, int type, long seconds, long nanoseconds);
1645 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08001646 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001647 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001649 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001650 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001651 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001652 // batches are temporally sorted, so we need only pull from the
1653 // start of the list until we either empty it or hit a batch
1654 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07001655 while (mAlarmBatches.size() > 0) {
1656 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001657 if (batch.start > nowELAPSED) {
1658 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 break;
1660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661
Christopher Tatee0a22b32013-07-11 14:43:13 -07001662 // We will (re)schedule some alarms now; don't let that interfere
1663 // with delivery of this current batch
1664 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001665
Christopher Tatee0a22b32013-07-11 14:43:13 -07001666 final int N = batch.size();
1667 for (int i = 0; i < N; i++) {
1668 Alarm alarm = batch.get(i);
1669 alarm.count = 1;
1670 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001671 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1672 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
1673 alarm.tag);
1674 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001675 if (mPendingIdleUntil == alarm) {
1676 mPendingIdleUntil = null;
1677 rebatchAllAlarmsLocked(false);
1678 restorePendingWhileIdleAlarmsLocked();
1679 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001680 if (mNextWakeFromIdle == alarm) {
1681 mNextWakeFromIdle = null;
1682 rebatchAllAlarmsLocked(false);
1683 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001684
1685 // Recurring alarms may have passed several alarm intervals while the
1686 // phone was asleep or off, so pass a trigger count when sending them.
1687 if (alarm.repeatInterval > 0) {
1688 // this adjustment will be zero if we're late by
1689 // less than one full repeat interval
1690 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
1691
1692 // Also schedule its next recurrence
1693 final long delta = alarm.count * alarm.repeatInterval;
1694 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07001695 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07001696 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001697 alarm.repeatInterval, alarm.operation, alarm.flags, true,
Adrian Roosc42a1e12014-07-07 23:35:53 +02001698 alarm.workSource, alarm.alarmClock, alarm.userId);
Christopher Tate864d42e2014-12-02 11:48:53 -08001699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700
Christopher Tate864d42e2014-12-02 11:48:53 -08001701 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001702 hasWakeup = true;
1703 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001704
1705 // We removed an alarm clock. Let the caller recompute the next alarm clock.
1706 if (alarm.alarmClock != null) {
1707 mNextAlarmClockMayChange = true;
1708 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07001709 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001711
Christopher Tate1590f1e2014-10-02 17:27:57 -07001712 // This is a new alarm delivery set; bump the sequence number to indicate that
1713 // all apps' alarm delivery classes should be recalculated.
1714 mCurrentSeq++;
1715 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001716 Collections.sort(triggerList, mAlarmDispatchComparator);
1717
1718 if (localLOGV) {
1719 for (int i=0; i<triggerList.size(); i++) {
1720 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
1721 }
1722 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001723
1724 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 /**
1728 * This Comparator sorts Alarms into increasing time order.
1729 */
1730 public static class IncreasingTimeOrder implements Comparator<Alarm> {
1731 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09001732 long when1 = a1.whenElapsed;
1733 long when2 = a2.whenElapsed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 if (when1 - when2 > 0) {
1735 return 1;
1736 }
1737 if (when1 - when2 < 0) {
1738 return -1;
1739 }
1740 return 0;
1741 }
1742 }
1743
1744 private static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001745 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001746 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001747 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001748 public final PendingIntent operation;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001749 public final String tag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001750 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001751 public final int flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 public int count;
1753 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07001754 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001755 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001756 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001757 public long repeatInterval;
Jose Lima235510e2014-08-13 12:50:01 -07001758 public final AlarmManager.AlarmClockInfo alarmClock;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001759 public final int userId;
Christopher Tate1590f1e2014-10-02 17:27:57 -07001760 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001761
Christopher Tate3e04b472013-10-21 17:51:31 -07001762 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001763 long _interval, PendingIntent _op, WorkSource _ws, int _flags,
Jose Lima235510e2014-08-13 12:50:01 -07001764 AlarmManager.AlarmClockInfo _info, int _userId) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001765 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001766 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001767 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
1768 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001769 when = _when;
1770 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07001771 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001772 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001773 repeatInterval = _interval;
1774 operation = _op;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001775 tag = makeTag(_op, _type);
David Christieebe51fc2013-07-26 13:23:29 -07001776 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001777 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001778 alarmClock = _info;
1779 userId = _userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001781
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001782 public static String makeTag(PendingIntent pi, int type) {
1783 return pi.getTag(type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
1784 ? "*walarm*:" : "*alarm*:");
1785 }
1786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001788 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001789 StringBuilder sb = new StringBuilder(128);
1790 sb.append("Alarm{");
1791 sb.append(Integer.toHexString(System.identityHashCode(this)));
1792 sb.append(" type ");
1793 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001794 sb.append(" when ");
1795 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001796 sb.append(" ");
1797 sb.append(operation.getTargetPackage());
1798 sb.append('}');
1799 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 }
1801
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001802 public void dump(PrintWriter pw, String prefix, long nowRTC, long nowELAPSED,
1803 SimpleDateFormat sdf) {
1804 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
1805 pw.print(prefix); pw.print("tag="); pw.println(tag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001806 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001807 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
1808 nowELAPSED, pw);
1809 if (isRtc) {
1810 pw.print(" when="); pw.print(sdf.format(new Date(when)));
1811 } else {
1812 pw.print(" when="); TimeUtils.formatDuration(when, nowELAPSED, pw);
1813 }
1814 pw.println();
1815 pw.print(prefix); pw.print("window="); pw.print(windowLength);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001816 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001817 pw.print(" count="); pw.print(count);
1818 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001819 if (alarmClock != null) {
1820 pw.print(prefix); pw.println("Alarm clock:");
1821 pw.print(prefix); pw.print(" triggerTime=");
1822 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
1823 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
1824 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001825 pw.print(prefix); pw.print("operation="); pw.println(operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 }
1827 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001828
Christopher Tatee0a22b32013-07-11 14:43:13 -07001829 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
1830 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07001831 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
1832 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001833 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07001834 break;
1835 }
1836
Christopher Tatee0a22b32013-07-11 14:43:13 -07001837 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07001838 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
1839 Alarm a = b.alarms.get(nextAlarm);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001840 WakeupEvent e = new WakeupEvent(nowRTC,
1841 a.operation.getCreatorUid(),
1842 a.operation.getIntent().getAction());
1843 mRecentWakeups.add(e);
1844 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001845 }
1846 }
1847
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001848 long currentNonWakeupFuzzLocked(long nowELAPSED) {
1849 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
1850 if (timeSinceOn < 5*60*1000) {
1851 // If the screen has been off for 5 minutes, only delay by at most two minutes.
1852 return 2*60*1000;
1853 } else if (timeSinceOn < 30*60*1000) {
1854 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
1855 return 15*60*1000;
1856 } else {
1857 // Otherwise, we will delay by at most an hour.
1858 return 60*60*1000;
1859 }
1860 }
1861
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001862 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001863 if (duration < 15*60*1000) {
1864 // If the duration until the time is less than 15 minutes, the maximum fuzz
1865 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001866 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001867 } else if (duration < 90*60*1000) {
1868 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
1869 return 15*60*1000;
1870 } else {
1871 // Otherwise, we will fuzz by at most half an hour.
1872 return 30*60*1000;
1873 }
1874 }
1875
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001876 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
1877 if (mInteractive) {
1878 return false;
1879 }
1880 if (mLastAlarmDeliveryTime <= 0) {
1881 return false;
1882 }
minho.choo649acab2014-12-12 16:13:55 +09001883 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001884 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
1885 // and the next delivery time is in the past, then just deliver them all. This
1886 // avoids bugs where we get stuck in a loop trying to poll for alarms.
1887 return false;
1888 }
1889 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
1890 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
1891 }
1892
1893 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
1894 mLastAlarmDeliveryTime = nowELAPSED;
1895 for (int i=0; i<triggerList.size(); i++) {
1896 Alarm alarm = triggerList.get(i);
1897 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07001898 if (localLOGV) {
1899 Slog.v(TAG, "sending alarm " + alarm);
1900 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07001901 if (RECORD_ALARMS_IN_HISTORY) {
1902 if (alarm.workSource != null && alarm.workSource.size() > 0) {
1903 for (int wi=0; wi<alarm.workSource.size(); wi++) {
1904 ActivityManagerNative.noteAlarmStart(
1905 alarm.operation, alarm.workSource.get(wi), alarm.tag);
1906 }
1907 } else {
1908 ActivityManagerNative.noteAlarmStart(
1909 alarm.operation, -1, alarm.tag);
1910 }
1911 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001912 alarm.operation.send(getContext(), 0,
1913 mBackgroundIntent.putExtra(
1914 Intent.EXTRA_ALARM_COUNT, alarm.count),
1915 mResultReceiver, mHandler);
1916
1917 // we have an active broadcast so stay awake.
1918 if (mBroadcastRefCount == 0) {
1919 setWakelockWorkSource(alarm.operation, alarm.workSource,
1920 alarm.type, alarm.tag, true);
1921 mWakeLock.acquire();
1922 }
1923 final InFlight inflight = new InFlight(AlarmManagerService.this,
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001924 alarm.operation, alarm.workSource, alarm.type, alarm.tag, nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001925 mInFlight.add(inflight);
1926 mBroadcastRefCount++;
1927
1928 final BroadcastStats bs = inflight.mBroadcastStats;
1929 bs.count++;
1930 if (bs.nesting == 0) {
1931 bs.nesting = 1;
1932 bs.startTime = nowELAPSED;
1933 } else {
1934 bs.nesting++;
1935 }
1936 final FilterStats fs = inflight.mFilterStats;
1937 fs.count++;
1938 if (fs.nesting == 0) {
1939 fs.nesting = 1;
1940 fs.startTime = nowELAPSED;
1941 } else {
1942 fs.nesting++;
1943 }
1944 if (alarm.type == ELAPSED_REALTIME_WAKEUP
1945 || alarm.type == RTC_WAKEUP) {
1946 bs.numWakeup++;
1947 fs.numWakeup++;
1948 if (alarm.workSource != null && alarm.workSource.size() > 0) {
1949 for (int wi=0; wi<alarm.workSource.size(); wi++) {
1950 ActivityManagerNative.noteWakeupAlarm(
1951 alarm.operation, alarm.workSource.get(wi),
Dianne Hackborn1e383822015-04-10 14:02:33 -07001952 alarm.workSource.getName(wi), alarm.tag);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001953 }
1954 } else {
1955 ActivityManagerNative.noteWakeupAlarm(
Dianne Hackborn1e383822015-04-10 14:02:33 -07001956 alarm.operation, -1, null, alarm.tag);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001957 }
1958 }
1959 } catch (PendingIntent.CanceledException e) {
1960 if (alarm.repeatInterval > 0) {
1961 // This IntentSender is no longer valid, but this
1962 // is a repeating alarm, so toss the hoser.
1963 removeImpl(alarm.operation);
1964 }
1965 } catch (RuntimeException e) {
1966 Slog.w(TAG, "Failure sending alarm.", e);
1967 }
1968 }
1969 }
1970
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001971 private class AlarmThread extends Thread
1972 {
1973 public AlarmThread()
1974 {
1975 super("AlarmManager");
1976 }
1977
1978 public void run()
1979 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07001980 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
1981
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001982 while (true)
1983 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001984 int result = waitForAlarm(mNativeData);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001985
1986 triggerList.clear();
1987
Dianne Hackbornc3527222015-05-13 14:03:20 -07001988 final long nowRTC = System.currentTimeMillis();
1989 final long nowELAPSED = SystemClock.elapsedRealtime();
1990
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001991 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07001992 // The kernel can give us spurious time change notifications due to
1993 // small adjustments it makes internally; we want to filter those out.
1994 final long lastTimeChangeClockTime;
1995 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07001996 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07001997 lastTimeChangeClockTime = mLastTimeChangeClockTime;
1998 expectedClockTime = lastTimeChangeClockTime
1999 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07002000 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002001 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-500)
2002 || nowRTC > (expectedClockTime+500)) {
2003 // The change is by at least +/- 500 ms (or this is the first change),
2004 // let's do it!
2005 if (DEBUG_BATCH) {
2006 Slog.v(TAG, "Time changed notification from kernel; rebatching");
2007 }
2008 removeImpl(mTimeTickSender);
2009 rebatchAllAlarms();
2010 mClockReceiver.scheduleTimeTickEvent();
2011 synchronized (mLock) {
2012 mNumTimeChanged++;
2013 mLastTimeChangeClockTime = nowRTC;
2014 mLastTimeChangeRealtime = nowELAPSED;
2015 }
2016 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
2017 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
2018 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2019 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
2020
2021 // The world has changed on us, so we need to re-evaluate alarms
2022 // regardless of whether the kernel has told us one went off.
2023 result |= IS_WAKEUP_MASK;
2024 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002025 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026
Dianne Hackbornc3527222015-05-13 14:03:20 -07002027 if (result != TIME_CHANGED_MASK) {
2028 // If this was anything besides just a time change, then figure what if
2029 // anything to do about alarms.
2030 synchronized (mLock) {
2031 if (localLOGV) Slog.v(
2032 TAG, "Checking for alarms... rtc=" + nowRTC
2033 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07002034
Dianne Hackbornc3527222015-05-13 14:03:20 -07002035 if (WAKEUP_STATS) {
2036 if ((result & IS_WAKEUP_MASK) != 0) {
2037 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
2038 int n = 0;
2039 for (WakeupEvent event : mRecentWakeups) {
2040 if (event.when > newEarliest) break;
2041 n++; // number of now-stale entries at the list head
2042 }
2043 for (int i = 0; i < n; i++) {
2044 mRecentWakeups.remove();
2045 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002046
Dianne Hackbornc3527222015-05-13 14:03:20 -07002047 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002048 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002049 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002050
2051 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2052 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
2053 // if there are no wakeup alarms and the screen is off, we can
2054 // delay what we have so far until the future.
2055 if (mPendingNonWakeupAlarms.size() == 0) {
2056 mStartCurrentDelayTime = nowELAPSED;
2057 mNextNonWakeupDeliveryTime = nowELAPSED
2058 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
2059 }
2060 mPendingNonWakeupAlarms.addAll(triggerList);
2061 mNumDelayedAlarms += triggerList.size();
2062 rescheduleKernelAlarmsLocked();
2063 updateNextAlarmClockLocked();
2064 } else {
2065 // now deliver the alarm intents; if there are pending non-wakeup
2066 // alarms, we need to merge them in to the list. note we don't
2067 // just deliver them first because we generally want non-wakeup
2068 // alarms delivered after wakeup alarms.
2069 rescheduleKernelAlarmsLocked();
2070 updateNextAlarmClockLocked();
2071 if (mPendingNonWakeupAlarms.size() > 0) {
2072 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
2073 triggerList.addAll(mPendingNonWakeupAlarms);
2074 Collections.sort(triggerList, mAlarmDispatchComparator);
2075 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2076 mTotalDelayTime += thisDelayTime;
2077 if (mMaxDelayTime < thisDelayTime) {
2078 mMaxDelayTime = thisDelayTime;
2079 }
2080 mPendingNonWakeupAlarms.clear();
2081 }
2082 deliverAlarmsLocked(triggerList, nowELAPSED);
2083 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002084 }
2085 }
2086 }
2087 }
2088 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002089
David Christieebe51fc2013-07-26 13:23:29 -07002090 /**
2091 * Attribute blame for a WakeLock.
2092 * @param pi PendingIntent to attribute blame to if ws is null.
2093 * @param ws WorkSource to attribute blame.
2094 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002095 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
2096 boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07002097 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002098 final boolean unimportant = pi == mTimeTickSender;
2099 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002100 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002101 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002102 } else {
2103 mWakeLock.setHistoryTag(null);
2104 }
2105 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07002106 if (ws != null) {
2107 mWakeLock.setWorkSource(ws);
2108 return;
2109 }
2110
Christopher Tatec4a07d12012-04-06 14:19:13 -07002111 final int uid = ActivityManagerNative.getDefault()
2112 .getUidForIntentSender(pi.getTarget());
2113 if (uid >= 0) {
2114 mWakeLock.setWorkSource(new WorkSource(uid));
2115 return;
2116 }
2117 } catch (Exception e) {
2118 }
2119
2120 // Something went wrong; fall back to attributing the lock to the OS
2121 mWakeLock.setWorkSource(null);
2122 }
2123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002124 private class AlarmHandler extends Handler {
2125 public static final int ALARM_EVENT = 1;
2126 public static final int MINUTE_CHANGE_EVENT = 2;
2127 public static final int DATE_CHANGE_EVENT = 3;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002128 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002129
2130 public AlarmHandler() {
2131 }
2132
2133 public void handleMessage(Message msg) {
2134 if (msg.what == ALARM_EVENT) {
2135 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2136 synchronized (mLock) {
2137 final long nowRTC = System.currentTimeMillis();
Christopher Tatee0a22b32013-07-11 14:43:13 -07002138 final long nowELAPSED = SystemClock.elapsedRealtime();
2139 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002140 updateNextAlarmClockLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002141 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002143 // now trigger the alarms without the lock held
Dianne Hackborn390517b2013-05-30 15:03:32 -07002144 for (int i=0; i<triggerList.size(); i++) {
2145 Alarm alarm = triggerList.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002146 try {
2147 alarm.operation.send();
2148 } catch (PendingIntent.CanceledException e) {
2149 if (alarm.repeatInterval > 0) {
2150 // This IntentSender is no longer valid, but this
2151 // is a repeating alarm, so toss the hoser.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002152 removeImpl(alarm.operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002153 }
2154 }
2155 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002156 } else if (msg.what == SEND_NEXT_ALARM_CLOCK_CHANGED) {
2157 sendNextAlarmClockChanged();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002158 }
2159 }
2160 }
2161
2162 class ClockReceiver extends BroadcastReceiver {
2163 public ClockReceiver() {
2164 IntentFilter filter = new IntentFilter();
2165 filter.addAction(Intent.ACTION_TIME_TICK);
2166 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002167 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002168 }
2169
2170 @Override
2171 public void onReceive(Context context, Intent intent) {
2172 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07002173 if (DEBUG_BATCH) {
2174 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
2175 }
2176 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002177 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
2178 // Since the kernel does not keep track of DST, we need to
2179 // reset the TZ information at the beginning of each day
2180 // based off of the current Zone gmt offset + userspace tracked
2181 // daylight savings information.
2182 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02002183 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002184 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07002185 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002186 }
2187 }
2188
2189 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07002190 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09002191 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07002192
2193 // Schedule this event for the amount of time that it would take to get to
2194 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09002195 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07002196
David Christieebe51fc2013-07-26 13:23:29 -07002197 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002198 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002199 0, mTimeTickSender, AlarmManager.FLAG_STANDALONE, workSource, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002200 }
Christopher Tate385e4982013-07-23 18:22:29 -07002201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002202 public void scheduleDateChangedEvent() {
2203 Calendar calendar = Calendar.getInstance();
2204 calendar.setTimeInMillis(System.currentTimeMillis());
2205 calendar.set(Calendar.HOUR, 0);
2206 calendar.set(Calendar.MINUTE, 0);
2207 calendar.set(Calendar.SECOND, 0);
2208 calendar.set(Calendar.MILLISECOND, 0);
2209 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07002210
2211 final WorkSource workSource = null; // Let system take blame for date change events.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002212 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender,
2213 AlarmManager.FLAG_STANDALONE, workSource, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002214 }
2215 }
2216
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002217 class InteractiveStateReceiver extends BroadcastReceiver {
2218 public InteractiveStateReceiver() {
2219 IntentFilter filter = new IntentFilter();
2220 filter.addAction(Intent.ACTION_SCREEN_OFF);
2221 filter.addAction(Intent.ACTION_SCREEN_ON);
2222 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
2223 getContext().registerReceiver(this, filter);
2224 }
2225
2226 @Override
2227 public void onReceive(Context context, Intent intent) {
2228 synchronized (mLock) {
2229 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
2230 }
2231 }
2232 }
2233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002234 class UninstallReceiver extends BroadcastReceiver {
2235 public UninstallReceiver() {
2236 IntentFilter filter = new IntentFilter();
2237 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2238 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002239 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002240 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08002241 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002242 // Register for events related to sdcard installation.
2243 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08002244 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002245 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002246 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002247 }
2248
2249 @Override
2250 public void onReceive(Context context, Intent intent) {
2251 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002252 String action = intent.getAction();
2253 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002254 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
2255 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
2256 for (String packageName : pkgList) {
2257 if (lookForPackageLocked(packageName)) {
2258 setResultCode(Activity.RESULT_OK);
2259 return;
2260 }
2261 }
2262 return;
2263 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002264 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002265 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
2266 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
2267 if (userHandle >= 0) {
2268 removeUserLocked(userHandle);
2269 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002270 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08002271 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
2272 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
2273 // This package is being updated; don't kill its alarms.
2274 return;
2275 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002276 Uri data = intent.getData();
2277 if (data != null) {
2278 String pkg = data.getSchemeSpecificPart();
2279 if (pkg != null) {
2280 pkgList = new String[]{pkg};
2281 }
2282 }
2283 }
2284 if (pkgList != null && (pkgList.length > 0)) {
2285 for (String pkg : pkgList) {
2286 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07002287 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002288 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
2289 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
2290 if (uidStats.remove(pkg) != null) {
2291 if (uidStats.size() <= 0) {
2292 mBroadcastStats.removeAt(i);
2293 }
2294 }
2295 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002297 }
2298 }
2299 }
2300 }
2301
2302 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002303 String pkg = pi.getCreatorPackage();
2304 int uid = pi.getCreatorUid();
2305 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
2306 if (uidStats == null) {
2307 uidStats = new ArrayMap<String, BroadcastStats>();
2308 mBroadcastStats.put(uid, uidStats);
2309 }
2310 BroadcastStats bs = uidStats.get(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002311 if (bs == null) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002312 bs = new BroadcastStats(uid, pkg);
2313 uidStats.put(pkg, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002314 }
2315 return bs;
2316 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002318 class ResultReceiver implements PendingIntent.OnFinished {
2319 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
2320 String resultData, Bundle resultExtras) {
2321 synchronized (mLock) {
Dianne Hackborn81038902012-11-26 17:04:09 -08002322 InFlight inflight = null;
2323 for (int i=0; i<mInFlight.size(); i++) {
2324 if (mInFlight.get(i).mPendingIntent == pi) {
2325 inflight = mInFlight.remove(i);
2326 break;
2327 }
2328 }
2329 if (inflight != null) {
2330 final long nowELAPSED = SystemClock.elapsedRealtime();
2331 BroadcastStats bs = inflight.mBroadcastStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002332 bs.nesting--;
2333 if (bs.nesting <= 0) {
2334 bs.nesting = 0;
Dianne Hackborn81038902012-11-26 17:04:09 -08002335 bs.aggregateTime += nowELAPSED - bs.startTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002336 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002337 FilterStats fs = inflight.mFilterStats;
2338 fs.nesting--;
2339 if (fs.nesting <= 0) {
2340 fs.nesting = 0;
2341 fs.aggregateTime += nowELAPSED - fs.startTime;
2342 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07002343 if (RECORD_ALARMS_IN_HISTORY) {
2344 if (inflight.mWorkSource != null && inflight.mWorkSource.size() > 0) {
2345 for (int wi=0; wi<inflight.mWorkSource.size(); wi++) {
2346 ActivityManagerNative.noteAlarmFinish(
2347 pi, inflight.mWorkSource.get(wi), inflight.mTag);
2348 }
2349 } else {
2350 ActivityManagerNative.noteAlarmFinish(
2351 pi, -1, inflight.mTag);
2352 }
2353 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002354 } else {
2355 mLog.w("No in-flight alarm for " + pi + " " + intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002356 }
2357 mBroadcastRefCount--;
2358 if (mBroadcastRefCount == 0) {
2359 mWakeLock.release();
Dianne Hackborn81038902012-11-26 17:04:09 -08002360 if (mInFlight.size() > 0) {
2361 mLog.w("Finished all broadcasts with " + mInFlight.size()
2362 + " remaining inflights");
2363 for (int i=0; i<mInFlight.size(); i++) {
2364 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
2365 }
2366 mInFlight.clear();
2367 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002368 } else {
2369 // the next of our alarms is now in flight. reattribute the wakelock.
Dianne Hackborn81038902012-11-26 17:04:09 -08002370 if (mInFlight.size() > 0) {
David Christieebe51fc2013-07-26 13:23:29 -07002371 InFlight inFlight = mInFlight.get(0);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08002372 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002373 inFlight.mAlarmType, inFlight.mTag, false);
Christopher Tatec4a07d12012-04-06 14:19:13 -07002374 } else {
2375 // should never happen
Dianne Hackborn81038902012-11-26 17:04:09 -08002376 mLog.w("Alarm wakelock still held but sent queue empty");
Christopher Tatec4a07d12012-04-06 14:19:13 -07002377 mWakeLock.setWorkSource(null);
2378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002379 }
2380 }
2381 }
2382 }
2383}