blob: 839b87a7afdedffd07ccfdb0d431d37656fc9538 [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;
Dianne Hackborna750a632015-06-16 17:18:23 -070023import android.app.BroadcastOptions;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.app.IAlarmManager;
25import android.app.PendingIntent;
26import android.content.BroadcastReceiver;
Dianne Hackborna750a632015-06-16 17:18:23 -070027import android.content.ContentResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.content.Context;
29import android.content.Intent;
30import android.content.IntentFilter;
31import android.content.pm.PackageManager;
Dianne Hackborna750a632015-06-16 17:18:23 -070032import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.net.Uri;
34import android.os.Binder;
35import android.os.Bundle;
36import android.os.Handler;
Adam Lesinski182f73f2013-12-05 16:48:06 -080037import android.os.IBinder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.os.Message;
39import android.os.PowerManager;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070040import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.os.SystemClock;
42import android.os.SystemProperties;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070043import android.os.UserHandle;
Christopher Tatec4a07d12012-04-06 14:19:13 -070044import android.os.WorkSource;
Adrian Roosc42a1e12014-07-07 23:35:53 +020045import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.text.TextUtils;
Adrian Roosc42a1e12014-07-07 23:35:53 +020047import android.text.format.DateFormat;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080048import android.util.ArrayMap;
Dianne Hackborna750a632015-06-16 17:18:23 -070049import android.util.KeyValueListParser;
Adrian Roosc42a1e12014-07-07 23:35:53 +020050import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080051import android.util.Slog;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080052import android.util.SparseArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +020053import android.util.SparseBooleanArray;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -070054import android.util.SparseLongArray;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070055import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056
Christopher Tate4cb338d2013-07-26 13:11:31 -070057import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import java.io.FileDescriptor;
59import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070060import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -080062import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import java.util.Calendar;
64import java.util.Collections;
65import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -050066import java.util.Date;
Christopher Tate1590f1e2014-10-02 17:27:57 -070067import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -070068import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +020069import java.util.Locale;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070070import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import java.util.TimeZone;
John Spurlock604a5ee2015-06-01 12:27:22 -040072import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073
Christopher Tatee0a22b32013-07-11 14:43:13 -070074import static android.app.AlarmManager.RTC_WAKEUP;
75import static android.app.AlarmManager.RTC;
76import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
77import static android.app.AlarmManager.ELAPSED_REALTIME;
78
Dianne Hackborn81038902012-11-26 17:04:09 -080079import com.android.internal.util.LocalLog;
80
Adam Lesinski182f73f2013-12-05 16:48:06 -080081class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -070082 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
83 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -080084 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -070085 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -080086 static final int TIME_CHANGED_MASK = 1 << 16;
87 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -080088
Christopher Tatee0a22b32013-07-11 14:43:13 -070089 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -080090 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -080091
Adam Lesinski182f73f2013-12-05 16:48:06 -080092 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -080093 static final boolean localLOGV = false;
94 static final boolean DEBUG_BATCH = localLOGV || false;
95 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +020096 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -070097 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Adam Lesinski182f73f2013-12-05 16:48:06 -080098 static final int ALARM_EVENT = 1;
99 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200100
Adam Lesinski182f73f2013-12-05 16:48:06 -0800101 static final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800103 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104
Adam Lesinski182f73f2013-12-05 16:48:06 -0800105 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700106
Adrian Roosc42a1e12014-07-07 23:35:53 +0200107 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT = new Intent(
108 AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED);
109
Adam Lesinski182f73f2013-12-05 16:48:06 -0800110 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800111
Adam Lesinski182f73f2013-12-05 16:48:06 -0800112 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800113
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800114 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800115 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700116 private long mNextNonWakeup;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800117 int mBroadcastRefCount = 0;
118 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700119 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700120 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
121 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800122 final AlarmHandler mHandler = new AlarmHandler();
123 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700124 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125 private UninstallReceiver mUninstallReceiver;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800126 final ResultReceiver mResultReceiver = new ResultReceiver();
127 PendingIntent mTimeTickSender;
128 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700129 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700130 boolean mInteractive = true;
131 long mNonInteractiveStartTime;
132 long mNonInteractiveTime;
133 long mLastAlarmDeliveryTime;
134 long mStartCurrentDelayTime;
135 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700136 long mLastTimeChangeClockTime;
137 long mLastTimeChangeRealtime;
Dianne Hackborna750a632015-06-16 17:18:23 -0700138 long mAllowWhileIdleMinTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700139 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800140
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700141 /**
142 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
143 * used to determine the earliest we can dispatch the next such alarm.
144 */
145 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
146
Dianne Hackborna750a632015-06-16 17:18:23 -0700147 /**
148 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
149 */
150 Bundle mIdleOptions;
151
Jose Lima235510e2014-08-13 12:50:01 -0700152 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
153 new SparseArray<>();
154 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
155 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200156 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
157 new SparseBooleanArray();
158 private boolean mNextAlarmClockMayChange;
159
160 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700161 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
162 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200163
Dianne Hackborna750a632015-06-16 17:18:23 -0700164 /**
165 * All times are in milliseconds. These constants are kept synchronized with the system
166 * global Settings. Any access to this class or its fields should be done while
167 * holding the AlarmManagerService.mLock lock.
168 */
169 private final class Constants extends ContentObserver {
170 // Key names stored in the settings value.
171 private static final String KEY_MIN_FUTURITY = "min_futurity";
172 private static final String KEY_MIN_INTERVAL = "min_interval";
173 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
174 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
175 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
176 = "allow_while_idle_whitelist_duration";
177
178 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
179 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
180 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = 60*1000;
181 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 15*60*1000;
182 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
183
184 // Minimum futurity of a new alarm
185 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
186
187 // Minimum alarm recurrence interval
188 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
189
190 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
191 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
192
193 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
194 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
195
196 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
197 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
198 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
199
200 private ContentResolver mResolver;
201 private final KeyValueListParser mParser = new KeyValueListParser(',');
202 private long mLastAllowWhileIdleWhitelistDuration = -1;
203
204 public Constants(Handler handler) {
205 super(handler);
206 updateAllowWhileIdleMinTimeLocked();
207 updateAllowWhileIdleWhitelistDurationLocked();
208 }
209
210 public void start(ContentResolver resolver) {
211 mResolver = resolver;
212 mResolver.registerContentObserver(Settings.Global.getUriFor(
213 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
214 updateConstants();
215 }
216
217 public void updateAllowWhileIdleMinTimeLocked() {
218 mAllowWhileIdleMinTime = mPendingIdleUntil != null
219 ? ALLOW_WHILE_IDLE_LONG_TIME : ALLOW_WHILE_IDLE_SHORT_TIME;
220 }
221
222 public void updateAllowWhileIdleWhitelistDurationLocked() {
223 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
224 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
225 BroadcastOptions opts = BroadcastOptions.makeBasic();
226 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
227 mIdleOptions = opts.toBundle();
228 }
229 }
230
231 @Override
232 public void onChange(boolean selfChange, Uri uri) {
233 updateConstants();
234 }
235
236 private void updateConstants() {
237 synchronized (mLock) {
238 try {
239 mParser.setString(Settings.Global.getString(mResolver,
240 Settings.Global.ALARM_MANAGER_CONSTANTS));
241 } catch (IllegalArgumentException e) {
242 // Failed to parse the settings string, log this and move on
243 // with defaults.
244 Slog.e(TAG, "Bad device idle settings", e);
245 }
246
247 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
248 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
249 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
250 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
251 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
252 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
253 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
254 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
255 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
256
257 updateAllowWhileIdleMinTimeLocked();
258 updateAllowWhileIdleWhitelistDurationLocked();
259 }
260 }
261
262 void dump(PrintWriter pw) {
263 pw.println(" Settings:");
264
265 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
266 TimeUtils.formatDuration(MIN_FUTURITY, pw);
267 pw.println();
268
269 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
270 TimeUtils.formatDuration(MIN_INTERVAL, pw);
271 pw.println();
272
273 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
274 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
275 pw.println();
276
277 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
278 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
279 pw.println();
280
281 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
282 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
283 pw.println();
284 }
285 }
286
287 final Constants mConstants;
288
Christopher Tate1590f1e2014-10-02 17:27:57 -0700289 // Alarm delivery ordering bookkeeping
290 static final int PRIO_TICK = 0;
291 static final int PRIO_WAKEUP = 1;
292 static final int PRIO_NORMAL = 2;
293
Dianne Hackborna750a632015-06-16 17:18:23 -0700294 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700295 int seq;
296 int priority;
297
298 PriorityClass() {
299 seq = mCurrentSeq - 1;
300 priority = PRIO_NORMAL;
301 }
302 }
303
Dianne Hackborna750a632015-06-16 17:18:23 -0700304 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700305 int mCurrentSeq = 0;
306
Dianne Hackborna750a632015-06-16 17:18:23 -0700307 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700308 public long when;
309 public int uid;
310 public String action;
311
312 public WakeupEvent(long theTime, int theUid, String theAction) {
313 when = theTime;
314 uid = theUid;
315 action = theAction;
316 }
317 }
318
Adam Lesinski182f73f2013-12-05 16:48:06 -0800319 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
320 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700321
Adrian Roosc42a1e12014-07-07 23:35:53 +0200322 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700323 long start; // These endpoints are always in ELAPSED
324 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700325 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700326
327 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
328
329 Batch() {
330 start = 0;
331 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700332 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700333 }
334
335 Batch(Alarm seed) {
336 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700337 end = seed.maxWhenElapsed;
338 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700339 alarms.add(seed);
340 }
341
342 int size() {
343 return alarms.size();
344 }
345
346 Alarm get(int index) {
347 return alarms.get(index);
348 }
349
350 boolean canHold(long whenElapsed, long maxWhen) {
351 return (end >= whenElapsed) && (start <= maxWhen);
352 }
353
354 boolean add(Alarm alarm) {
355 boolean newStart = false;
356 // narrows the batch if necessary; presumes that canHold(alarm) is true
357 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
358 if (index < 0) {
359 index = 0 - index - 1;
360 }
361 alarms.add(index, alarm);
362 if (DEBUG_BATCH) {
363 Slog.v(TAG, "Adding " + alarm + " to " + this);
364 }
365 if (alarm.whenElapsed > start) {
366 start = alarm.whenElapsed;
367 newStart = true;
368 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700369 if (alarm.maxWhenElapsed < end) {
370 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700371 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700372 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700373
374 if (DEBUG_BATCH) {
375 Slog.v(TAG, " => now " + this);
376 }
377 return newStart;
378 }
379
380 boolean remove(final PendingIntent operation) {
381 boolean didRemove = false;
382 long newStart = 0; // recalculate endpoints as we go
383 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700384 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700385 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700386 Alarm alarm = alarms.get(i);
387 if (alarm.operation.equals(operation)) {
388 alarms.remove(i);
389 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200390 if (alarm.alarmClock != null) {
391 mNextAlarmClockMayChange = true;
392 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700393 } else {
394 if (alarm.whenElapsed > newStart) {
395 newStart = alarm.whenElapsed;
396 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700397 if (alarm.maxWhenElapsed < newEnd) {
398 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700399 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700400 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700401 i++;
402 }
403 }
404 if (didRemove) {
405 // commit the new batch bounds
406 start = newStart;
407 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700408 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700409 }
410 return didRemove;
411 }
412
413 boolean remove(final String packageName) {
414 boolean didRemove = false;
415 long newStart = 0; // recalculate endpoints as we go
416 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700417 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700418 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700419 Alarm alarm = alarms.get(i);
420 if (alarm.operation.getTargetPackage().equals(packageName)) {
421 alarms.remove(i);
422 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200423 if (alarm.alarmClock != null) {
424 mNextAlarmClockMayChange = true;
425 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700426 } else {
427 if (alarm.whenElapsed > newStart) {
428 newStart = alarm.whenElapsed;
429 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700430 if (alarm.maxWhenElapsed < newEnd) {
431 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700432 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700433 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700434 i++;
435 }
436 }
437 if (didRemove) {
438 // commit the new batch bounds
439 start = newStart;
440 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700441 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700442 }
443 return didRemove;
444 }
445
446 boolean remove(final int userHandle) {
447 boolean didRemove = false;
448 long newStart = 0; // recalculate endpoints as we go
449 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700450 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700451 Alarm alarm = alarms.get(i);
452 if (UserHandle.getUserId(alarm.operation.getCreatorUid()) == userHandle) {
453 alarms.remove(i);
454 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200455 if (alarm.alarmClock != null) {
456 mNextAlarmClockMayChange = true;
457 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700458 } else {
459 if (alarm.whenElapsed > newStart) {
460 newStart = alarm.whenElapsed;
461 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700462 if (alarm.maxWhenElapsed < newEnd) {
463 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700464 }
465 i++;
466 }
467 }
468 if (didRemove) {
469 // commit the new batch bounds
470 start = newStart;
471 end = newEnd;
472 }
473 return didRemove;
474 }
475
476 boolean hasPackage(final String packageName) {
477 final int N = alarms.size();
478 for (int i = 0; i < N; i++) {
479 Alarm a = alarms.get(i);
480 if (a.operation.getTargetPackage().equals(packageName)) {
481 return true;
482 }
483 }
484 return false;
485 }
486
487 boolean hasWakeups() {
488 final int N = alarms.size();
489 for (int i = 0; i < N; i++) {
490 Alarm a = alarms.get(i);
491 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
492 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
493 return true;
494 }
495 }
496 return false;
497 }
498
499 @Override
500 public String toString() {
501 StringBuilder b = new StringBuilder(40);
502 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
503 b.append(" num="); b.append(size());
504 b.append(" start="); b.append(start);
505 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700506 if (flags != 0) {
507 b.append(" flgs=0x");
508 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700509 }
510 b.append('}');
511 return b.toString();
512 }
513 }
514
515 static class BatchTimeOrder implements Comparator<Batch> {
516 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800517 long when1 = b1.start;
518 long when2 = b2.start;
519 if (when1 - when2 > 0) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700520 return 1;
521 }
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800522 if (when1 - when2 < 0) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700523 return -1;
524 }
525 return 0;
526 }
527 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800528
529 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
530 @Override
531 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700532 // priority class trumps everything. TICK < WAKEUP < NORMAL
533 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
534 return -1;
535 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
536 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800537 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700538
539 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800540 if (lhs.whenElapsed < rhs.whenElapsed) {
541 return -1;
542 } else if (lhs.whenElapsed > rhs.whenElapsed) {
543 return 1;
544 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700545
546 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800547 return 0;
548 }
549 };
550
Christopher Tate1590f1e2014-10-02 17:27:57 -0700551 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
552 final int N = alarms.size();
553 for (int i = 0; i < N; i++) {
554 Alarm a = alarms.get(i);
555
556 final int alarmPrio;
557 if (Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
558 alarmPrio = PRIO_TICK;
559 } else if (a.wakeup) {
560 alarmPrio = PRIO_WAKEUP;
561 } else {
562 alarmPrio = PRIO_NORMAL;
563 }
564
565 PriorityClass packagePrio = a.priorityClass;
566 if (packagePrio == null) packagePrio = mPriorities.get(a.operation.getCreatorPackage());
567 if (packagePrio == null) {
568 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
569 mPriorities.put(a.operation.getCreatorPackage(), packagePrio);
570 }
571 a.priorityClass = packagePrio;
572
573 if (packagePrio.seq != mCurrentSeq) {
574 // first alarm we've seen in the current delivery generation from this package
575 packagePrio.priority = alarmPrio;
576 packagePrio.seq = mCurrentSeq;
577 } else {
578 // Multiple alarms from this package being delivered in this generation;
579 // bump the package's delivery class if it's warranted.
580 // TICK < WAKEUP < NORMAL
581 if (alarmPrio < packagePrio.priority) {
582 packagePrio.priority = alarmPrio;
583 }
584 }
585 }
586 }
587
Christopher Tatee0a22b32013-07-11 14:43:13 -0700588 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800589 static final long MIN_FUZZABLE_INTERVAL = 10000;
590 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700591 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
592
593 // set to null if in idle mode; while in this mode, any alarms we don't want
594 // to run during this time are placed in mPendingWhileIdleAlarms
595 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700596 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700597 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700598
Jeff Brownb880d882014-02-10 19:47:07 -0800599 public AlarmManagerService(Context context) {
600 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700601 mConstants = new Constants(mHandler);
Jeff Brownb880d882014-02-10 19:47:07 -0800602 }
603
Christopher Tatee0a22b32013-07-11 14:43:13 -0700604 static long convertToElapsed(long when, int type) {
605 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
606 if (isRtc) {
607 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
608 }
609 return when;
610 }
611
612 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
613 // calculate the end of our nominal delivery window for the alarm.
614 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
615 // Current heuristic: batchable window is 75% of either the recurrence interval
616 // [for a periodic alarm] or of the time from now to the desired delivery time,
617 // with a minimum delay/interval of 10 seconds, under which we will simply not
618 // defer the alarm.
619 long futurity = (interval == 0)
620 ? (triggerAtTime - now)
621 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700622 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700623 futurity = 0;
624 }
625 return triggerAtTime + (long)(.75 * futurity);
626 }
627
628 // returns true if the batch was added at the head
629 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
630 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
631 if (index < 0) {
632 index = 0 - index - 1;
633 }
634 list.add(index, newBatch);
635 return (index == 0);
636 }
637
Christopher Tate385e4982013-07-23 18:22:29 -0700638 // Return the index of the matching batch, or -1 if none found.
639 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700640 final int N = mAlarmBatches.size();
641 for (int i = 0; i < N; i++) {
642 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700643 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700644 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700645 }
646 }
Christopher Tate385e4982013-07-23 18:22:29 -0700647 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700648 }
649
650 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
651 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700652 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700653 rebatchAllAlarmsLocked(true);
654 }
655 }
656
657 void rebatchAllAlarmsLocked(boolean doValidate) {
658 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
659 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700660 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700661 final long nowElapsed = SystemClock.elapsedRealtime();
662 final int oldBatches = oldSet.size();
663 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
664 Batch batch = oldSet.get(batchNum);
665 final int N = batch.size();
666 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700667 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700668 }
669 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700670 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
671 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
672 + " to " + mPendingIdleUntil);
673 if (mPendingIdleUntil == null) {
674 // Somehow we lost this... we need to restore all of the pending alarms.
675 restorePendingWhileIdleAlarmsLocked();
676 }
677 }
678 rescheduleKernelAlarmsLocked();
679 updateNextAlarmClockLocked();
680 }
681
682 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
683 a.when = a.origWhen;
684 long whenElapsed = convertToElapsed(a.when, a.type);
685 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700686 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700687 // Exact
688 maxElapsed = whenElapsed;
689 } else {
690 // Not exact. Preserve any explicit window, otherwise recalculate
691 // the window based on the alarm's new futurity. Note that this
692 // reflects a policy of preferring timely to deferred delivery.
693 maxElapsed = (a.windowLength > 0)
694 ? (whenElapsed + a.windowLength)
695 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
696 }
697 a.whenElapsed = whenElapsed;
698 a.maxWhenElapsed = maxElapsed;
699 setImplLocked(a, true, doValidate);
700 }
701
702 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackborn35d54032015-04-23 10:30:43 -0700703 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700704 if (mPendingWhileIdleAlarms.size() > 0) {
705 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
706 mPendingWhileIdleAlarms = new ArrayList<>();
707 final long nowElapsed = SystemClock.elapsedRealtime();
708 for (int i=alarms.size() - 1; i >= 0; i--) {
709 Alarm a = alarms.get(i);
710 reAddAlarmLocked(a, nowElapsed, false);
711 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700712 }
Dianne Hackborn35d54032015-04-23 10:30:43 -0700713
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700714 // Make sure we are using the correct ALLOW_WHILE_IDLE min time.
Dianne Hackborna750a632015-06-16 17:18:23 -0700715 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700716
Dianne Hackborn35d54032015-04-23 10:30:43 -0700717 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700718 rescheduleKernelAlarmsLocked();
719 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -0700720
721 // And send a TIME_TICK right now, since it is important to get the UI updated.
722 try {
723 mTimeTickSender.send();
724 } catch (PendingIntent.CanceledException e) {
725 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700726 }
727
Adam Lesinski182f73f2013-12-05 16:48:06 -0800728 static final class InFlight extends Intent {
Dianne Hackborn81038902012-11-26 17:04:09 -0800729 final PendingIntent mPendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700730 final WorkSource mWorkSource;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700731 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800732 final BroadcastStats mBroadcastStats;
733 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800734 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800735
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800736 InFlight(AlarmManagerService service, PendingIntent pendingIntent, WorkSource workSource,
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700737 int alarmType, String tag, long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800738 mPendingIntent = pendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700739 mWorkSource = workSource;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700740 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800741 mBroadcastStats = service.getStatsLocked(pendingIntent);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700742 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -0800743 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700744 fs = new FilterStats(mBroadcastStats, mTag);
745 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -0800746 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700747 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -0800748 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800749 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800750 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800752
Adam Lesinski182f73f2013-12-05 16:48:06 -0800753 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -0800754 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700755 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800756
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700757 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800759 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 int numWakeup;
761 long startTime;
762 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -0800763
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700764 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800765 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700766 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800767 }
768 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700769
Adam Lesinski182f73f2013-12-05 16:48:06 -0800770 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800771 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800772 final String mPackageName;
773
774 long aggregateTime;
775 int count;
776 int numWakeup;
777 long startTime;
778 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700779 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -0800780
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800781 BroadcastStats(int uid, String packageName) {
782 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800783 mPackageName = packageName;
784 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700786
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800787 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
788 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700789
790 int mNumDelayedAlarms = 0;
791 long mTotalDelayTime = 0;
792 long mMaxDelayTime = 0;
793
Adam Lesinski182f73f2013-12-05 16:48:06 -0800794 @Override
795 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800796 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800797 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800798
799 // We have to set current TimeZone info to kernel
800 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -0800801 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800802
Adam Lesinski182f73f2013-12-05 16:48:06 -0800803 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800804 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800805
Adam Lesinski182f73f2013-12-05 16:48:06 -0800806 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700808 Intent.FLAG_RECEIVER_REGISTERED_ONLY
809 | Intent.FLAG_RECEIVER_FOREGROUND), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700810 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800811 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
812 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800813 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700814 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815
816 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -0800817 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 mClockReceiver.scheduleTimeTickEvent();
819 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700820 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 mUninstallReceiver = new UninstallReceiver();
822
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800823 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800824 AlarmThread waitThread = new AlarmThread();
825 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800827 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800829
830 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800832
833 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -0700834 public void onBootPhase(int phase) {
835 if (phase == PHASE_SYSTEM_SERVICES_READY) {
836 mConstants.start(getContext().getContentResolver());
837 }
838 }
839
840 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 protected void finalize() throws Throwable {
842 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800843 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 } finally {
845 super.finalize();
846 }
847 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700848
Adam Lesinski182f73f2013-12-05 16:48:06 -0800849 void setTimeZoneImpl(String tz) {
850 if (TextUtils.isEmpty(tz)) {
851 return;
David Christieebe51fc2013-07-26 13:23:29 -0700852 }
853
Adam Lesinski182f73f2013-12-05 16:48:06 -0800854 TimeZone zone = TimeZone.getTimeZone(tz);
855 // Prevent reentrant calls from stepping on each other when writing
856 // the time zone property
857 boolean timeZoneWasChanged = false;
858 synchronized (this) {
859 String current = SystemProperties.get(TIMEZONE_PROPERTY);
860 if (current == null || !current.equals(zone.getID())) {
861 if (localLOGV) {
862 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
863 }
864 timeZoneWasChanged = true;
865 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
866 }
867
868 // Update the kernel timezone information
869 // Kernel tracks time offsets as 'minutes west of GMT'
870 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800871 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -0800872 }
873
874 TimeZone.setDefault(null);
875
876 if (timeZoneWasChanged) {
877 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
878 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
879 intent.putExtra("time-zone", zone.getID());
880 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
881 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700883
Adam Lesinski182f73f2013-12-05 16:48:06 -0800884 void removeImpl(PendingIntent operation) {
885 if (operation == null) {
886 return;
887 }
888 synchronized (mLock) {
889 removeLocked(operation);
890 }
891 }
892
893 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700894 PendingIntent operation, int flags, WorkSource workSource,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700895 AlarmManager.AlarmClockInfo alarmClock, int callingUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896 if (operation == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800897 Slog.w(TAG, "set/setRepeating ignored because there is no intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898 return;
899 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700900
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700901 // Sanity check the window length. This will catch people mistakenly
902 // trying to pass an end-of-window timestamp rather than a duration.
903 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
904 Slog.w(TAG, "Window length " + windowLength
905 + "ms suspiciously long; limiting to 1 hour");
906 windowLength = AlarmManager.INTERVAL_HOUR;
907 }
908
Christopher Tate498c6cb2014-11-17 16:09:27 -0800909 // Sanity check the recurrence interval. This will catch people who supply
910 // seconds when the API expects milliseconds.
Dianne Hackborna750a632015-06-16 17:18:23 -0700911 final long minInterval = mConstants.MIN_INTERVAL;
912 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -0800913 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -0700914 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -0800915 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -0700916 interval = minInterval;
Christopher Tate498c6cb2014-11-17 16:09:27 -0800917 }
918
Christopher Tatee0a22b32013-07-11 14:43:13 -0700919 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
920 throw new IllegalArgumentException("Invalid alarm type " + type);
921 }
922
Christopher Tate5f221e82013-07-30 17:13:15 -0700923 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -0700924 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700925 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -0700926 + " pid=" + what);
927 triggerAtTime = 0;
928 }
929
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700930 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -0800931 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
932 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -0700933 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -0800934 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
935
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700936 final long maxElapsed;
937 if (windowLength == AlarmManager.WINDOW_EXACT) {
938 maxElapsed = triggerElapsed;
939 } else if (windowLength < 0) {
940 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700941 // Fix this window in place, so that as time approaches we don't collapse it.
942 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700943 } else {
944 maxElapsed = triggerElapsed + windowLength;
945 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700948 if (DEBUG_BATCH) {
949 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700950 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -0700951 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700952 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800953 }
Christopher Tate3e04b472013-10-21 17:51:31 -0700954 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700955 interval, operation, flags, true, workSource, alarmClock, callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956 }
957 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958
Christopher Tate3e04b472013-10-21 17:51:31 -0700959 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700960 long maxWhen, long interval, PendingIntent operation, int flags,
Jose Lima235510e2014-08-13 12:50:01 -0700961 boolean doValidate, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700962 int uid) {
Christopher Tate3e04b472013-10-21 17:51:31 -0700963 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700964 operation, workSource, flags, alarmClock, uid);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700965 removeLocked(operation);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700966 setImplLocked(a, false, doValidate);
967 }
Christopher Tateb8849c12011-02-08 13:39:01 -0800968
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700969 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
970 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700971 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700972 // The caller has given the time they want this to happen at, however we need
973 // to pull that earlier if there are existing alarms that have requested to
974 // bring us out of idle.
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700975 if (mNextWakeFromIdle != null) {
976 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700977 }
978 // Add fuzz to make the alarm go off some time before the actual desired time.
979 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700980 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700981 if (fuzz > 0) {
982 if (mRandom == null) {
983 mRandom = new Random();
984 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700985 final int delta = mRandom.nextInt(fuzz);
986 a.whenElapsed -= delta;
987 if (false) {
988 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
989 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
990 Slog.d(TAG, "Applied fuzz: " + fuzz);
991 Slog.d(TAG, "Final delta: " + delta);
992 Slog.d(TAG, "Final when: " + a.whenElapsed);
993 }
994 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700995 }
996
997 } else if (mPendingIdleUntil != null) {
998 // We currently have an idle until alarm scheduled; if the new alarm has
999 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001000 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1001 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1002 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001003 == 0) {
1004 mPendingWhileIdleAlarms.add(a);
1005 return;
1006 }
1007 }
1008
1009 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
1010 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -07001011 if (whichBatch < 0) {
1012 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001013 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014 } else {
Christopher Tate385e4982013-07-23 18:22:29 -07001015 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001016 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001017 // The start time of this batch advanced, so batch ordering may
1018 // have just been broken. Move it to where it now belongs.
1019 mAlarmBatches.remove(whichBatch);
1020 addBatchLocked(mAlarmBatches, batch);
1021 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022 }
1023
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001024 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001025 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001026 }
1027
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001028 boolean needRebatch = false;
1029
1030 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
1031 mPendingIdleUntil = a;
Dianne Hackborna750a632015-06-16 17:18:23 -07001032 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001033 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001034 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1035 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1036 mNextWakeFromIdle = a;
1037 // If this wake from idle is earlier than whatever was previously scheduled,
1038 // and we are currently idling, then we need to rebatch alarms in case the idle
1039 // until time needs to be updated.
1040 if (mPendingIdleUntil != null) {
1041 needRebatch = true;
1042 }
1043 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001044 }
1045
1046 if (!rebatching) {
1047 if (DEBUG_VALIDATE) {
1048 if (doValidate && !validateConsistencyLocked()) {
1049 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1050 + " when(hex)=" + Long.toHexString(a.when)
1051 + " whenElapsed=" + a.whenElapsed
1052 + " maxWhenElapsed=" + a.maxWhenElapsed
1053 + " interval=" + a.repeatInterval + " op=" + a.operation
1054 + " flags=0x" + Integer.toHexString(a.flags));
1055 rebatchAllAlarmsLocked(false);
1056 needRebatch = false;
1057 }
1058 }
1059
1060 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001061 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001062 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001063
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001064 rescheduleKernelAlarmsLocked();
1065 updateNextAlarmClockLocked();
1066 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001067 }
1068
Adam Lesinski182f73f2013-12-05 16:48:06 -08001069 private final IBinder mService = new IAlarmManager.Stub() {
1070 @Override
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001071 public void set(int type, long triggerAtTime, long windowLength, long interval, int flags,
Jose Lima235510e2014-08-13 12:50:01 -07001072 PendingIntent operation, WorkSource workSource,
1073 AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001074 final int callingUid = Binder.getCallingUid();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001075 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001076 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001077 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001078 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001079 }
1080
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001081 // No incoming callers can request either WAKE_FROM_IDLE or
1082 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1083 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1084 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1085
1086 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1087 // manager when to come out of idle mode, which is only for DeviceIdleController.
1088 if (callingUid != Process.SYSTEM_UID) {
1089 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1090 }
1091
1092 // If the caller is a core system component, and not calling to do work on behalf
1093 // of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED. This means we
1094 // will allow these alarms to go off as normal even while idle, with no timing
1095 // restrictions.
1096 if (callingUid < Process.FIRST_APPLICATION_UID && workSource == null) {
1097 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1098 }
1099
1100 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001101 if (windowLength == AlarmManager.WINDOW_EXACT) {
1102 flags |= AlarmManager.FLAG_STANDALONE;
1103 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001104
1105 // If this alarm is for an alarm clock, then it must be standalone and we will
1106 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001107 if (alarmClock != null) {
1108 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
1109 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001110
Adam Lesinski182f73f2013-12-05 16:48:06 -08001111 setImpl(type, triggerAtTime, windowLength, interval, operation,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001112 flags, workSource, alarmClock, callingUid);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001113 }
Christopher Tate89779822012-08-31 14:40:03 -07001114
Adam Lesinski182f73f2013-12-05 16:48:06 -08001115 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001116 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001117 getContext().enforceCallingOrSelfPermission(
1118 "android.permission.SET_TIME",
1119 "setTime");
1120
Greg Hackmann0cab8962014-02-21 16:35:52 -08001121 if (mNativeData == 0) {
1122 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1123 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001124 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001125
1126 synchronized (mLock) {
1127 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001128 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001129 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001130
1131 @Override
1132 public void setTimeZone(String tz) {
1133 getContext().enforceCallingOrSelfPermission(
1134 "android.permission.SET_TIME_ZONE",
1135 "setTimeZone");
1136
1137 final long oldId = Binder.clearCallingIdentity();
1138 try {
1139 setTimeZoneImpl(tz);
1140 } finally {
1141 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 }
1143 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001144
Adam Lesinski182f73f2013-12-05 16:48:06 -08001145 @Override
1146 public void remove(PendingIntent operation) {
1147 removeImpl(operation);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001148
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001150
Adam Lesinski182f73f2013-12-05 16:48:06 -08001151 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001152 public long getNextWakeFromIdleTime() {
1153 return getNextWakeFromIdleTimeImpl();
1154 }
1155
1156 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001157 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001158 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1159 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1160 "getNextAlarmClock", null);
1161
1162 return getNextAlarmClockImpl(userId);
1163 }
1164
1165 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001166 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1167 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1168 != PackageManager.PERMISSION_GRANTED) {
1169 pw.println("Permission Denial: can't dump AlarmManager from from pid="
1170 + Binder.getCallingPid()
1171 + ", uid=" + Binder.getCallingUid());
1172 return;
Christopher Tate4cb338d2013-07-26 13:11:31 -07001173 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001174
Adam Lesinski182f73f2013-12-05 16:48:06 -08001175 dumpImpl(pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001176 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001177 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001178
Adam Lesinski182f73f2013-12-05 16:48:06 -08001179 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001180 synchronized (mLock) {
1181 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001182 mConstants.dump(pw);
1183 pw.println();
1184
Christopher Tatee0a22b32013-07-11 14:43:13 -07001185 final long nowRTC = System.currentTimeMillis();
1186 final long nowELAPSED = SystemClock.elapsedRealtime();
1187 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1188
Dianne Hackborna750a632015-06-16 17:18:23 -07001189 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001190 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001191 pw.print(" nowELAPSED="); TimeUtils.formatDuration(nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001192 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001193 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001194 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001195 pw.print(" mLastTimeChangeRealtime=");
Dianne Hackbornc3527222015-05-13 14:03:20 -07001196 TimeUtils.formatDuration(mLastTimeChangeRealtime, pw);
1197 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001198 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001199 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001200 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1201 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001202 pw.print(" Max wakeup delay: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001203 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1204 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001205 pw.print(" Time since last dispatch: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001206 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1207 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001208 pw.print(" Next non-wakeup delivery time: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001209 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1210 pw.println();
1211 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001212
1213 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1214 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001215 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001216 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001217 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001218 pw.print(" Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001219 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001220 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001221
John Spurlock604a5ee2015-06-01 12:27:22 -04001222 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001223 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001224 final TreeSet<Integer> users = new TreeSet<>();
1225 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1226 users.add(mNextAlarmClockForUser.keyAt(i));
1227 }
1228 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1229 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1230 }
1231 for (int user : users) {
1232 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1233 final long time = next != null ? next.getTriggerTime() : 0;
1234 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001235 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001236 pw.print(" pendingSend:"); pw.print(pendingSend);
1237 pw.print(" time:"); pw.print(time);
1238 if (time > 0) {
1239 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1240 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1241 }
1242 pw.println();
1243 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001244 if (mAlarmBatches.size() > 0) {
1245 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001246 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001247 pw.println(mAlarmBatches.size());
1248 for (Batch b : mAlarmBatches) {
1249 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001250 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001251 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001252 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001253 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001254 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001255 pw.println(" Idle mode state:");
1256 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001257 if (mPendingIdleUntil != null) {
1258 pw.println(mPendingIdleUntil);
1259 mPendingIdleUntil.dump(pw, " ", nowRTC, nowELAPSED, sdf);
1260 } else {
1261 pw.println("null");
1262 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001263 pw.println(" Pending alarms:");
1264 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001265 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001266 if (mNextWakeFromIdle != null) {
1267 pw.println();
1268 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
1269 mNextWakeFromIdle.dump(pw, " ", nowRTC, nowELAPSED, sdf);
1270 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001271
1272 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001273 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001274 if (mPendingNonWakeupAlarms.size() > 0) {
1275 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001276 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001277 } else {
1278 pw.println("(none)");
1279 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001280 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001281 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1282 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001283 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001284 pw.print(", max non-interactive time: ");
1285 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1286 pw.println();
1287
1288 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001289 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001290 pw.println();
1291
Dianne Hackborna750a632015-06-16 17:18:23 -07001292 pw.print(" mAllowWhileIdleMinTime=");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001293 TimeUtils.formatDuration(mAllowWhileIdleMinTime, pw);
1294 pw.println();
1295 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001296 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001297 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
1298 pw.print(" UID ");
1299 UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
1300 pw.print(": ");
1301 TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i),
1302 nowELAPSED, pw);
1303 pw.println();
1304 }
1305 }
1306 pw.println();
1307
Dianne Hackborn81038902012-11-26 17:04:09 -08001308 if (mLog.dump(pw, " Recent problems", " ")) {
1309 pw.println();
1310 }
1311
1312 final FilterStats[] topFilters = new FilterStats[10];
1313 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1314 @Override
1315 public int compare(FilterStats lhs, FilterStats rhs) {
1316 if (lhs.aggregateTime < rhs.aggregateTime) {
1317 return 1;
1318 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1319 return -1;
1320 }
1321 return 0;
1322 }
1323 };
1324 int len = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001325 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1326 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1327 for (int ip=0; ip<uidStats.size(); ip++) {
1328 BroadcastStats bs = uidStats.valueAt(ip);
1329 for (int is=0; is<bs.filterStats.size(); is++) {
1330 FilterStats fs = bs.filterStats.valueAt(is);
1331 int pos = len > 0
1332 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1333 if (pos < 0) {
1334 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001335 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001336 if (pos < topFilters.length) {
1337 int copylen = topFilters.length - pos - 1;
1338 if (copylen > 0) {
1339 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1340 }
1341 topFilters[pos] = fs;
1342 if (len < topFilters.length) {
1343 len++;
1344 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001345 }
1346 }
1347 }
1348 }
1349 if (len > 0) {
1350 pw.println(" Top Alarms:");
1351 for (int i=0; i<len; i++) {
1352 FilterStats fs = topFilters[i];
1353 pw.print(" ");
1354 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1355 TimeUtils.formatDuration(fs.aggregateTime, pw);
1356 pw.print(" running, "); pw.print(fs.numWakeup);
1357 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001358 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1359 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001360 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001361 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001362 pw.println();
1363 }
1364 }
1365
1366 pw.println(" ");
1367 pw.println(" Alarm Stats:");
1368 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001369 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1370 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1371 for (int ip=0; ip<uidStats.size(); ip++) {
1372 BroadcastStats bs = uidStats.valueAt(ip);
1373 pw.print(" ");
1374 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1375 UserHandle.formatUid(pw, bs.mUid);
1376 pw.print(":");
1377 pw.print(bs.mPackageName);
1378 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1379 pw.print(" running, "); pw.print(bs.numWakeup);
1380 pw.println(" wakeups:");
1381 tmpFilters.clear();
1382 for (int is=0; is<bs.filterStats.size(); is++) {
1383 tmpFilters.add(bs.filterStats.valueAt(is));
1384 }
1385 Collections.sort(tmpFilters, comparator);
1386 for (int i=0; i<tmpFilters.size(); i++) {
1387 FilterStats fs = tmpFilters.get(i);
1388 pw.print(" ");
1389 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1390 TimeUtils.formatDuration(fs.aggregateTime, pw);
1391 pw.print(" "); pw.print(fs.numWakeup);
1392 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001393 pw.print(" alarms, last ");
1394 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1395 pw.println(":");
1396 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001397 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001398 pw.println();
1399 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 }
1401 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001402
1403 if (WAKEUP_STATS) {
1404 pw.println();
1405 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001406 long last = -1;
1407 for (WakeupEvent event : mRecentWakeups) {
1408 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1409 pw.print('|');
1410 if (last < 0) {
1411 pw.print('0');
1412 } else {
1413 pw.print(event.when - last);
1414 }
1415 last = event.when;
1416 pw.print('|'); pw.print(event.uid);
1417 pw.print('|'); pw.print(event.action);
1418 pw.println();
1419 }
1420 pw.println();
1421 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422 }
1423 }
1424
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001425 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001426 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
1427 PrintWriter pw = new PrintWriter(bs);
1428 final long nowRTC = System.currentTimeMillis();
1429 final long nowELAPSED = SystemClock.elapsedRealtime();
1430 final int NZ = mAlarmBatches.size();
1431 for (int iz = 0; iz < NZ; iz++) {
1432 Batch bz = mAlarmBatches.get(iz);
1433 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001434 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001435 pw.flush();
1436 Slog.v(TAG, bs.toString());
1437 bs.reset();
1438 }
1439 }
1440
1441 private boolean validateConsistencyLocked() {
1442 if (DEBUG_VALIDATE) {
1443 long lastTime = Long.MIN_VALUE;
1444 final int N = mAlarmBatches.size();
1445 for (int i = 0; i < N; i++) {
1446 Batch b = mAlarmBatches.get(i);
1447 if (b.start >= lastTime) {
1448 // duplicate start times are okay because of standalone batches
1449 lastTime = b.start;
1450 } else {
1451 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001452 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1453 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001454 return false;
1455 }
1456 }
1457 }
1458 return true;
1459 }
1460
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001461 private Batch findFirstWakeupBatchLocked() {
1462 final int N = mAlarmBatches.size();
1463 for (int i = 0; i < N; i++) {
1464 Batch b = mAlarmBatches.get(i);
1465 if (b.hasWakeups()) {
1466 return b;
1467 }
1468 }
1469 return null;
1470 }
1471
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001472 long getNextWakeFromIdleTimeImpl() {
1473 synchronized (mLock) {
1474 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
1475 }
1476 }
1477
1478 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001479 synchronized (mLock) {
1480 return mNextAlarmClockForUser.get(userId);
1481 }
1482 }
1483
1484 /**
1485 * Recomputes the next alarm clock for all users.
1486 */
1487 private void updateNextAlarmClockLocked() {
1488 if (!mNextAlarmClockMayChange) {
1489 return;
1490 }
1491 mNextAlarmClockMayChange = false;
1492
Jose Lima235510e2014-08-13 12:50:01 -07001493 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001494 nextForUser.clear();
1495
1496 final int N = mAlarmBatches.size();
1497 for (int i = 0; i < N; i++) {
1498 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
1499 final int M = alarms.size();
1500
1501 for (int j = 0; j < M; j++) {
1502 Alarm a = alarms.get(j);
1503 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001504 final int userId = UserHandle.getUserId(a.uid);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001505
1506 if (DEBUG_ALARM_CLOCK) {
1507 Log.v(TAG, "Found AlarmClockInfo at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001508 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02001509 " for user " + userId);
1510 }
1511
1512 // Alarms and batches are sorted by time, no need to compare times here.
1513 if (nextForUser.get(userId) == null) {
1514 nextForUser.put(userId, a.alarmClock);
1515 }
1516 }
1517 }
1518 }
1519
1520 // Update mNextAlarmForUser with new values.
1521 final int NN = nextForUser.size();
1522 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07001523 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001524 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001525 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001526 if (!newAlarm.equals(currentAlarm)) {
1527 updateNextAlarmInfoForUserLocked(userId, newAlarm);
1528 }
1529 }
1530
1531 // Remove users without any alarm clocks scheduled.
1532 final int NNN = mNextAlarmClockForUser.size();
1533 for (int i = NNN - 1; i >= 0; i--) {
1534 int userId = mNextAlarmClockForUser.keyAt(i);
1535 if (nextForUser.get(userId) == null) {
1536 updateNextAlarmInfoForUserLocked(userId, null);
1537 }
1538 }
1539 }
1540
Jose Lima235510e2014-08-13 12:50:01 -07001541 private void updateNextAlarmInfoForUserLocked(int userId,
1542 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001543 if (alarmClock != null) {
1544 if (DEBUG_ALARM_CLOCK) {
1545 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001546 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02001547 }
1548 mNextAlarmClockForUser.put(userId, alarmClock);
1549 } else {
1550 if (DEBUG_ALARM_CLOCK) {
1551 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
1552 }
1553 mNextAlarmClockForUser.remove(userId);
1554 }
1555
1556 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
1557 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1558 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1559 }
1560
1561 /**
1562 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
1563 * for which alarm clocks have changed since the last call to this.
1564 *
1565 * Do not call with a lock held. Only call from mHandler's thread.
1566 *
1567 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
1568 */
1569 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07001570 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001571 pendingUsers.clear();
1572
1573 synchronized (mLock) {
1574 final int N = mPendingSendNextAlarmClockChangedForUser.size();
1575 for (int i = 0; i < N; i++) {
1576 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
1577 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
1578 }
1579 mPendingSendNextAlarmClockChangedForUser.clear();
1580 }
1581
1582 final int N = pendingUsers.size();
1583 for (int i = 0; i < N; i++) {
1584 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001585 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001586 Settings.System.putStringForUser(getContext().getContentResolver(),
1587 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01001588 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02001589 userId);
1590
1591 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
1592 new UserHandle(userId));
1593 }
1594 }
1595
1596 /**
1597 * Formats an alarm like platform/packages/apps/DeskClock used to.
1598 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01001599 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
1600 int userId) {
1601 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02001602 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
1603 return (info == null) ? "" :
1604 DateFormat.format(pattern, info.getTriggerTime()).toString();
1605 }
1606
Adam Lesinski182f73f2013-12-05 16:48:06 -08001607 void rescheduleKernelAlarmsLocked() {
1608 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
1609 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001610 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001611 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001612 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001613 final Batch firstBatch = mAlarmBatches.get(0);
Christopher Tatec83d3e42015-02-04 13:48:29 -08001614 // always update the kernel alarms, as a backstop against missed wakeups
1615 if (firstWakeup != null) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001616 mNextWakeup = firstWakeup.start;
1617 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001618 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001619 if (firstBatch != firstWakeup) {
1620 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001621 }
1622 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001623 if (mPendingNonWakeupAlarms.size() > 0) {
1624 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
1625 nextNonWakeup = mNextNonWakeupDeliveryTime;
1626 }
1627 }
Christopher Tatec83d3e42015-02-04 13:48:29 -08001628 // always update the kernel alarm, as a backstop against missed wakeups
1629 if (nextNonWakeup != 0) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001630 mNextNonWakeup = nextNonWakeup;
1631 setLocked(ELAPSED_REALTIME, nextNonWakeup);
1632 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001633 }
1634
1635 private void removeLocked(PendingIntent operation) {
1636 boolean didRemove = false;
1637 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1638 Batch b = mAlarmBatches.get(i);
1639 didRemove |= b.remove(operation);
1640 if (b.size() == 0) {
1641 mAlarmBatches.remove(i);
1642 }
1643 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001644 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1645 if (mPendingWhileIdleAlarms.get(i).operation.equals(operation)) {
1646 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1647 mPendingWhileIdleAlarms.remove(i);
1648 }
1649 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001650
1651 if (didRemove) {
1652 if (DEBUG_BATCH) {
1653 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
1654 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001655 boolean restorePending = false;
1656 if (mPendingIdleUntil != null && mPendingIdleUntil.operation.equals(operation)) {
1657 mPendingIdleUntil = null;
1658 restorePending = true;
1659 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001660 if (mNextWakeFromIdle != null && mNextWakeFromIdle.operation.equals(operation)) {
1661 mNextWakeFromIdle = null;
1662 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001663 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001664 if (restorePending) {
1665 restorePendingWhileIdleAlarmsLocked();
1666 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001667 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001668 }
1669 }
1670
1671 void removeLocked(String packageName) {
1672 boolean didRemove = false;
1673 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1674 Batch b = mAlarmBatches.get(i);
1675 didRemove |= b.remove(packageName);
1676 if (b.size() == 0) {
1677 mAlarmBatches.remove(i);
1678 }
1679 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001680 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1681 if (mPendingWhileIdleAlarms.get(i).operation.getTargetPackage().equals(packageName)) {
1682 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1683 mPendingWhileIdleAlarms.remove(i);
1684 }
1685 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001686
1687 if (didRemove) {
1688 if (DEBUG_BATCH) {
1689 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1690 }
1691 rebatchAllAlarmsLocked(true);
1692 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001693 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001694 }
1695 }
1696
1697 void removeUserLocked(int userHandle) {
1698 boolean didRemove = false;
1699 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1700 Batch b = mAlarmBatches.get(i);
1701 didRemove |= b.remove(userHandle);
1702 if (b.size() == 0) {
1703 mAlarmBatches.remove(i);
1704 }
1705 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001706 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1707 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).operation.getCreatorUid())
1708 == userHandle) {
1709 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1710 mPendingWhileIdleAlarms.remove(i);
1711 }
1712 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001713 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
1714 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
1715 mLastAllowWhileIdleDispatch.removeAt(i);
1716 }
1717 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001718
1719 if (didRemove) {
1720 if (DEBUG_BATCH) {
1721 Slog.v(TAG, "remove(user) changed bounds; rebatching");
1722 }
1723 rebatchAllAlarmsLocked(true);
1724 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001725 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001726 }
1727 }
1728
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001729 void interactiveStateChangedLocked(boolean interactive) {
1730 if (mInteractive != interactive) {
1731 mInteractive = interactive;
1732 final long nowELAPSED = SystemClock.elapsedRealtime();
1733 if (interactive) {
1734 if (mPendingNonWakeupAlarms.size() > 0) {
1735 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1736 mTotalDelayTime += thisDelayTime;
1737 if (mMaxDelayTime < thisDelayTime) {
1738 mMaxDelayTime = thisDelayTime;
1739 }
1740 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
1741 mPendingNonWakeupAlarms.clear();
1742 }
1743 if (mNonInteractiveStartTime > 0) {
1744 long dur = nowELAPSED - mNonInteractiveStartTime;
1745 if (dur > mNonInteractiveTime) {
1746 mNonInteractiveTime = dur;
1747 }
1748 }
1749 } else {
1750 mNonInteractiveStartTime = nowELAPSED;
1751 }
1752 }
1753 }
1754
Adam Lesinski182f73f2013-12-05 16:48:06 -08001755 boolean lookForPackageLocked(String packageName) {
1756 for (int i = 0; i < mAlarmBatches.size(); i++) {
1757 Batch b = mAlarmBatches.get(i);
1758 if (b.hasPackage(packageName)) {
1759 return true;
1760 }
1761 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001762 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
1763 if (mPendingWhileIdleAlarms.get(i).operation.getTargetPackage().equals(packageName)) {
1764 return true;
1765 }
1766 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001767 return false;
1768 }
1769
1770 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001771 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001772 // The kernel never triggers alarms with negative wakeup times
1773 // so we ensure they are positive.
1774 long alarmSeconds, alarmNanoseconds;
1775 if (when < 0) {
1776 alarmSeconds = 0;
1777 alarmNanoseconds = 0;
1778 } else {
1779 alarmSeconds = when / 1000;
1780 alarmNanoseconds = (when % 1000) * 1000 * 1000;
1781 }
1782
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001783 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001784 } else {
1785 Message msg = Message.obtain();
1786 msg.what = ALARM_EVENT;
1787
1788 mHandler.removeMessages(ALARM_EVENT);
1789 mHandler.sendMessageAtTime(msg, when);
1790 }
1791 }
1792
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001793 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001794 String prefix, String label, long nowRTC, long nowELAPSED, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001795 for (int i=list.size()-1; i>=0; i--) {
1796 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001797 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1798 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001799 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 }
1801 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001802
1803 private static final String labelForType(int type) {
1804 switch (type) {
1805 case RTC: return "RTC";
1806 case RTC_WAKEUP : return "RTC_WAKEUP";
1807 case ELAPSED_REALTIME : return "ELAPSED";
1808 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
1809 default:
1810 break;
1811 }
1812 return "--unknown--";
1813 }
1814
1815 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001816 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001817 for (int i=list.size()-1; i>=0; i--) {
1818 Alarm a = list.get(i);
1819 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001820 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1821 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001822 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001823 }
1824 }
1825
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001826 private native long init();
1827 private native void close(long nativeData);
1828 private native void set(long nativeData, int type, long seconds, long nanoseconds);
1829 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08001830 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001831 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001833 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001834 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001835 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001836 // batches are temporally sorted, so we need only pull from the
1837 // start of the list until we either empty it or hit a batch
1838 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07001839 while (mAlarmBatches.size() > 0) {
1840 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001841 if (batch.start > nowELAPSED) {
1842 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 break;
1844 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845
Christopher Tatee0a22b32013-07-11 14:43:13 -07001846 // We will (re)schedule some alarms now; don't let that interfere
1847 // with delivery of this current batch
1848 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001849
Christopher Tatee0a22b32013-07-11 14:43:13 -07001850 final int N = batch.size();
1851 for (int i = 0; i < N; i++) {
1852 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001853
1854 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1855 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
1856 // schedule such alarms.
1857 long lastTime = mLastAllowWhileIdleDispatch.get(alarm.uid, 0);
1858 long minTime = lastTime + mAllowWhileIdleMinTime;
1859 if (nowELAPSED < minTime) {
1860 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
1861 // alarm went off for this app. Reschedule the alarm to be in the
1862 // correct time period.
1863 alarm.whenElapsed = minTime;
1864 if (alarm.maxWhenElapsed < minTime) {
1865 alarm.maxWhenElapsed = minTime;
1866 }
1867 setImplLocked(alarm, true, false);
1868 continue;
1869 }
1870 }
1871
Christopher Tatee0a22b32013-07-11 14:43:13 -07001872 alarm.count = 1;
1873 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001874 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1875 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
1876 alarm.tag);
1877 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001878 if (mPendingIdleUntil == alarm) {
1879 mPendingIdleUntil = null;
1880 rebatchAllAlarmsLocked(false);
1881 restorePendingWhileIdleAlarmsLocked();
1882 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001883 if (mNextWakeFromIdle == alarm) {
1884 mNextWakeFromIdle = null;
1885 rebatchAllAlarmsLocked(false);
1886 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001887
1888 // Recurring alarms may have passed several alarm intervals while the
1889 // phone was asleep or off, so pass a trigger count when sending them.
1890 if (alarm.repeatInterval > 0) {
1891 // this adjustment will be zero if we're late by
1892 // less than one full repeat interval
1893 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
1894
1895 // Also schedule its next recurrence
1896 final long delta = alarm.count * alarm.repeatInterval;
1897 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07001898 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07001899 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001900 alarm.repeatInterval, alarm.operation, alarm.flags, true,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001901 alarm.workSource, alarm.alarmClock, alarm.uid);
Christopher Tate864d42e2014-12-02 11:48:53 -08001902 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001903
Christopher Tate864d42e2014-12-02 11:48:53 -08001904 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001905 hasWakeup = true;
1906 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001907
1908 // We removed an alarm clock. Let the caller recompute the next alarm clock.
1909 if (alarm.alarmClock != null) {
1910 mNextAlarmClockMayChange = true;
1911 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07001912 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001913 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001914
Christopher Tate1590f1e2014-10-02 17:27:57 -07001915 // This is a new alarm delivery set; bump the sequence number to indicate that
1916 // all apps' alarm delivery classes should be recalculated.
1917 mCurrentSeq++;
1918 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001919 Collections.sort(triggerList, mAlarmDispatchComparator);
1920
1921 if (localLOGV) {
1922 for (int i=0; i<triggerList.size(); i++) {
1923 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
1924 }
1925 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001926
1927 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 /**
1931 * This Comparator sorts Alarms into increasing time order.
1932 */
1933 public static class IncreasingTimeOrder implements Comparator<Alarm> {
1934 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09001935 long when1 = a1.whenElapsed;
1936 long when2 = a2.whenElapsed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 if (when1 - when2 > 0) {
1938 return 1;
1939 }
1940 if (when1 - when2 < 0) {
1941 return -1;
1942 }
1943 return 0;
1944 }
1945 }
1946
1947 private static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001948 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001949 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001950 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001951 public final PendingIntent operation;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001952 public final String tag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001953 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001954 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001955 public final AlarmManager.AlarmClockInfo alarmClock;
1956 public final int uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001957 public int count;
1958 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07001959 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001960 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001961 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07001963 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001964
Christopher Tate3e04b472013-10-21 17:51:31 -07001965 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001966 long _interval, PendingIntent _op, WorkSource _ws, int _flags,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001967 AlarmManager.AlarmClockInfo _info, int _uid) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001968 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001969 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001970 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
1971 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001972 when = _when;
1973 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07001974 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001975 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001976 repeatInterval = _interval;
1977 operation = _op;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001978 tag = makeTag(_op, _type);
David Christieebe51fc2013-07-26 13:23:29 -07001979 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001980 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001981 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001982 uid = _uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001983 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001984
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001985 public static String makeTag(PendingIntent pi, int type) {
1986 return pi.getTag(type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
1987 ? "*walarm*:" : "*alarm*:");
1988 }
1989
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001991 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001992 StringBuilder sb = new StringBuilder(128);
1993 sb.append("Alarm{");
1994 sb.append(Integer.toHexString(System.identityHashCode(this)));
1995 sb.append(" type ");
1996 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001997 sb.append(" when ");
1998 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001999 sb.append(" ");
2000 sb.append(operation.getTargetPackage());
2001 sb.append('}');
2002 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 }
2004
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002005 public void dump(PrintWriter pw, String prefix, long nowRTC, long nowELAPSED,
2006 SimpleDateFormat sdf) {
2007 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
2008 pw.print(prefix); pw.print("tag="); pw.println(tag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002009 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002010 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
2011 nowELAPSED, pw);
2012 if (isRtc) {
2013 pw.print(" when="); pw.print(sdf.format(new Date(when)));
2014 } else {
2015 pw.print(" when="); TimeUtils.formatDuration(when, nowELAPSED, pw);
2016 }
2017 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002018 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002019 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002020 pw.print(" count="); pw.print(count);
2021 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002022 if (alarmClock != null) {
2023 pw.print(prefix); pw.println("Alarm clock:");
2024 pw.print(prefix); pw.print(" triggerTime=");
2025 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
2026 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
2027 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002028 pw.print(prefix); pw.print("operation="); pw.println(operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002029 }
2030 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002031
Christopher Tatee0a22b32013-07-11 14:43:13 -07002032 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
2033 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002034 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
2035 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002036 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07002037 break;
2038 }
2039
Christopher Tatee0a22b32013-07-11 14:43:13 -07002040 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002041 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
2042 Alarm a = b.alarms.get(nextAlarm);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002043 WakeupEvent e = new WakeupEvent(nowRTC,
2044 a.operation.getCreatorUid(),
2045 a.operation.getIntent().getAction());
2046 mRecentWakeups.add(e);
2047 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002048 }
2049 }
2050
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002051 long currentNonWakeupFuzzLocked(long nowELAPSED) {
2052 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
2053 if (timeSinceOn < 5*60*1000) {
2054 // If the screen has been off for 5 minutes, only delay by at most two minutes.
2055 return 2*60*1000;
2056 } else if (timeSinceOn < 30*60*1000) {
2057 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
2058 return 15*60*1000;
2059 } else {
2060 // Otherwise, we will delay by at most an hour.
2061 return 60*60*1000;
2062 }
2063 }
2064
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002065 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002066 if (duration < 15*60*1000) {
2067 // If the duration until the time is less than 15 minutes, the maximum fuzz
2068 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002069 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002070 } else if (duration < 90*60*1000) {
2071 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
2072 return 15*60*1000;
2073 } else {
2074 // Otherwise, we will fuzz by at most half an hour.
2075 return 30*60*1000;
2076 }
2077 }
2078
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002079 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
2080 if (mInteractive) {
2081 return false;
2082 }
2083 if (mLastAlarmDeliveryTime <= 0) {
2084 return false;
2085 }
minho.choo649acab2014-12-12 16:13:55 +09002086 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002087 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
2088 // and the next delivery time is in the past, then just deliver them all. This
2089 // avoids bugs where we get stuck in a loop trying to poll for alarms.
2090 return false;
2091 }
2092 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
2093 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
2094 }
2095
2096 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
2097 mLastAlarmDeliveryTime = nowELAPSED;
2098 for (int i=0; i<triggerList.size(); i++) {
2099 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07002100 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002101 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07002102 if (localLOGV) {
2103 Slog.v(TAG, "sending alarm " + alarm);
2104 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07002105 if (RECORD_ALARMS_IN_HISTORY) {
2106 if (alarm.workSource != null && alarm.workSource.size() > 0) {
2107 for (int wi=0; wi<alarm.workSource.size(); wi++) {
2108 ActivityManagerNative.noteAlarmStart(
2109 alarm.operation, alarm.workSource.get(wi), alarm.tag);
2110 }
2111 } else {
2112 ActivityManagerNative.noteAlarmStart(
2113 alarm.operation, -1, alarm.tag);
2114 }
2115 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002116 alarm.operation.send(getContext(), 0,
2117 mBackgroundIntent.putExtra(
2118 Intent.EXTRA_ALARM_COUNT, alarm.count),
Dianne Hackborna750a632015-06-16 17:18:23 -07002119 mResultReceiver, mHandler, null, allowWhileIdle ? mIdleOptions : null);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002120
2121 // we have an active broadcast so stay awake.
2122 if (mBroadcastRefCount == 0) {
2123 setWakelockWorkSource(alarm.operation, alarm.workSource,
2124 alarm.type, alarm.tag, true);
2125 mWakeLock.acquire();
2126 }
2127 final InFlight inflight = new InFlight(AlarmManagerService.this,
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002128 alarm.operation, alarm.workSource, alarm.type, alarm.tag, nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002129 mInFlight.add(inflight);
2130 mBroadcastRefCount++;
2131
Dianne Hackborna750a632015-06-16 17:18:23 -07002132 if (allowWhileIdle) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002133 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
2134 mLastAllowWhileIdleDispatch.put(alarm.uid, nowELAPSED);
2135 }
2136
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002137 final BroadcastStats bs = inflight.mBroadcastStats;
2138 bs.count++;
2139 if (bs.nesting == 0) {
2140 bs.nesting = 1;
2141 bs.startTime = nowELAPSED;
2142 } else {
2143 bs.nesting++;
2144 }
2145 final FilterStats fs = inflight.mFilterStats;
2146 fs.count++;
2147 if (fs.nesting == 0) {
2148 fs.nesting = 1;
2149 fs.startTime = nowELAPSED;
2150 } else {
2151 fs.nesting++;
2152 }
2153 if (alarm.type == ELAPSED_REALTIME_WAKEUP
2154 || alarm.type == RTC_WAKEUP) {
2155 bs.numWakeup++;
2156 fs.numWakeup++;
2157 if (alarm.workSource != null && alarm.workSource.size() > 0) {
2158 for (int wi=0; wi<alarm.workSource.size(); wi++) {
2159 ActivityManagerNative.noteWakeupAlarm(
2160 alarm.operation, alarm.workSource.get(wi),
Dianne Hackborn1e383822015-04-10 14:02:33 -07002161 alarm.workSource.getName(wi), alarm.tag);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002162 }
2163 } else {
2164 ActivityManagerNative.noteWakeupAlarm(
Dianne Hackborn1e383822015-04-10 14:02:33 -07002165 alarm.operation, -1, null, alarm.tag);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002166 }
2167 }
2168 } catch (PendingIntent.CanceledException e) {
2169 if (alarm.repeatInterval > 0) {
2170 // This IntentSender is no longer valid, but this
2171 // is a repeating alarm, so toss the hoser.
2172 removeImpl(alarm.operation);
2173 }
2174 } catch (RuntimeException e) {
2175 Slog.w(TAG, "Failure sending alarm.", e);
2176 }
2177 }
2178 }
2179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002180 private class AlarmThread extends Thread
2181 {
2182 public AlarmThread()
2183 {
2184 super("AlarmManager");
2185 }
2186
2187 public void run()
2188 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002189 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2190
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002191 while (true)
2192 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002193 int result = waitForAlarm(mNativeData);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002194
2195 triggerList.clear();
2196
Dianne Hackbornc3527222015-05-13 14:03:20 -07002197 final long nowRTC = System.currentTimeMillis();
2198 final long nowELAPSED = SystemClock.elapsedRealtime();
2199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002200 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002201 // The kernel can give us spurious time change notifications due to
2202 // small adjustments it makes internally; we want to filter those out.
2203 final long lastTimeChangeClockTime;
2204 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07002205 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002206 lastTimeChangeClockTime = mLastTimeChangeClockTime;
2207 expectedClockTime = lastTimeChangeClockTime
2208 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07002209 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002210 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-500)
2211 || nowRTC > (expectedClockTime+500)) {
2212 // The change is by at least +/- 500 ms (or this is the first change),
2213 // let's do it!
2214 if (DEBUG_BATCH) {
2215 Slog.v(TAG, "Time changed notification from kernel; rebatching");
2216 }
2217 removeImpl(mTimeTickSender);
2218 rebatchAllAlarms();
2219 mClockReceiver.scheduleTimeTickEvent();
2220 synchronized (mLock) {
2221 mNumTimeChanged++;
2222 mLastTimeChangeClockTime = nowRTC;
2223 mLastTimeChangeRealtime = nowELAPSED;
2224 }
2225 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
2226 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
2227 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2228 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
2229
2230 // The world has changed on us, so we need to re-evaluate alarms
2231 // regardless of whether the kernel has told us one went off.
2232 result |= IS_WAKEUP_MASK;
2233 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002234 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002235
Dianne Hackbornc3527222015-05-13 14:03:20 -07002236 if (result != TIME_CHANGED_MASK) {
2237 // If this was anything besides just a time change, then figure what if
2238 // anything to do about alarms.
2239 synchronized (mLock) {
2240 if (localLOGV) Slog.v(
2241 TAG, "Checking for alarms... rtc=" + nowRTC
2242 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07002243
Dianne Hackbornc3527222015-05-13 14:03:20 -07002244 if (WAKEUP_STATS) {
2245 if ((result & IS_WAKEUP_MASK) != 0) {
2246 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
2247 int n = 0;
2248 for (WakeupEvent event : mRecentWakeups) {
2249 if (event.when > newEarliest) break;
2250 n++; // number of now-stale entries at the list head
2251 }
2252 for (int i = 0; i < n; i++) {
2253 mRecentWakeups.remove();
2254 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002255
Dianne Hackbornc3527222015-05-13 14:03:20 -07002256 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002257 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002258 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002259
2260 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2261 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
2262 // if there are no wakeup alarms and the screen is off, we can
2263 // delay what we have so far until the future.
2264 if (mPendingNonWakeupAlarms.size() == 0) {
2265 mStartCurrentDelayTime = nowELAPSED;
2266 mNextNonWakeupDeliveryTime = nowELAPSED
2267 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
2268 }
2269 mPendingNonWakeupAlarms.addAll(triggerList);
2270 mNumDelayedAlarms += triggerList.size();
2271 rescheduleKernelAlarmsLocked();
2272 updateNextAlarmClockLocked();
2273 } else {
2274 // now deliver the alarm intents; if there are pending non-wakeup
2275 // alarms, we need to merge them in to the list. note we don't
2276 // just deliver them first because we generally want non-wakeup
2277 // alarms delivered after wakeup alarms.
2278 rescheduleKernelAlarmsLocked();
2279 updateNextAlarmClockLocked();
2280 if (mPendingNonWakeupAlarms.size() > 0) {
2281 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
2282 triggerList.addAll(mPendingNonWakeupAlarms);
2283 Collections.sort(triggerList, mAlarmDispatchComparator);
2284 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2285 mTotalDelayTime += thisDelayTime;
2286 if (mMaxDelayTime < thisDelayTime) {
2287 mMaxDelayTime = thisDelayTime;
2288 }
2289 mPendingNonWakeupAlarms.clear();
2290 }
2291 deliverAlarmsLocked(triggerList, nowELAPSED);
2292 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002293 }
2294 }
2295 }
2296 }
2297 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002298
David Christieebe51fc2013-07-26 13:23:29 -07002299 /**
2300 * Attribute blame for a WakeLock.
2301 * @param pi PendingIntent to attribute blame to if ws is null.
2302 * @param ws WorkSource to attribute blame.
2303 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002304 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
2305 boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07002306 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002307 final boolean unimportant = pi == mTimeTickSender;
2308 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002309 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002310 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002311 } else {
2312 mWakeLock.setHistoryTag(null);
2313 }
2314 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07002315 if (ws != null) {
2316 mWakeLock.setWorkSource(ws);
2317 return;
2318 }
2319
Christopher Tatec4a07d12012-04-06 14:19:13 -07002320 final int uid = ActivityManagerNative.getDefault()
2321 .getUidForIntentSender(pi.getTarget());
2322 if (uid >= 0) {
2323 mWakeLock.setWorkSource(new WorkSource(uid));
2324 return;
2325 }
2326 } catch (Exception e) {
2327 }
2328
2329 // Something went wrong; fall back to attributing the lock to the OS
2330 mWakeLock.setWorkSource(null);
2331 }
2332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002333 private class AlarmHandler extends Handler {
2334 public static final int ALARM_EVENT = 1;
2335 public static final int MINUTE_CHANGE_EVENT = 2;
2336 public static final int DATE_CHANGE_EVENT = 3;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002337 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002338
2339 public AlarmHandler() {
2340 }
2341
2342 public void handleMessage(Message msg) {
2343 if (msg.what == ALARM_EVENT) {
2344 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2345 synchronized (mLock) {
2346 final long nowRTC = System.currentTimeMillis();
Christopher Tatee0a22b32013-07-11 14:43:13 -07002347 final long nowELAPSED = SystemClock.elapsedRealtime();
2348 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002349 updateNextAlarmClockLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002350 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002351
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002352 // now trigger the alarms without the lock held
Dianne Hackborn390517b2013-05-30 15:03:32 -07002353 for (int i=0; i<triggerList.size(); i++) {
2354 Alarm alarm = triggerList.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002355 try {
2356 alarm.operation.send();
2357 } catch (PendingIntent.CanceledException e) {
2358 if (alarm.repeatInterval > 0) {
2359 // This IntentSender is no longer valid, but this
2360 // is a repeating alarm, so toss the hoser.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002361 removeImpl(alarm.operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002362 }
2363 }
2364 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002365 } else if (msg.what == SEND_NEXT_ALARM_CLOCK_CHANGED) {
2366 sendNextAlarmClockChanged();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002367 }
2368 }
2369 }
2370
2371 class ClockReceiver extends BroadcastReceiver {
2372 public ClockReceiver() {
2373 IntentFilter filter = new IntentFilter();
2374 filter.addAction(Intent.ACTION_TIME_TICK);
2375 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002376 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002377 }
2378
2379 @Override
2380 public void onReceive(Context context, Intent intent) {
2381 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07002382 if (DEBUG_BATCH) {
2383 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
2384 }
2385 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002386 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
2387 // Since the kernel does not keep track of DST, we need to
2388 // reset the TZ information at the beginning of each day
2389 // based off of the current Zone gmt offset + userspace tracked
2390 // daylight savings information.
2391 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02002392 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002393 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07002394 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002395 }
2396 }
2397
2398 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07002399 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09002400 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07002401
2402 // Schedule this event for the amount of time that it would take to get to
2403 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09002404 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07002405
David Christieebe51fc2013-07-26 13:23:29 -07002406 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002407 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002408 0, mTimeTickSender, AlarmManager.FLAG_STANDALONE, workSource, null,
2409 Process.myUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002410 }
Christopher Tate385e4982013-07-23 18:22:29 -07002411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002412 public void scheduleDateChangedEvent() {
2413 Calendar calendar = Calendar.getInstance();
2414 calendar.setTimeInMillis(System.currentTimeMillis());
2415 calendar.set(Calendar.HOUR, 0);
2416 calendar.set(Calendar.MINUTE, 0);
2417 calendar.set(Calendar.SECOND, 0);
2418 calendar.set(Calendar.MILLISECOND, 0);
2419 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07002420
2421 final WorkSource workSource = null; // Let system take blame for date change events.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002422 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002423 AlarmManager.FLAG_STANDALONE, workSource, null, Process.myUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002424 }
2425 }
2426
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002427 class InteractiveStateReceiver extends BroadcastReceiver {
2428 public InteractiveStateReceiver() {
2429 IntentFilter filter = new IntentFilter();
2430 filter.addAction(Intent.ACTION_SCREEN_OFF);
2431 filter.addAction(Intent.ACTION_SCREEN_ON);
2432 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
2433 getContext().registerReceiver(this, filter);
2434 }
2435
2436 @Override
2437 public void onReceive(Context context, Intent intent) {
2438 synchronized (mLock) {
2439 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
2440 }
2441 }
2442 }
2443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002444 class UninstallReceiver extends BroadcastReceiver {
2445 public UninstallReceiver() {
2446 IntentFilter filter = new IntentFilter();
2447 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2448 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002449 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08002451 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002452 // Register for events related to sdcard installation.
2453 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08002454 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002455 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002456 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002457 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002458 }
2459
2460 @Override
2461 public void onReceive(Context context, Intent intent) {
2462 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002463 String action = intent.getAction();
2464 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002465 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
2466 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
2467 for (String packageName : pkgList) {
2468 if (lookForPackageLocked(packageName)) {
2469 setResultCode(Activity.RESULT_OK);
2470 return;
2471 }
2472 }
2473 return;
2474 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002475 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002476 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
2477 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
2478 if (userHandle >= 0) {
2479 removeUserLocked(userHandle);
2480 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002481 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
2482 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
2483 if (uid >= 0) {
2484 mLastAllowWhileIdleDispatch.delete(uid);
2485 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002486 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08002487 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
2488 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
2489 // This package is being updated; don't kill its alarms.
2490 return;
2491 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002492 Uri data = intent.getData();
2493 if (data != null) {
2494 String pkg = data.getSchemeSpecificPart();
2495 if (pkg != null) {
2496 pkgList = new String[]{pkg};
2497 }
2498 }
2499 }
2500 if (pkgList != null && (pkgList.length > 0)) {
2501 for (String pkg : pkgList) {
2502 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07002503 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002504 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
2505 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
2506 if (uidStats.remove(pkg) != null) {
2507 if (uidStats.size() <= 0) {
2508 mBroadcastStats.removeAt(i);
2509 }
2510 }
2511 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002513 }
2514 }
2515 }
2516 }
2517
2518 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002519 String pkg = pi.getCreatorPackage();
2520 int uid = pi.getCreatorUid();
2521 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
2522 if (uidStats == null) {
2523 uidStats = new ArrayMap<String, BroadcastStats>();
2524 mBroadcastStats.put(uid, uidStats);
2525 }
2526 BroadcastStats bs = uidStats.get(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527 if (bs == null) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002528 bs = new BroadcastStats(uid, pkg);
2529 uidStats.put(pkg, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002530 }
2531 return bs;
2532 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 class ResultReceiver implements PendingIntent.OnFinished {
2535 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
2536 String resultData, Bundle resultExtras) {
2537 synchronized (mLock) {
Dianne Hackborn81038902012-11-26 17:04:09 -08002538 InFlight inflight = null;
2539 for (int i=0; i<mInFlight.size(); i++) {
2540 if (mInFlight.get(i).mPendingIntent == pi) {
2541 inflight = mInFlight.remove(i);
2542 break;
2543 }
2544 }
2545 if (inflight != null) {
2546 final long nowELAPSED = SystemClock.elapsedRealtime();
2547 BroadcastStats bs = inflight.mBroadcastStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002548 bs.nesting--;
2549 if (bs.nesting <= 0) {
2550 bs.nesting = 0;
Dianne Hackborn81038902012-11-26 17:04:09 -08002551 bs.aggregateTime += nowELAPSED - bs.startTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002552 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002553 FilterStats fs = inflight.mFilterStats;
2554 fs.nesting--;
2555 if (fs.nesting <= 0) {
2556 fs.nesting = 0;
2557 fs.aggregateTime += nowELAPSED - fs.startTime;
2558 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07002559 if (RECORD_ALARMS_IN_HISTORY) {
2560 if (inflight.mWorkSource != null && inflight.mWorkSource.size() > 0) {
2561 for (int wi=0; wi<inflight.mWorkSource.size(); wi++) {
2562 ActivityManagerNative.noteAlarmFinish(
2563 pi, inflight.mWorkSource.get(wi), inflight.mTag);
2564 }
2565 } else {
2566 ActivityManagerNative.noteAlarmFinish(
2567 pi, -1, inflight.mTag);
2568 }
2569 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002570 } else {
2571 mLog.w("No in-flight alarm for " + pi + " " + intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002572 }
2573 mBroadcastRefCount--;
2574 if (mBroadcastRefCount == 0) {
2575 mWakeLock.release();
Dianne Hackborn81038902012-11-26 17:04:09 -08002576 if (mInFlight.size() > 0) {
2577 mLog.w("Finished all broadcasts with " + mInFlight.size()
2578 + " remaining inflights");
2579 for (int i=0; i<mInFlight.size(); i++) {
2580 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
2581 }
2582 mInFlight.clear();
2583 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002584 } else {
2585 // the next of our alarms is now in flight. reattribute the wakelock.
Dianne Hackborn81038902012-11-26 17:04:09 -08002586 if (mInFlight.size() > 0) {
David Christieebe51fc2013-07-26 13:23:29 -07002587 InFlight inFlight = mInFlight.get(0);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08002588 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002589 inFlight.mAlarmType, inFlight.mTag, false);
Christopher Tatec4a07d12012-04-06 14:19:13 -07002590 } else {
2591 // should never happen
Dianne Hackborn81038902012-11-26 17:04:09 -08002592 mLog.w("Alarm wakelock still held but sent queue empty");
Christopher Tatec4a07d12012-04-06 14:19:13 -07002593 mWakeLock.setWorkSource(null);
2594 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002595 }
2596 }
2597 }
2598 }
2599}