blob: 26ece72581cf11fbc7c6be1bb95c8485d59d5b28 [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 Hackborn3d1933c42015-06-10 16:25:57 -070050import android.util.SparseLongArray;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070051import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052
Christopher Tate4cb338d2013-07-26 13:11:31 -070053import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import java.io.FileDescriptor;
55import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070056import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -080058import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import java.util.Calendar;
60import java.util.Collections;
61import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -050062import java.util.Date;
Christopher Tate1590f1e2014-10-02 17:27:57 -070063import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -070064import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +020065import java.util.Locale;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070066import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import java.util.TimeZone;
John Spurlock604a5ee2015-06-01 12:27:22 -040068import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069
Christopher Tatee0a22b32013-07-11 14:43:13 -070070import static android.app.AlarmManager.RTC_WAKEUP;
71import static android.app.AlarmManager.RTC;
72import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
73import static android.app.AlarmManager.ELAPSED_REALTIME;
74
Dianne Hackborn81038902012-11-26 17:04:09 -080075import com.android.internal.util.LocalLog;
76
Adam Lesinski182f73f2013-12-05 16:48:06 -080077class AlarmManagerService extends SystemService {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078 // The threshold for how long an alarm can be late before we print a
79 // warning message. The time duration is in milliseconds.
80 private static final long LATE_ALARM_THRESHOLD = 10 * 1000;
Christopher Tatee0a22b32013-07-11 14:43:13 -070081
Christopher Tate498c6cb2014-11-17 16:09:27 -080082 // Minimum futurity of a new alarm
83 private static final long MIN_FUTURITY = 5 * 1000; // 5 seconds, in millis
84
85 // Minimum alarm recurrence interval
86 private static final long MIN_INTERVAL = 60 * 1000; // one minute, in millis
87
Dianne Hackborn3d1933c42015-06-10 16:25:57 -070088 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
89 private static final long ALLOW_WHILE_IDLE_SHORT_TIME = 60*1000;
90
91 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
92 private static final long ALLOW_WHILE_IDLE_LONG_TIME = 15*60*1000;
93
Christopher Tatee0a22b32013-07-11 14:43:13 -070094 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
95 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -080096 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -070097 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -080098 static final int TIME_CHANGED_MASK = 1 << 16;
99 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -0800100
Christopher Tatee0a22b32013-07-11 14:43:13 -0700101 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -0800102 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -0800103
Adam Lesinski182f73f2013-12-05 16:48:06 -0800104 static final String TAG = "AlarmManager";
105 static final String ClockReceiver_TAG = "ClockReceiver";
106 static final boolean localLOGV = false;
107 static final boolean DEBUG_BATCH = localLOGV || false;
108 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200109 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700110 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800111 static final int ALARM_EVENT = 1;
112 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200113
Adam Lesinski182f73f2013-12-05 16:48:06 -0800114 static final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800116 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117
Adam Lesinski182f73f2013-12-05 16:48:06 -0800118 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700119
Adrian Roosc42a1e12014-07-07 23:35:53 +0200120 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT = new Intent(
121 AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED);
122
Adam Lesinski182f73f2013-12-05 16:48:06 -0800123 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800124
Adam Lesinski182f73f2013-12-05 16:48:06 -0800125 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800126
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800127 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800128 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700129 private long mNextNonWakeup;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800130 int mBroadcastRefCount = 0;
131 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700132 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700133 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
134 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800135 final AlarmHandler mHandler = new AlarmHandler();
136 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700137 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138 private UninstallReceiver mUninstallReceiver;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800139 final ResultReceiver mResultReceiver = new ResultReceiver();
140 PendingIntent mTimeTickSender;
141 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700142 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700143 boolean mInteractive = true;
144 long mNonInteractiveStartTime;
145 long mNonInteractiveTime;
146 long mLastAlarmDeliveryTime;
147 long mStartCurrentDelayTime;
148 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700149 long mLastTimeChangeClockTime;
150 long mLastTimeChangeRealtime;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700151 long mAllowWhileIdleMinTime = ALLOW_WHILE_IDLE_SHORT_TIME;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700152 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800153
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700154 /**
155 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
156 * used to determine the earliest we can dispatch the next such alarm.
157 */
158 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
159
Jose Lima235510e2014-08-13 12:50:01 -0700160 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
161 new SparseArray<>();
162 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
163 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200164 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
165 new SparseBooleanArray();
166 private boolean mNextAlarmClockMayChange;
167
168 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700169 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
170 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200171
Christopher Tate1590f1e2014-10-02 17:27:57 -0700172 // Alarm delivery ordering bookkeeping
173 static final int PRIO_TICK = 0;
174 static final int PRIO_WAKEUP = 1;
175 static final int PRIO_NORMAL = 2;
176
177 class PriorityClass {
178 int seq;
179 int priority;
180
181 PriorityClass() {
182 seq = mCurrentSeq - 1;
183 priority = PRIO_NORMAL;
184 }
185 }
186
187 final HashMap<String, PriorityClass> mPriorities =
188 new HashMap<String, PriorityClass>();
189 int mCurrentSeq = 0;
190
Christopher Tate18a75f12013-07-01 18:18:59 -0700191 class WakeupEvent {
192 public long when;
193 public int uid;
194 public String action;
195
196 public WakeupEvent(long theTime, int theUid, String theAction) {
197 when = theTime;
198 uid = theUid;
199 action = theAction;
200 }
201 }
202
Adam Lesinski182f73f2013-12-05 16:48:06 -0800203 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
204 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700205
Adrian Roosc42a1e12014-07-07 23:35:53 +0200206 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700207 long start; // These endpoints are always in ELAPSED
208 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700209 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700210
211 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
212
213 Batch() {
214 start = 0;
215 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700216 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700217 }
218
219 Batch(Alarm seed) {
220 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700221 end = seed.maxWhenElapsed;
222 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700223 alarms.add(seed);
224 }
225
226 int size() {
227 return alarms.size();
228 }
229
230 Alarm get(int index) {
231 return alarms.get(index);
232 }
233
234 boolean canHold(long whenElapsed, long maxWhen) {
235 return (end >= whenElapsed) && (start <= maxWhen);
236 }
237
238 boolean add(Alarm alarm) {
239 boolean newStart = false;
240 // narrows the batch if necessary; presumes that canHold(alarm) is true
241 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
242 if (index < 0) {
243 index = 0 - index - 1;
244 }
245 alarms.add(index, alarm);
246 if (DEBUG_BATCH) {
247 Slog.v(TAG, "Adding " + alarm + " to " + this);
248 }
249 if (alarm.whenElapsed > start) {
250 start = alarm.whenElapsed;
251 newStart = true;
252 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700253 if (alarm.maxWhenElapsed < end) {
254 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700255 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700256 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700257
258 if (DEBUG_BATCH) {
259 Slog.v(TAG, " => now " + this);
260 }
261 return newStart;
262 }
263
264 boolean remove(final PendingIntent operation) {
265 boolean didRemove = false;
266 long newStart = 0; // recalculate endpoints as we go
267 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700268 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700269 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700270 Alarm alarm = alarms.get(i);
271 if (alarm.operation.equals(operation)) {
272 alarms.remove(i);
273 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200274 if (alarm.alarmClock != null) {
275 mNextAlarmClockMayChange = true;
276 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700277 } else {
278 if (alarm.whenElapsed > newStart) {
279 newStart = alarm.whenElapsed;
280 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700281 if (alarm.maxWhenElapsed < newEnd) {
282 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700283 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700284 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700285 i++;
286 }
287 }
288 if (didRemove) {
289 // commit the new batch bounds
290 start = newStart;
291 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700292 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700293 }
294 return didRemove;
295 }
296
297 boolean remove(final String packageName) {
298 boolean didRemove = false;
299 long newStart = 0; // recalculate endpoints as we go
300 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700301 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700302 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700303 Alarm alarm = alarms.get(i);
304 if (alarm.operation.getTargetPackage().equals(packageName)) {
305 alarms.remove(i);
306 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200307 if (alarm.alarmClock != null) {
308 mNextAlarmClockMayChange = true;
309 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700310 } else {
311 if (alarm.whenElapsed > newStart) {
312 newStart = alarm.whenElapsed;
313 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700314 if (alarm.maxWhenElapsed < newEnd) {
315 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700316 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700317 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700318 i++;
319 }
320 }
321 if (didRemove) {
322 // commit the new batch bounds
323 start = newStart;
324 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700325 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700326 }
327 return didRemove;
328 }
329
330 boolean remove(final int userHandle) {
331 boolean didRemove = false;
332 long newStart = 0; // recalculate endpoints as we go
333 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700334 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700335 Alarm alarm = alarms.get(i);
336 if (UserHandle.getUserId(alarm.operation.getCreatorUid()) == userHandle) {
337 alarms.remove(i);
338 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200339 if (alarm.alarmClock != null) {
340 mNextAlarmClockMayChange = true;
341 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700342 } else {
343 if (alarm.whenElapsed > newStart) {
344 newStart = alarm.whenElapsed;
345 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700346 if (alarm.maxWhenElapsed < newEnd) {
347 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700348 }
349 i++;
350 }
351 }
352 if (didRemove) {
353 // commit the new batch bounds
354 start = newStart;
355 end = newEnd;
356 }
357 return didRemove;
358 }
359
360 boolean hasPackage(final String packageName) {
361 final int N = alarms.size();
362 for (int i = 0; i < N; i++) {
363 Alarm a = alarms.get(i);
364 if (a.operation.getTargetPackage().equals(packageName)) {
365 return true;
366 }
367 }
368 return false;
369 }
370
371 boolean hasWakeups() {
372 final int N = alarms.size();
373 for (int i = 0; i < N; i++) {
374 Alarm a = alarms.get(i);
375 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
376 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
377 return true;
378 }
379 }
380 return false;
381 }
382
383 @Override
384 public String toString() {
385 StringBuilder b = new StringBuilder(40);
386 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
387 b.append(" num="); b.append(size());
388 b.append(" start="); b.append(start);
389 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700390 if (flags != 0) {
391 b.append(" flgs=0x");
392 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700393 }
394 b.append('}');
395 return b.toString();
396 }
397 }
398
399 static class BatchTimeOrder implements Comparator<Batch> {
400 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800401 long when1 = b1.start;
402 long when2 = b2.start;
403 if (when1 - when2 > 0) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700404 return 1;
405 }
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800406 if (when1 - when2 < 0) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700407 return -1;
408 }
409 return 0;
410 }
411 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800412
413 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
414 @Override
415 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700416 // priority class trumps everything. TICK < WAKEUP < NORMAL
417 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
418 return -1;
419 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
420 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800421 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700422
423 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800424 if (lhs.whenElapsed < rhs.whenElapsed) {
425 return -1;
426 } else if (lhs.whenElapsed > rhs.whenElapsed) {
427 return 1;
428 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700429
430 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800431 return 0;
432 }
433 };
434
Christopher Tate1590f1e2014-10-02 17:27:57 -0700435 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
436 final int N = alarms.size();
437 for (int i = 0; i < N; i++) {
438 Alarm a = alarms.get(i);
439
440 final int alarmPrio;
441 if (Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
442 alarmPrio = PRIO_TICK;
443 } else if (a.wakeup) {
444 alarmPrio = PRIO_WAKEUP;
445 } else {
446 alarmPrio = PRIO_NORMAL;
447 }
448
449 PriorityClass packagePrio = a.priorityClass;
450 if (packagePrio == null) packagePrio = mPriorities.get(a.operation.getCreatorPackage());
451 if (packagePrio == null) {
452 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
453 mPriorities.put(a.operation.getCreatorPackage(), packagePrio);
454 }
455 a.priorityClass = packagePrio;
456
457 if (packagePrio.seq != mCurrentSeq) {
458 // first alarm we've seen in the current delivery generation from this package
459 packagePrio.priority = alarmPrio;
460 packagePrio.seq = mCurrentSeq;
461 } else {
462 // Multiple alarms from this package being delivered in this generation;
463 // bump the package's delivery class if it's warranted.
464 // TICK < WAKEUP < NORMAL
465 if (alarmPrio < packagePrio.priority) {
466 packagePrio.priority = alarmPrio;
467 }
468 }
469 }
470 }
471
Christopher Tatee0a22b32013-07-11 14:43:13 -0700472 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800473 static final long MIN_FUZZABLE_INTERVAL = 10000;
474 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700475 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
476
477 // set to null if in idle mode; while in this mode, any alarms we don't want
478 // to run during this time are placed in mPendingWhileIdleAlarms
479 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700480 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700481 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700482
Jeff Brownb880d882014-02-10 19:47:07 -0800483 public AlarmManagerService(Context context) {
484 super(context);
485 }
486
Christopher Tatee0a22b32013-07-11 14:43:13 -0700487 static long convertToElapsed(long when, int type) {
488 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
489 if (isRtc) {
490 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
491 }
492 return when;
493 }
494
495 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
496 // calculate the end of our nominal delivery window for the alarm.
497 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
498 // Current heuristic: batchable window is 75% of either the recurrence interval
499 // [for a periodic alarm] or of the time from now to the desired delivery time,
500 // with a minimum delay/interval of 10 seconds, under which we will simply not
501 // defer the alarm.
502 long futurity = (interval == 0)
503 ? (triggerAtTime - now)
504 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700505 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700506 futurity = 0;
507 }
508 return triggerAtTime + (long)(.75 * futurity);
509 }
510
511 // returns true if the batch was added at the head
512 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
513 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
514 if (index < 0) {
515 index = 0 - index - 1;
516 }
517 list.add(index, newBatch);
518 return (index == 0);
519 }
520
Christopher Tate385e4982013-07-23 18:22:29 -0700521 // Return the index of the matching batch, or -1 if none found.
522 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700523 final int N = mAlarmBatches.size();
524 for (int i = 0; i < N; i++) {
525 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700526 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700527 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700528 }
529 }
Christopher Tate385e4982013-07-23 18:22:29 -0700530 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700531 }
532
533 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
534 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700535 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700536 rebatchAllAlarmsLocked(true);
537 }
538 }
539
540 void rebatchAllAlarmsLocked(boolean doValidate) {
541 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
542 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700543 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700544 final long nowElapsed = SystemClock.elapsedRealtime();
545 final int oldBatches = oldSet.size();
546 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
547 Batch batch = oldSet.get(batchNum);
548 final int N = batch.size();
549 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700550 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700551 }
552 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700553 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
554 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
555 + " to " + mPendingIdleUntil);
556 if (mPendingIdleUntil == null) {
557 // Somehow we lost this... we need to restore all of the pending alarms.
558 restorePendingWhileIdleAlarmsLocked();
559 }
560 }
561 rescheduleKernelAlarmsLocked();
562 updateNextAlarmClockLocked();
563 }
564
565 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
566 a.when = a.origWhen;
567 long whenElapsed = convertToElapsed(a.when, a.type);
568 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700569 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700570 // Exact
571 maxElapsed = whenElapsed;
572 } else {
573 // Not exact. Preserve any explicit window, otherwise recalculate
574 // the window based on the alarm's new futurity. Note that this
575 // reflects a policy of preferring timely to deferred delivery.
576 maxElapsed = (a.windowLength > 0)
577 ? (whenElapsed + a.windowLength)
578 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
579 }
580 a.whenElapsed = whenElapsed;
581 a.maxWhenElapsed = maxElapsed;
582 setImplLocked(a, true, doValidate);
583 }
584
585 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackborn35d54032015-04-23 10:30:43 -0700586 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700587 if (mPendingWhileIdleAlarms.size() > 0) {
588 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
589 mPendingWhileIdleAlarms = new ArrayList<>();
590 final long nowElapsed = SystemClock.elapsedRealtime();
591 for (int i=alarms.size() - 1; i >= 0; i--) {
592 Alarm a = alarms.get(i);
593 reAddAlarmLocked(a, nowElapsed, false);
594 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700595 }
Dianne Hackborn35d54032015-04-23 10:30:43 -0700596
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700597 // Make sure we are using the correct ALLOW_WHILE_IDLE min time.
598 mAllowWhileIdleMinTime = ALLOW_WHILE_IDLE_SHORT_TIME;
599
Dianne Hackborn35d54032015-04-23 10:30:43 -0700600 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700601 rescheduleKernelAlarmsLocked();
602 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -0700603
604 // And send a TIME_TICK right now, since it is important to get the UI updated.
605 try {
606 mTimeTickSender.send();
607 } catch (PendingIntent.CanceledException e) {
608 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700609 }
610
Adam Lesinski182f73f2013-12-05 16:48:06 -0800611 static final class InFlight extends Intent {
Dianne Hackborn81038902012-11-26 17:04:09 -0800612 final PendingIntent mPendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700613 final WorkSource mWorkSource;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700614 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800615 final BroadcastStats mBroadcastStats;
616 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800617 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800618
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800619 InFlight(AlarmManagerService service, PendingIntent pendingIntent, WorkSource workSource,
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700620 int alarmType, String tag, long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800621 mPendingIntent = pendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700622 mWorkSource = workSource;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700623 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800624 mBroadcastStats = service.getStatsLocked(pendingIntent);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700625 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -0800626 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700627 fs = new FilterStats(mBroadcastStats, mTag);
628 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -0800629 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700630 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -0800631 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800632 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800633 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800634 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800635
Adam Lesinski182f73f2013-12-05 16:48:06 -0800636 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -0800637 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700638 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800639
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700640 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800641 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800642 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643 int numWakeup;
644 long startTime;
645 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -0800646
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700647 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800648 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700649 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800650 }
651 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700652
Adam Lesinski182f73f2013-12-05 16:48:06 -0800653 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800654 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800655 final String mPackageName;
656
657 long aggregateTime;
658 int count;
659 int numWakeup;
660 long startTime;
661 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700662 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -0800663
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800664 BroadcastStats(int uid, String packageName) {
665 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800666 mPackageName = packageName;
667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800668 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700669
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800670 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
671 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700672
673 int mNumDelayedAlarms = 0;
674 long mTotalDelayTime = 0;
675 long mMaxDelayTime = 0;
676
Adam Lesinski182f73f2013-12-05 16:48:06 -0800677 @Override
678 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800679 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800680 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800681
682 // We have to set current TimeZone info to kernel
683 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -0800684 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800685
Adam Lesinski182f73f2013-12-05 16:48:06 -0800686 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800687 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800688
Adam Lesinski182f73f2013-12-05 16:48:06 -0800689 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700691 Intent.FLAG_RECEIVER_REGISTERED_ONLY
692 | Intent.FLAG_RECEIVER_FOREGROUND), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700693 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800694 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
695 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800696 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700697 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698
699 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -0800700 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701 mClockReceiver.scheduleTimeTickEvent();
702 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700703 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704 mUninstallReceiver = new UninstallReceiver();
705
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800706 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800707 AlarmThread waitThread = new AlarmThread();
708 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800710 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800712
713 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800714 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800715
716 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717 protected void finalize() throws Throwable {
718 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800719 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 } finally {
721 super.finalize();
722 }
723 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700724
Adam Lesinski182f73f2013-12-05 16:48:06 -0800725 void setTimeZoneImpl(String tz) {
726 if (TextUtils.isEmpty(tz)) {
727 return;
David Christieebe51fc2013-07-26 13:23:29 -0700728 }
729
Adam Lesinski182f73f2013-12-05 16:48:06 -0800730 TimeZone zone = TimeZone.getTimeZone(tz);
731 // Prevent reentrant calls from stepping on each other when writing
732 // the time zone property
733 boolean timeZoneWasChanged = false;
734 synchronized (this) {
735 String current = SystemProperties.get(TIMEZONE_PROPERTY);
736 if (current == null || !current.equals(zone.getID())) {
737 if (localLOGV) {
738 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
739 }
740 timeZoneWasChanged = true;
741 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
742 }
743
744 // Update the kernel timezone information
745 // Kernel tracks time offsets as 'minutes west of GMT'
746 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800747 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -0800748 }
749
750 TimeZone.setDefault(null);
751
752 if (timeZoneWasChanged) {
753 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
754 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
755 intent.putExtra("time-zone", zone.getID());
756 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
757 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700759
Adam Lesinski182f73f2013-12-05 16:48:06 -0800760 void removeImpl(PendingIntent operation) {
761 if (operation == null) {
762 return;
763 }
764 synchronized (mLock) {
765 removeLocked(operation);
766 }
767 }
768
769 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700770 PendingIntent operation, int flags, WorkSource workSource,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700771 AlarmManager.AlarmClockInfo alarmClock, int callingUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800772 if (operation == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800773 Slog.w(TAG, "set/setRepeating ignored because there is no intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 return;
775 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700776
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700777 // Sanity check the window length. This will catch people mistakenly
778 // trying to pass an end-of-window timestamp rather than a duration.
779 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
780 Slog.w(TAG, "Window length " + windowLength
781 + "ms suspiciously long; limiting to 1 hour");
782 windowLength = AlarmManager.INTERVAL_HOUR;
783 }
784
Christopher Tate498c6cb2014-11-17 16:09:27 -0800785 // Sanity check the recurrence interval. This will catch people who supply
786 // seconds when the API expects milliseconds.
787 if (interval > 0 && interval < MIN_INTERVAL) {
788 Slog.w(TAG, "Suspiciously short interval " + interval
789 + " millis; expanding to " + (int)(MIN_INTERVAL/1000)
790 + " seconds");
791 interval = MIN_INTERVAL;
792 }
793
Christopher Tatee0a22b32013-07-11 14:43:13 -0700794 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
795 throw new IllegalArgumentException("Invalid alarm type " + type);
796 }
797
Christopher Tate5f221e82013-07-30 17:13:15 -0700798 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -0700799 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700800 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -0700801 + " pid=" + what);
802 triggerAtTime = 0;
803 }
804
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700805 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -0800806 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
807 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
808 final long minTrigger = nowElapsed + MIN_FUTURITY;
809 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
810
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700811 final long maxElapsed;
812 if (windowLength == AlarmManager.WINDOW_EXACT) {
813 maxElapsed = triggerElapsed;
814 } else if (windowLength < 0) {
815 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700816 // Fix this window in place, so that as time approaches we don't collapse it.
817 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700818 } else {
819 maxElapsed = triggerElapsed + windowLength;
820 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800822 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700823 if (DEBUG_BATCH) {
824 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700825 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -0700826 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700827 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 }
Christopher Tate3e04b472013-10-21 17:51:31 -0700829 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700830 interval, operation, flags, true, workSource, alarmClock, callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 }
832 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833
Christopher Tate3e04b472013-10-21 17:51:31 -0700834 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700835 long maxWhen, long interval, PendingIntent operation, int flags,
Jose Lima235510e2014-08-13 12:50:01 -0700836 boolean doValidate, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700837 int uid) {
Christopher Tate3e04b472013-10-21 17:51:31 -0700838 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700839 operation, workSource, flags, alarmClock, uid);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700840 removeLocked(operation);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700841 setImplLocked(a, false, doValidate);
842 }
Christopher Tateb8849c12011-02-08 13:39:01 -0800843
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700844 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
845 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700846 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700847 // The caller has given the time they want this to happen at, however we need
848 // to pull that earlier if there are existing alarms that have requested to
849 // bring us out of idle.
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700850 if (mNextWakeFromIdle != null) {
851 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700852 }
853 // Add fuzz to make the alarm go off some time before the actual desired time.
854 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700855 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700856 if (fuzz > 0) {
857 if (mRandom == null) {
858 mRandom = new Random();
859 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700860 final int delta = mRandom.nextInt(fuzz);
861 a.whenElapsed -= delta;
862 if (false) {
863 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
864 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
865 Slog.d(TAG, "Applied fuzz: " + fuzz);
866 Slog.d(TAG, "Final delta: " + delta);
867 Slog.d(TAG, "Final when: " + a.whenElapsed);
868 }
869 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700870 }
871
872 } else if (mPendingIdleUntil != null) {
873 // We currently have an idle until alarm scheduled; if the new alarm has
874 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700875 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
876 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
877 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700878 == 0) {
879 mPendingWhileIdleAlarms.add(a);
880 return;
881 }
882 }
883
884 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
885 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -0700886 if (whichBatch < 0) {
887 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -0700888 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 } else {
Christopher Tate385e4982013-07-23 18:22:29 -0700890 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -0700891 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700892 // The start time of this batch advanced, so batch ordering may
893 // have just been broken. Move it to where it now belongs.
894 mAlarmBatches.remove(whichBatch);
895 addBatchLocked(mAlarmBatches, batch);
896 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 }
898
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700899 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +0200900 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200901 }
902
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700903 boolean needRebatch = false;
904
905 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
906 mPendingIdleUntil = a;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700907 mAllowWhileIdleMinTime = ALLOW_WHILE_IDLE_LONG_TIME;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700908 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700909 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
910 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
911 mNextWakeFromIdle = a;
912 // If this wake from idle is earlier than whatever was previously scheduled,
913 // and we are currently idling, then we need to rebatch alarms in case the idle
914 // until time needs to be updated.
915 if (mPendingIdleUntil != null) {
916 needRebatch = true;
917 }
918 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700919 }
920
921 if (!rebatching) {
922 if (DEBUG_VALIDATE) {
923 if (doValidate && !validateConsistencyLocked()) {
924 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
925 + " when(hex)=" + Long.toHexString(a.when)
926 + " whenElapsed=" + a.whenElapsed
927 + " maxWhenElapsed=" + a.maxWhenElapsed
928 + " interval=" + a.repeatInterval + " op=" + a.operation
929 + " flags=0x" + Integer.toHexString(a.flags));
930 rebatchAllAlarmsLocked(false);
931 needRebatch = false;
932 }
933 }
934
935 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700936 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -0700937 }
Christopher Tate4cb338d2013-07-26 13:11:31 -0700938
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700939 rescheduleKernelAlarmsLocked();
940 updateNextAlarmClockLocked();
941 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700942 }
943
Adam Lesinski182f73f2013-12-05 16:48:06 -0800944 private final IBinder mService = new IAlarmManager.Stub() {
945 @Override
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700946 public void set(int type, long triggerAtTime, long windowLength, long interval, int flags,
Jose Lima235510e2014-08-13 12:50:01 -0700947 PendingIntent operation, WorkSource workSource,
948 AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700949 final int callingUid = Binder.getCallingUid();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800950 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700951 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -0800952 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700953 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -0700954 }
955
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700956 // No incoming callers can request either WAKE_FROM_IDLE or
957 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
958 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
959 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
960
961 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
962 // manager when to come out of idle mode, which is only for DeviceIdleController.
963 if (callingUid != Process.SYSTEM_UID) {
964 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
965 }
966
967 // If the caller is a core system component, and not calling to do work on behalf
968 // of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED. This means we
969 // will allow these alarms to go off as normal even while idle, with no timing
970 // restrictions.
971 if (callingUid < Process.FIRST_APPLICATION_UID && workSource == null) {
972 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
973 }
974
975 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700976 if (windowLength == AlarmManager.WINDOW_EXACT) {
977 flags |= AlarmManager.FLAG_STANDALONE;
978 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700979
980 // If this alarm is for an alarm clock, then it must be standalone and we will
981 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700982 if (alarmClock != null) {
983 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
984 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700985
Adam Lesinski182f73f2013-12-05 16:48:06 -0800986 setImpl(type, triggerAtTime, windowLength, interval, operation,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700987 flags, workSource, alarmClock, callingUid);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800988 }
Christopher Tate89779822012-08-31 14:40:03 -0700989
Adam Lesinski182f73f2013-12-05 16:48:06 -0800990 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -0800991 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800992 getContext().enforceCallingOrSelfPermission(
993 "android.permission.SET_TIME",
994 "setTime");
995
Greg Hackmann0cab8962014-02-21 16:35:52 -0800996 if (mNativeData == 0) {
997 Slog.w(TAG, "Not setting time since no alarm driver is available.");
998 return false;
Christopher Tate89779822012-08-31 14:40:03 -0700999 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001000
1001 synchronized (mLock) {
1002 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001005
1006 @Override
1007 public void setTimeZone(String tz) {
1008 getContext().enforceCallingOrSelfPermission(
1009 "android.permission.SET_TIME_ZONE",
1010 "setTimeZone");
1011
1012 final long oldId = Binder.clearCallingIdentity();
1013 try {
1014 setTimeZoneImpl(tz);
1015 } finally {
1016 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 }
1018 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001019
Adam Lesinski182f73f2013-12-05 16:48:06 -08001020 @Override
1021 public void remove(PendingIntent operation) {
1022 removeImpl(operation);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001023
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001025
Adam Lesinski182f73f2013-12-05 16:48:06 -08001026 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001027 public long getNextWakeFromIdleTime() {
1028 return getNextWakeFromIdleTimeImpl();
1029 }
1030
1031 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001032 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001033 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1034 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1035 "getNextAlarmClock", null);
1036
1037 return getNextAlarmClockImpl(userId);
1038 }
1039
1040 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001041 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1042 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1043 != PackageManager.PERMISSION_GRANTED) {
1044 pw.println("Permission Denial: can't dump AlarmManager from from pid="
1045 + Binder.getCallingPid()
1046 + ", uid=" + Binder.getCallingUid());
1047 return;
Christopher Tate4cb338d2013-07-26 13:11:31 -07001048 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001049
Adam Lesinski182f73f2013-12-05 16:48:06 -08001050 dumpImpl(pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001051 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001052 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001053
Adam Lesinski182f73f2013-12-05 16:48:06 -08001054 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 synchronized (mLock) {
1056 pw.println("Current Alarm Manager state:");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001057 final long nowRTC = System.currentTimeMillis();
1058 final long nowELAPSED = SystemClock.elapsedRealtime();
1059 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1060
1061 pw.print("nowRTC="); pw.print(nowRTC);
1062 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001063 pw.print(" nowELAPSED="); TimeUtils.formatDuration(nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001064 pw.println();
Dianne Hackbornc3527222015-05-13 14:03:20 -07001065 pw.print("mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
1066 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
1067 pw.print("mLastTimeChangeRealtime=");
1068 TimeUtils.formatDuration(mLastTimeChangeRealtime, pw);
1069 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001070 if (!mInteractive) {
1071 pw.print("Time since non-interactive: ");
1072 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1073 pw.println();
1074 pw.print("Max wakeup delay: ");
1075 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1076 pw.println();
1077 pw.print("Time since last dispatch: ");
1078 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1079 pw.println();
1080 pw.print("Next non-wakeup delivery time: ");
1081 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1082 pw.println();
1083 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001084
1085 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1086 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001087 pw.print("Next non-wakeup alarm: ");
1088 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001089 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001090 pw.print("Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001091 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackborn998e6082014-09-11 19:13:23 -07001092 pw.print("Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001093
John Spurlock604a5ee2015-06-01 12:27:22 -04001094 pw.println();
1095 pw.println("Next alarm clock information: ");
1096 final TreeSet<Integer> users = new TreeSet<>();
1097 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1098 users.add(mNextAlarmClockForUser.keyAt(i));
1099 }
1100 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1101 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1102 }
1103 for (int user : users) {
1104 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1105 final long time = next != null ? next.getTriggerTime() : 0;
1106 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
1107 pw.print(" user:"); pw.print(user);
1108 pw.print(" pendingSend:"); pw.print(pendingSend);
1109 pw.print(" time:"); pw.print(time);
1110 if (time > 0) {
1111 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1112 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1113 }
1114 pw.println();
1115 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001116 if (mAlarmBatches.size() > 0) {
1117 pw.println();
1118 pw.print("Pending alarm batches: ");
1119 pw.println(mAlarmBatches.size());
1120 for (Batch b : mAlarmBatches) {
1121 pw.print(b); pw.println(':');
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001122 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001123 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001125 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001126 pw.println();
1127 pw.println("Idle mode state:");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001128 pw.print(" Idling until: ");
1129 if (mPendingIdleUntil != null) {
1130 pw.println(mPendingIdleUntil);
1131 mPendingIdleUntil.dump(pw, " ", nowRTC, nowELAPSED, sdf);
1132 } else {
1133 pw.println("null");
1134 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001135 pw.println(" Pending alarms:");
1136 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
1137 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001138 if (mNextWakeFromIdle != null) {
1139 pw.println();
1140 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
1141 mNextWakeFromIdle.dump(pw, " ", nowRTC, nowELAPSED, sdf);
1142 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001143
1144 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001145 pw.print("Past-due non-wakeup alarms: ");
1146 if (mPendingNonWakeupAlarms.size() > 0) {
1147 pw.println(mPendingNonWakeupAlarms.size());
1148 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
1149 } else {
1150 pw.println("(none)");
1151 }
1152 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
1153 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1154 pw.println();
1155 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
1156 pw.print(", max non-interactive time: ");
1157 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1158 pw.println();
1159
1160 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001161 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001162 pw.println();
1163
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001164 pw.print("mAllowWhileIdleMinTime=");
1165 TimeUtils.formatDuration(mAllowWhileIdleMinTime, pw);
1166 pw.println();
1167 if (mLastAllowWhileIdleDispatch.size() > 0) {
1168 pw.println("Last allow while idle dispatch times:");
1169 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
1170 pw.print(" UID ");
1171 UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
1172 pw.print(": ");
1173 TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i),
1174 nowELAPSED, pw);
1175 pw.println();
1176 }
1177 }
1178 pw.println();
1179
Dianne Hackborn81038902012-11-26 17:04:09 -08001180 if (mLog.dump(pw, " Recent problems", " ")) {
1181 pw.println();
1182 }
1183
1184 final FilterStats[] topFilters = new FilterStats[10];
1185 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1186 @Override
1187 public int compare(FilterStats lhs, FilterStats rhs) {
1188 if (lhs.aggregateTime < rhs.aggregateTime) {
1189 return 1;
1190 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1191 return -1;
1192 }
1193 return 0;
1194 }
1195 };
1196 int len = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001197 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1198 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1199 for (int ip=0; ip<uidStats.size(); ip++) {
1200 BroadcastStats bs = uidStats.valueAt(ip);
1201 for (int is=0; is<bs.filterStats.size(); is++) {
1202 FilterStats fs = bs.filterStats.valueAt(is);
1203 int pos = len > 0
1204 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1205 if (pos < 0) {
1206 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001207 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001208 if (pos < topFilters.length) {
1209 int copylen = topFilters.length - pos - 1;
1210 if (copylen > 0) {
1211 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1212 }
1213 topFilters[pos] = fs;
1214 if (len < topFilters.length) {
1215 len++;
1216 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001217 }
1218 }
1219 }
1220 }
1221 if (len > 0) {
1222 pw.println(" Top Alarms:");
1223 for (int i=0; i<len; i++) {
1224 FilterStats fs = topFilters[i];
1225 pw.print(" ");
1226 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1227 TimeUtils.formatDuration(fs.aggregateTime, pw);
1228 pw.print(" running, "); pw.print(fs.numWakeup);
1229 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001230 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1231 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001232 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001233 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001234 pw.println();
1235 }
1236 }
1237
1238 pw.println(" ");
1239 pw.println(" Alarm Stats:");
1240 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001241 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1242 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1243 for (int ip=0; ip<uidStats.size(); ip++) {
1244 BroadcastStats bs = uidStats.valueAt(ip);
1245 pw.print(" ");
1246 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1247 UserHandle.formatUid(pw, bs.mUid);
1248 pw.print(":");
1249 pw.print(bs.mPackageName);
1250 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1251 pw.print(" running, "); pw.print(bs.numWakeup);
1252 pw.println(" wakeups:");
1253 tmpFilters.clear();
1254 for (int is=0; is<bs.filterStats.size(); is++) {
1255 tmpFilters.add(bs.filterStats.valueAt(is));
1256 }
1257 Collections.sort(tmpFilters, comparator);
1258 for (int i=0; i<tmpFilters.size(); i++) {
1259 FilterStats fs = tmpFilters.get(i);
1260 pw.print(" ");
1261 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1262 TimeUtils.formatDuration(fs.aggregateTime, pw);
1263 pw.print(" "); pw.print(fs.numWakeup);
1264 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001265 pw.print(" alarms, last ");
1266 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1267 pw.println(":");
1268 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001269 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001270 pw.println();
1271 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001272 }
1273 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001274
1275 if (WAKEUP_STATS) {
1276 pw.println();
1277 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001278 long last = -1;
1279 for (WakeupEvent event : mRecentWakeups) {
1280 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1281 pw.print('|');
1282 if (last < 0) {
1283 pw.print('0');
1284 } else {
1285 pw.print(event.when - last);
1286 }
1287 last = event.when;
1288 pw.print('|'); pw.print(event.uid);
1289 pw.print('|'); pw.print(event.action);
1290 pw.println();
1291 }
1292 pw.println();
1293 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 }
1295 }
1296
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001297 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001298 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
1299 PrintWriter pw = new PrintWriter(bs);
1300 final long nowRTC = System.currentTimeMillis();
1301 final long nowELAPSED = SystemClock.elapsedRealtime();
1302 final int NZ = mAlarmBatches.size();
1303 for (int iz = 0; iz < NZ; iz++) {
1304 Batch bz = mAlarmBatches.get(iz);
1305 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001306 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001307 pw.flush();
1308 Slog.v(TAG, bs.toString());
1309 bs.reset();
1310 }
1311 }
1312
1313 private boolean validateConsistencyLocked() {
1314 if (DEBUG_VALIDATE) {
1315 long lastTime = Long.MIN_VALUE;
1316 final int N = mAlarmBatches.size();
1317 for (int i = 0; i < N; i++) {
1318 Batch b = mAlarmBatches.get(i);
1319 if (b.start >= lastTime) {
1320 // duplicate start times are okay because of standalone batches
1321 lastTime = b.start;
1322 } else {
1323 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001324 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1325 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001326 return false;
1327 }
1328 }
1329 }
1330 return true;
1331 }
1332
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001333 private Batch findFirstWakeupBatchLocked() {
1334 final int N = mAlarmBatches.size();
1335 for (int i = 0; i < N; i++) {
1336 Batch b = mAlarmBatches.get(i);
1337 if (b.hasWakeups()) {
1338 return b;
1339 }
1340 }
1341 return null;
1342 }
1343
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001344 long getNextWakeFromIdleTimeImpl() {
1345 synchronized (mLock) {
1346 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
1347 }
1348 }
1349
1350 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001351 synchronized (mLock) {
1352 return mNextAlarmClockForUser.get(userId);
1353 }
1354 }
1355
1356 /**
1357 * Recomputes the next alarm clock for all users.
1358 */
1359 private void updateNextAlarmClockLocked() {
1360 if (!mNextAlarmClockMayChange) {
1361 return;
1362 }
1363 mNextAlarmClockMayChange = false;
1364
Jose Lima235510e2014-08-13 12:50:01 -07001365 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001366 nextForUser.clear();
1367
1368 final int N = mAlarmBatches.size();
1369 for (int i = 0; i < N; i++) {
1370 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
1371 final int M = alarms.size();
1372
1373 for (int j = 0; j < M; j++) {
1374 Alarm a = alarms.get(j);
1375 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001376 final int userId = UserHandle.getUserId(a.uid);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001377
1378 if (DEBUG_ALARM_CLOCK) {
1379 Log.v(TAG, "Found AlarmClockInfo at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001380 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02001381 " for user " + userId);
1382 }
1383
1384 // Alarms and batches are sorted by time, no need to compare times here.
1385 if (nextForUser.get(userId) == null) {
1386 nextForUser.put(userId, a.alarmClock);
1387 }
1388 }
1389 }
1390 }
1391
1392 // Update mNextAlarmForUser with new values.
1393 final int NN = nextForUser.size();
1394 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07001395 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001396 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001397 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001398 if (!newAlarm.equals(currentAlarm)) {
1399 updateNextAlarmInfoForUserLocked(userId, newAlarm);
1400 }
1401 }
1402
1403 // Remove users without any alarm clocks scheduled.
1404 final int NNN = mNextAlarmClockForUser.size();
1405 for (int i = NNN - 1; i >= 0; i--) {
1406 int userId = mNextAlarmClockForUser.keyAt(i);
1407 if (nextForUser.get(userId) == null) {
1408 updateNextAlarmInfoForUserLocked(userId, null);
1409 }
1410 }
1411 }
1412
Jose Lima235510e2014-08-13 12:50:01 -07001413 private void updateNextAlarmInfoForUserLocked(int userId,
1414 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001415 if (alarmClock != null) {
1416 if (DEBUG_ALARM_CLOCK) {
1417 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001418 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02001419 }
1420 mNextAlarmClockForUser.put(userId, alarmClock);
1421 } else {
1422 if (DEBUG_ALARM_CLOCK) {
1423 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
1424 }
1425 mNextAlarmClockForUser.remove(userId);
1426 }
1427
1428 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
1429 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1430 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1431 }
1432
1433 /**
1434 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
1435 * for which alarm clocks have changed since the last call to this.
1436 *
1437 * Do not call with a lock held. Only call from mHandler's thread.
1438 *
1439 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
1440 */
1441 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07001442 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001443 pendingUsers.clear();
1444
1445 synchronized (mLock) {
1446 final int N = mPendingSendNextAlarmClockChangedForUser.size();
1447 for (int i = 0; i < N; i++) {
1448 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
1449 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
1450 }
1451 mPendingSendNextAlarmClockChangedForUser.clear();
1452 }
1453
1454 final int N = pendingUsers.size();
1455 for (int i = 0; i < N; i++) {
1456 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001457 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001458 Settings.System.putStringForUser(getContext().getContentResolver(),
1459 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01001460 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02001461 userId);
1462
1463 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
1464 new UserHandle(userId));
1465 }
1466 }
1467
1468 /**
1469 * Formats an alarm like platform/packages/apps/DeskClock used to.
1470 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01001471 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
1472 int userId) {
1473 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02001474 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
1475 return (info == null) ? "" :
1476 DateFormat.format(pattern, info.getTriggerTime()).toString();
1477 }
1478
Adam Lesinski182f73f2013-12-05 16:48:06 -08001479 void rescheduleKernelAlarmsLocked() {
1480 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
1481 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001482 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001483 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001484 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001485 final Batch firstBatch = mAlarmBatches.get(0);
Christopher Tatec83d3e42015-02-04 13:48:29 -08001486 // always update the kernel alarms, as a backstop against missed wakeups
1487 if (firstWakeup != null) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001488 mNextWakeup = firstWakeup.start;
1489 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001490 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001491 if (firstBatch != firstWakeup) {
1492 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001493 }
1494 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001495 if (mPendingNonWakeupAlarms.size() > 0) {
1496 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
1497 nextNonWakeup = mNextNonWakeupDeliveryTime;
1498 }
1499 }
Christopher Tatec83d3e42015-02-04 13:48:29 -08001500 // always update the kernel alarm, as a backstop against missed wakeups
1501 if (nextNonWakeup != 0) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001502 mNextNonWakeup = nextNonWakeup;
1503 setLocked(ELAPSED_REALTIME, nextNonWakeup);
1504 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001505 }
1506
1507 private void removeLocked(PendingIntent operation) {
1508 boolean didRemove = false;
1509 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1510 Batch b = mAlarmBatches.get(i);
1511 didRemove |= b.remove(operation);
1512 if (b.size() == 0) {
1513 mAlarmBatches.remove(i);
1514 }
1515 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001516 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1517 if (mPendingWhileIdleAlarms.get(i).operation.equals(operation)) {
1518 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1519 mPendingWhileIdleAlarms.remove(i);
1520 }
1521 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001522
1523 if (didRemove) {
1524 if (DEBUG_BATCH) {
1525 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
1526 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001527 boolean restorePending = false;
1528 if (mPendingIdleUntil != null && mPendingIdleUntil.operation.equals(operation)) {
1529 mPendingIdleUntil = null;
1530 restorePending = true;
1531 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001532 if (mNextWakeFromIdle != null && mNextWakeFromIdle.operation.equals(operation)) {
1533 mNextWakeFromIdle = null;
1534 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001535 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001536 if (restorePending) {
1537 restorePendingWhileIdleAlarmsLocked();
1538 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001539 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001540 }
1541 }
1542
1543 void removeLocked(String packageName) {
1544 boolean didRemove = false;
1545 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1546 Batch b = mAlarmBatches.get(i);
1547 didRemove |= b.remove(packageName);
1548 if (b.size() == 0) {
1549 mAlarmBatches.remove(i);
1550 }
1551 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001552 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1553 if (mPendingWhileIdleAlarms.get(i).operation.getTargetPackage().equals(packageName)) {
1554 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1555 mPendingWhileIdleAlarms.remove(i);
1556 }
1557 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001558
1559 if (didRemove) {
1560 if (DEBUG_BATCH) {
1561 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1562 }
1563 rebatchAllAlarmsLocked(true);
1564 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001565 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001566 }
1567 }
1568
1569 void removeUserLocked(int userHandle) {
1570 boolean didRemove = false;
1571 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1572 Batch b = mAlarmBatches.get(i);
1573 didRemove |= b.remove(userHandle);
1574 if (b.size() == 0) {
1575 mAlarmBatches.remove(i);
1576 }
1577 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001578 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1579 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).operation.getCreatorUid())
1580 == userHandle) {
1581 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1582 mPendingWhileIdleAlarms.remove(i);
1583 }
1584 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001585 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
1586 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
1587 mLastAllowWhileIdleDispatch.removeAt(i);
1588 }
1589 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001590
1591 if (didRemove) {
1592 if (DEBUG_BATCH) {
1593 Slog.v(TAG, "remove(user) changed bounds; rebatching");
1594 }
1595 rebatchAllAlarmsLocked(true);
1596 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001597 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001598 }
1599 }
1600
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001601 void interactiveStateChangedLocked(boolean interactive) {
1602 if (mInteractive != interactive) {
1603 mInteractive = interactive;
1604 final long nowELAPSED = SystemClock.elapsedRealtime();
1605 if (interactive) {
1606 if (mPendingNonWakeupAlarms.size() > 0) {
1607 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1608 mTotalDelayTime += thisDelayTime;
1609 if (mMaxDelayTime < thisDelayTime) {
1610 mMaxDelayTime = thisDelayTime;
1611 }
1612 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
1613 mPendingNonWakeupAlarms.clear();
1614 }
1615 if (mNonInteractiveStartTime > 0) {
1616 long dur = nowELAPSED - mNonInteractiveStartTime;
1617 if (dur > mNonInteractiveTime) {
1618 mNonInteractiveTime = dur;
1619 }
1620 }
1621 } else {
1622 mNonInteractiveStartTime = nowELAPSED;
1623 }
1624 }
1625 }
1626
Adam Lesinski182f73f2013-12-05 16:48:06 -08001627 boolean lookForPackageLocked(String packageName) {
1628 for (int i = 0; i < mAlarmBatches.size(); i++) {
1629 Batch b = mAlarmBatches.get(i);
1630 if (b.hasPackage(packageName)) {
1631 return true;
1632 }
1633 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001634 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
1635 if (mPendingWhileIdleAlarms.get(i).operation.getTargetPackage().equals(packageName)) {
1636 return true;
1637 }
1638 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001639 return false;
1640 }
1641
1642 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001643 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001644 // The kernel never triggers alarms with negative wakeup times
1645 // so we ensure they are positive.
1646 long alarmSeconds, alarmNanoseconds;
1647 if (when < 0) {
1648 alarmSeconds = 0;
1649 alarmNanoseconds = 0;
1650 } else {
1651 alarmSeconds = when / 1000;
1652 alarmNanoseconds = (when % 1000) * 1000 * 1000;
1653 }
1654
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001655 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001656 } else {
1657 Message msg = Message.obtain();
1658 msg.what = ALARM_EVENT;
1659
1660 mHandler.removeMessages(ALARM_EVENT);
1661 mHandler.sendMessageAtTime(msg, when);
1662 }
1663 }
1664
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001665 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001666 String prefix, String label, long nowRTC, long nowELAPSED, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 for (int i=list.size()-1; i>=0; i--) {
1668 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001669 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1670 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001671 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 }
1673 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001674
1675 private static final String labelForType(int type) {
1676 switch (type) {
1677 case RTC: return "RTC";
1678 case RTC_WAKEUP : return "RTC_WAKEUP";
1679 case ELAPSED_REALTIME : return "ELAPSED";
1680 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
1681 default:
1682 break;
1683 }
1684 return "--unknown--";
1685 }
1686
1687 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001688 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001689 for (int i=list.size()-1; i>=0; i--) {
1690 Alarm a = list.get(i);
1691 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001692 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1693 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001694 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001695 }
1696 }
1697
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001698 private native long init();
1699 private native void close(long nativeData);
1700 private native void set(long nativeData, int type, long seconds, long nanoseconds);
1701 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08001702 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001703 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001705 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001706 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001707 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001708 // batches are temporally sorted, so we need only pull from the
1709 // start of the list until we either empty it or hit a batch
1710 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07001711 while (mAlarmBatches.size() > 0) {
1712 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001713 if (batch.start > nowELAPSED) {
1714 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001715 break;
1716 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717
Christopher Tatee0a22b32013-07-11 14:43:13 -07001718 // We will (re)schedule some alarms now; don't let that interfere
1719 // with delivery of this current batch
1720 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001721
Christopher Tatee0a22b32013-07-11 14:43:13 -07001722 final int N = batch.size();
1723 for (int i = 0; i < N; i++) {
1724 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001725
1726 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1727 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
1728 // schedule such alarms.
1729 long lastTime = mLastAllowWhileIdleDispatch.get(alarm.uid, 0);
1730 long minTime = lastTime + mAllowWhileIdleMinTime;
1731 if (nowELAPSED < minTime) {
1732 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
1733 // alarm went off for this app. Reschedule the alarm to be in the
1734 // correct time period.
1735 alarm.whenElapsed = minTime;
1736 if (alarm.maxWhenElapsed < minTime) {
1737 alarm.maxWhenElapsed = minTime;
1738 }
1739 setImplLocked(alarm, true, false);
1740 continue;
1741 }
1742 }
1743
Christopher Tatee0a22b32013-07-11 14:43:13 -07001744 alarm.count = 1;
1745 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001746 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1747 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
1748 alarm.tag);
1749 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001750 if (mPendingIdleUntil == alarm) {
1751 mPendingIdleUntil = null;
1752 rebatchAllAlarmsLocked(false);
1753 restorePendingWhileIdleAlarmsLocked();
1754 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001755 if (mNextWakeFromIdle == alarm) {
1756 mNextWakeFromIdle = null;
1757 rebatchAllAlarmsLocked(false);
1758 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001759
1760 // Recurring alarms may have passed several alarm intervals while the
1761 // phone was asleep or off, so pass a trigger count when sending them.
1762 if (alarm.repeatInterval > 0) {
1763 // this adjustment will be zero if we're late by
1764 // less than one full repeat interval
1765 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
1766
1767 // Also schedule its next recurrence
1768 final long delta = alarm.count * alarm.repeatInterval;
1769 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07001770 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07001771 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001772 alarm.repeatInterval, alarm.operation, alarm.flags, true,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001773 alarm.workSource, alarm.alarmClock, alarm.uid);
Christopher Tate864d42e2014-12-02 11:48:53 -08001774 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001775
Christopher Tate864d42e2014-12-02 11:48:53 -08001776 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001777 hasWakeup = true;
1778 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001779
1780 // We removed an alarm clock. Let the caller recompute the next alarm clock.
1781 if (alarm.alarmClock != null) {
1782 mNextAlarmClockMayChange = true;
1783 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07001784 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001786
Christopher Tate1590f1e2014-10-02 17:27:57 -07001787 // This is a new alarm delivery set; bump the sequence number to indicate that
1788 // all apps' alarm delivery classes should be recalculated.
1789 mCurrentSeq++;
1790 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001791 Collections.sort(triggerList, mAlarmDispatchComparator);
1792
1793 if (localLOGV) {
1794 for (int i=0; i<triggerList.size(); i++) {
1795 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
1796 }
1797 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001798
1799 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 /**
1803 * This Comparator sorts Alarms into increasing time order.
1804 */
1805 public static class IncreasingTimeOrder implements Comparator<Alarm> {
1806 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09001807 long when1 = a1.whenElapsed;
1808 long when2 = a2.whenElapsed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 if (when1 - when2 > 0) {
1810 return 1;
1811 }
1812 if (when1 - when2 < 0) {
1813 return -1;
1814 }
1815 return 0;
1816 }
1817 }
1818
1819 private static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001820 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001821 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001822 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001823 public final PendingIntent operation;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001824 public final String tag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001825 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001826 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001827 public final AlarmManager.AlarmClockInfo alarmClock;
1828 public final int uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 public int count;
1830 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07001831 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001832 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001833 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07001835 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001836
Christopher Tate3e04b472013-10-21 17:51:31 -07001837 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001838 long _interval, PendingIntent _op, WorkSource _ws, int _flags,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001839 AlarmManager.AlarmClockInfo _info, int _uid) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001840 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001841 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001842 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
1843 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001844 when = _when;
1845 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07001846 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001847 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001848 repeatInterval = _interval;
1849 operation = _op;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001850 tag = makeTag(_op, _type);
David Christieebe51fc2013-07-26 13:23:29 -07001851 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001852 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001853 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001854 uid = _uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001856
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001857 public static String makeTag(PendingIntent pi, int type) {
1858 return pi.getTag(type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
1859 ? "*walarm*:" : "*alarm*:");
1860 }
1861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001863 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001864 StringBuilder sb = new StringBuilder(128);
1865 sb.append("Alarm{");
1866 sb.append(Integer.toHexString(System.identityHashCode(this)));
1867 sb.append(" type ");
1868 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001869 sb.append(" when ");
1870 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001871 sb.append(" ");
1872 sb.append(operation.getTargetPackage());
1873 sb.append('}');
1874 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 }
1876
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001877 public void dump(PrintWriter pw, String prefix, long nowRTC, long nowELAPSED,
1878 SimpleDateFormat sdf) {
1879 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
1880 pw.print(prefix); pw.print("tag="); pw.println(tag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001881 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001882 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
1883 nowELAPSED, pw);
1884 if (isRtc) {
1885 pw.print(" when="); pw.print(sdf.format(new Date(when)));
1886 } else {
1887 pw.print(" when="); TimeUtils.formatDuration(when, nowELAPSED, pw);
1888 }
1889 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001890 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001891 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001892 pw.print(" count="); pw.print(count);
1893 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001894 if (alarmClock != null) {
1895 pw.print(prefix); pw.println("Alarm clock:");
1896 pw.print(prefix); pw.print(" triggerTime=");
1897 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
1898 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
1899 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001900 pw.print(prefix); pw.print("operation="); pw.println(operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 }
1902 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001903
Christopher Tatee0a22b32013-07-11 14:43:13 -07001904 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
1905 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07001906 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
1907 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001908 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07001909 break;
1910 }
1911
Christopher Tatee0a22b32013-07-11 14:43:13 -07001912 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07001913 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
1914 Alarm a = b.alarms.get(nextAlarm);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001915 WakeupEvent e = new WakeupEvent(nowRTC,
1916 a.operation.getCreatorUid(),
1917 a.operation.getIntent().getAction());
1918 mRecentWakeups.add(e);
1919 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001920 }
1921 }
1922
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001923 long currentNonWakeupFuzzLocked(long nowELAPSED) {
1924 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
1925 if (timeSinceOn < 5*60*1000) {
1926 // If the screen has been off for 5 minutes, only delay by at most two minutes.
1927 return 2*60*1000;
1928 } else if (timeSinceOn < 30*60*1000) {
1929 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
1930 return 15*60*1000;
1931 } else {
1932 // Otherwise, we will delay by at most an hour.
1933 return 60*60*1000;
1934 }
1935 }
1936
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001937 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001938 if (duration < 15*60*1000) {
1939 // If the duration until the time is less than 15 minutes, the maximum fuzz
1940 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001941 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001942 } else if (duration < 90*60*1000) {
1943 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
1944 return 15*60*1000;
1945 } else {
1946 // Otherwise, we will fuzz by at most half an hour.
1947 return 30*60*1000;
1948 }
1949 }
1950
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001951 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
1952 if (mInteractive) {
1953 return false;
1954 }
1955 if (mLastAlarmDeliveryTime <= 0) {
1956 return false;
1957 }
minho.choo649acab2014-12-12 16:13:55 +09001958 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001959 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
1960 // and the next delivery time is in the past, then just deliver them all. This
1961 // avoids bugs where we get stuck in a loop trying to poll for alarms.
1962 return false;
1963 }
1964 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
1965 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
1966 }
1967
1968 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
1969 mLastAlarmDeliveryTime = nowELAPSED;
1970 for (int i=0; i<triggerList.size(); i++) {
1971 Alarm alarm = triggerList.get(i);
1972 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07001973 if (localLOGV) {
1974 Slog.v(TAG, "sending alarm " + alarm);
1975 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07001976 if (RECORD_ALARMS_IN_HISTORY) {
1977 if (alarm.workSource != null && alarm.workSource.size() > 0) {
1978 for (int wi=0; wi<alarm.workSource.size(); wi++) {
1979 ActivityManagerNative.noteAlarmStart(
1980 alarm.operation, alarm.workSource.get(wi), alarm.tag);
1981 }
1982 } else {
1983 ActivityManagerNative.noteAlarmStart(
1984 alarm.operation, -1, alarm.tag);
1985 }
1986 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001987 alarm.operation.send(getContext(), 0,
1988 mBackgroundIntent.putExtra(
1989 Intent.EXTRA_ALARM_COUNT, alarm.count),
1990 mResultReceiver, mHandler);
1991
1992 // we have an active broadcast so stay awake.
1993 if (mBroadcastRefCount == 0) {
1994 setWakelockWorkSource(alarm.operation, alarm.workSource,
1995 alarm.type, alarm.tag, true);
1996 mWakeLock.acquire();
1997 }
1998 final InFlight inflight = new InFlight(AlarmManagerService.this,
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001999 alarm.operation, alarm.workSource, alarm.type, alarm.tag, nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002000 mInFlight.add(inflight);
2001 mBroadcastRefCount++;
2002
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002003 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
2004 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
2005 mLastAllowWhileIdleDispatch.put(alarm.uid, nowELAPSED);
2006 }
2007
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002008 final BroadcastStats bs = inflight.mBroadcastStats;
2009 bs.count++;
2010 if (bs.nesting == 0) {
2011 bs.nesting = 1;
2012 bs.startTime = nowELAPSED;
2013 } else {
2014 bs.nesting++;
2015 }
2016 final FilterStats fs = inflight.mFilterStats;
2017 fs.count++;
2018 if (fs.nesting == 0) {
2019 fs.nesting = 1;
2020 fs.startTime = nowELAPSED;
2021 } else {
2022 fs.nesting++;
2023 }
2024 if (alarm.type == ELAPSED_REALTIME_WAKEUP
2025 || alarm.type == RTC_WAKEUP) {
2026 bs.numWakeup++;
2027 fs.numWakeup++;
2028 if (alarm.workSource != null && alarm.workSource.size() > 0) {
2029 for (int wi=0; wi<alarm.workSource.size(); wi++) {
2030 ActivityManagerNative.noteWakeupAlarm(
2031 alarm.operation, alarm.workSource.get(wi),
Dianne Hackborn1e383822015-04-10 14:02:33 -07002032 alarm.workSource.getName(wi), alarm.tag);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002033 }
2034 } else {
2035 ActivityManagerNative.noteWakeupAlarm(
Dianne Hackborn1e383822015-04-10 14:02:33 -07002036 alarm.operation, -1, null, alarm.tag);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002037 }
2038 }
2039 } catch (PendingIntent.CanceledException e) {
2040 if (alarm.repeatInterval > 0) {
2041 // This IntentSender is no longer valid, but this
2042 // is a repeating alarm, so toss the hoser.
2043 removeImpl(alarm.operation);
2044 }
2045 } catch (RuntimeException e) {
2046 Slog.w(TAG, "Failure sending alarm.", e);
2047 }
2048 }
2049 }
2050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051 private class AlarmThread extends Thread
2052 {
2053 public AlarmThread()
2054 {
2055 super("AlarmManager");
2056 }
2057
2058 public void run()
2059 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002060 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2061
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002062 while (true)
2063 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002064 int result = waitForAlarm(mNativeData);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002065
2066 triggerList.clear();
2067
Dianne Hackbornc3527222015-05-13 14:03:20 -07002068 final long nowRTC = System.currentTimeMillis();
2069 final long nowELAPSED = SystemClock.elapsedRealtime();
2070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002072 // The kernel can give us spurious time change notifications due to
2073 // small adjustments it makes internally; we want to filter those out.
2074 final long lastTimeChangeClockTime;
2075 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07002076 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002077 lastTimeChangeClockTime = mLastTimeChangeClockTime;
2078 expectedClockTime = lastTimeChangeClockTime
2079 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07002080 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002081 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-500)
2082 || nowRTC > (expectedClockTime+500)) {
2083 // The change is by at least +/- 500 ms (or this is the first change),
2084 // let's do it!
2085 if (DEBUG_BATCH) {
2086 Slog.v(TAG, "Time changed notification from kernel; rebatching");
2087 }
2088 removeImpl(mTimeTickSender);
2089 rebatchAllAlarms();
2090 mClockReceiver.scheduleTimeTickEvent();
2091 synchronized (mLock) {
2092 mNumTimeChanged++;
2093 mLastTimeChangeClockTime = nowRTC;
2094 mLastTimeChangeRealtime = nowELAPSED;
2095 }
2096 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
2097 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
2098 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2099 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
2100
2101 // The world has changed on us, so we need to re-evaluate alarms
2102 // regardless of whether the kernel has told us one went off.
2103 result |= IS_WAKEUP_MASK;
2104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002105 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002106
Dianne Hackbornc3527222015-05-13 14:03:20 -07002107 if (result != TIME_CHANGED_MASK) {
2108 // If this was anything besides just a time change, then figure what if
2109 // anything to do about alarms.
2110 synchronized (mLock) {
2111 if (localLOGV) Slog.v(
2112 TAG, "Checking for alarms... rtc=" + nowRTC
2113 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07002114
Dianne Hackbornc3527222015-05-13 14:03:20 -07002115 if (WAKEUP_STATS) {
2116 if ((result & IS_WAKEUP_MASK) != 0) {
2117 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
2118 int n = 0;
2119 for (WakeupEvent event : mRecentWakeups) {
2120 if (event.when > newEarliest) break;
2121 n++; // number of now-stale entries at the list head
2122 }
2123 for (int i = 0; i < n; i++) {
2124 mRecentWakeups.remove();
2125 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002126
Dianne Hackbornc3527222015-05-13 14:03:20 -07002127 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002128 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002129 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002130
2131 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2132 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
2133 // if there are no wakeup alarms and the screen is off, we can
2134 // delay what we have so far until the future.
2135 if (mPendingNonWakeupAlarms.size() == 0) {
2136 mStartCurrentDelayTime = nowELAPSED;
2137 mNextNonWakeupDeliveryTime = nowELAPSED
2138 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
2139 }
2140 mPendingNonWakeupAlarms.addAll(triggerList);
2141 mNumDelayedAlarms += triggerList.size();
2142 rescheduleKernelAlarmsLocked();
2143 updateNextAlarmClockLocked();
2144 } else {
2145 // now deliver the alarm intents; if there are pending non-wakeup
2146 // alarms, we need to merge them in to the list. note we don't
2147 // just deliver them first because we generally want non-wakeup
2148 // alarms delivered after wakeup alarms.
2149 rescheduleKernelAlarmsLocked();
2150 updateNextAlarmClockLocked();
2151 if (mPendingNonWakeupAlarms.size() > 0) {
2152 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
2153 triggerList.addAll(mPendingNonWakeupAlarms);
2154 Collections.sort(triggerList, mAlarmDispatchComparator);
2155 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2156 mTotalDelayTime += thisDelayTime;
2157 if (mMaxDelayTime < thisDelayTime) {
2158 mMaxDelayTime = thisDelayTime;
2159 }
2160 mPendingNonWakeupAlarms.clear();
2161 }
2162 deliverAlarmsLocked(triggerList, nowELAPSED);
2163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002164 }
2165 }
2166 }
2167 }
2168 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002169
David Christieebe51fc2013-07-26 13:23:29 -07002170 /**
2171 * Attribute blame for a WakeLock.
2172 * @param pi PendingIntent to attribute blame to if ws is null.
2173 * @param ws WorkSource to attribute blame.
2174 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002175 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
2176 boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07002177 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002178 final boolean unimportant = pi == mTimeTickSender;
2179 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002180 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002181 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002182 } else {
2183 mWakeLock.setHistoryTag(null);
2184 }
2185 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07002186 if (ws != null) {
2187 mWakeLock.setWorkSource(ws);
2188 return;
2189 }
2190
Christopher Tatec4a07d12012-04-06 14:19:13 -07002191 final int uid = ActivityManagerNative.getDefault()
2192 .getUidForIntentSender(pi.getTarget());
2193 if (uid >= 0) {
2194 mWakeLock.setWorkSource(new WorkSource(uid));
2195 return;
2196 }
2197 } catch (Exception e) {
2198 }
2199
2200 // Something went wrong; fall back to attributing the lock to the OS
2201 mWakeLock.setWorkSource(null);
2202 }
2203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002204 private class AlarmHandler extends Handler {
2205 public static final int ALARM_EVENT = 1;
2206 public static final int MINUTE_CHANGE_EVENT = 2;
2207 public static final int DATE_CHANGE_EVENT = 3;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002208 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002209
2210 public AlarmHandler() {
2211 }
2212
2213 public void handleMessage(Message msg) {
2214 if (msg.what == ALARM_EVENT) {
2215 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2216 synchronized (mLock) {
2217 final long nowRTC = System.currentTimeMillis();
Christopher Tatee0a22b32013-07-11 14:43:13 -07002218 final long nowELAPSED = SystemClock.elapsedRealtime();
2219 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002220 updateNextAlarmClockLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002221 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002223 // now trigger the alarms without the lock held
Dianne Hackborn390517b2013-05-30 15:03:32 -07002224 for (int i=0; i<triggerList.size(); i++) {
2225 Alarm alarm = triggerList.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002226 try {
2227 alarm.operation.send();
2228 } catch (PendingIntent.CanceledException e) {
2229 if (alarm.repeatInterval > 0) {
2230 // This IntentSender is no longer valid, but this
2231 // is a repeating alarm, so toss the hoser.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002232 removeImpl(alarm.operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002233 }
2234 }
2235 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002236 } else if (msg.what == SEND_NEXT_ALARM_CLOCK_CHANGED) {
2237 sendNextAlarmClockChanged();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002238 }
2239 }
2240 }
2241
2242 class ClockReceiver extends BroadcastReceiver {
2243 public ClockReceiver() {
2244 IntentFilter filter = new IntentFilter();
2245 filter.addAction(Intent.ACTION_TIME_TICK);
2246 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002247 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002248 }
2249
2250 @Override
2251 public void onReceive(Context context, Intent intent) {
2252 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07002253 if (DEBUG_BATCH) {
2254 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
2255 }
2256 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002257 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
2258 // Since the kernel does not keep track of DST, we need to
2259 // reset the TZ information at the beginning of each day
2260 // based off of the current Zone gmt offset + userspace tracked
2261 // daylight savings information.
2262 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02002263 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002264 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07002265 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002266 }
2267 }
2268
2269 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07002270 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09002271 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07002272
2273 // Schedule this event for the amount of time that it would take to get to
2274 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09002275 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07002276
David Christieebe51fc2013-07-26 13:23:29 -07002277 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002278 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002279 0, mTimeTickSender, AlarmManager.FLAG_STANDALONE, workSource, null,
2280 Process.myUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002281 }
Christopher Tate385e4982013-07-23 18:22:29 -07002282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002283 public void scheduleDateChangedEvent() {
2284 Calendar calendar = Calendar.getInstance();
2285 calendar.setTimeInMillis(System.currentTimeMillis());
2286 calendar.set(Calendar.HOUR, 0);
2287 calendar.set(Calendar.MINUTE, 0);
2288 calendar.set(Calendar.SECOND, 0);
2289 calendar.set(Calendar.MILLISECOND, 0);
2290 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07002291
2292 final WorkSource workSource = null; // Let system take blame for date change events.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002293 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002294 AlarmManager.FLAG_STANDALONE, workSource, null, Process.myUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002295 }
2296 }
2297
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002298 class InteractiveStateReceiver extends BroadcastReceiver {
2299 public InteractiveStateReceiver() {
2300 IntentFilter filter = new IntentFilter();
2301 filter.addAction(Intent.ACTION_SCREEN_OFF);
2302 filter.addAction(Intent.ACTION_SCREEN_ON);
2303 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
2304 getContext().registerReceiver(this, filter);
2305 }
2306
2307 @Override
2308 public void onReceive(Context context, Intent intent) {
2309 synchronized (mLock) {
2310 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
2311 }
2312 }
2313 }
2314
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002315 class UninstallReceiver extends BroadcastReceiver {
2316 public UninstallReceiver() {
2317 IntentFilter filter = new IntentFilter();
2318 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2319 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002320 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002321 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08002322 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002323 // Register for events related to sdcard installation.
2324 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08002325 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002326 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002327 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002328 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002329 }
2330
2331 @Override
2332 public void onReceive(Context context, Intent intent) {
2333 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002334 String action = intent.getAction();
2335 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002336 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
2337 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
2338 for (String packageName : pkgList) {
2339 if (lookForPackageLocked(packageName)) {
2340 setResultCode(Activity.RESULT_OK);
2341 return;
2342 }
2343 }
2344 return;
2345 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002346 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002347 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
2348 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
2349 if (userHandle >= 0) {
2350 removeUserLocked(userHandle);
2351 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002352 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
2353 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
2354 if (uid >= 0) {
2355 mLastAllowWhileIdleDispatch.delete(uid);
2356 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002357 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08002358 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
2359 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
2360 // This package is being updated; don't kill its alarms.
2361 return;
2362 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002363 Uri data = intent.getData();
2364 if (data != null) {
2365 String pkg = data.getSchemeSpecificPart();
2366 if (pkg != null) {
2367 pkgList = new String[]{pkg};
2368 }
2369 }
2370 }
2371 if (pkgList != null && (pkgList.length > 0)) {
2372 for (String pkg : pkgList) {
2373 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07002374 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002375 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
2376 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
2377 if (uidStats.remove(pkg) != null) {
2378 if (uidStats.size() <= 0) {
2379 mBroadcastStats.removeAt(i);
2380 }
2381 }
2382 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002383 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002384 }
2385 }
2386 }
2387 }
2388
2389 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002390 String pkg = pi.getCreatorPackage();
2391 int uid = pi.getCreatorUid();
2392 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
2393 if (uidStats == null) {
2394 uidStats = new ArrayMap<String, BroadcastStats>();
2395 mBroadcastStats.put(uid, uidStats);
2396 }
2397 BroadcastStats bs = uidStats.get(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002398 if (bs == null) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002399 bs = new BroadcastStats(uid, pkg);
2400 uidStats.put(pkg, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002401 }
2402 return bs;
2403 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002404
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002405 class ResultReceiver implements PendingIntent.OnFinished {
2406 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
2407 String resultData, Bundle resultExtras) {
2408 synchronized (mLock) {
Dianne Hackborn81038902012-11-26 17:04:09 -08002409 InFlight inflight = null;
2410 for (int i=0; i<mInFlight.size(); i++) {
2411 if (mInFlight.get(i).mPendingIntent == pi) {
2412 inflight = mInFlight.remove(i);
2413 break;
2414 }
2415 }
2416 if (inflight != null) {
2417 final long nowELAPSED = SystemClock.elapsedRealtime();
2418 BroadcastStats bs = inflight.mBroadcastStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002419 bs.nesting--;
2420 if (bs.nesting <= 0) {
2421 bs.nesting = 0;
Dianne Hackborn81038902012-11-26 17:04:09 -08002422 bs.aggregateTime += nowELAPSED - bs.startTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002423 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002424 FilterStats fs = inflight.mFilterStats;
2425 fs.nesting--;
2426 if (fs.nesting <= 0) {
2427 fs.nesting = 0;
2428 fs.aggregateTime += nowELAPSED - fs.startTime;
2429 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07002430 if (RECORD_ALARMS_IN_HISTORY) {
2431 if (inflight.mWorkSource != null && inflight.mWorkSource.size() > 0) {
2432 for (int wi=0; wi<inflight.mWorkSource.size(); wi++) {
2433 ActivityManagerNative.noteAlarmFinish(
2434 pi, inflight.mWorkSource.get(wi), inflight.mTag);
2435 }
2436 } else {
2437 ActivityManagerNative.noteAlarmFinish(
2438 pi, -1, inflight.mTag);
2439 }
2440 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002441 } else {
2442 mLog.w("No in-flight alarm for " + pi + " " + intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002443 }
2444 mBroadcastRefCount--;
2445 if (mBroadcastRefCount == 0) {
2446 mWakeLock.release();
Dianne Hackborn81038902012-11-26 17:04:09 -08002447 if (mInFlight.size() > 0) {
2448 mLog.w("Finished all broadcasts with " + mInFlight.size()
2449 + " remaining inflights");
2450 for (int i=0; i<mInFlight.size(); i++) {
2451 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
2452 }
2453 mInFlight.clear();
2454 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002455 } else {
2456 // the next of our alarms is now in flight. reattribute the wakelock.
Dianne Hackborn81038902012-11-26 17:04:09 -08002457 if (mInFlight.size() > 0) {
David Christieebe51fc2013-07-26 13:23:29 -07002458 InFlight inFlight = mInFlight.get(0);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08002459 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002460 inFlight.mAlarmType, inFlight.mTag, false);
Christopher Tatec4a07d12012-04-06 14:19:13 -07002461 } else {
2462 // should never happen
Dianne Hackborn81038902012-11-26 17:04:09 -08002463 mLog.w("Alarm wakelock still held but sent queue empty");
Christopher Tatec4a07d12012-04-06 14:19:13 -07002464 mWakeLock.setWorkSource(null);
2465 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002466 }
2467 }
2468 }
2469 }
2470}