blob: e268bc83574edc3224b583eed4676ebef49b353a [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;
Dianne Hackbornae78bf82015-10-26 13:33:20 -070098 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -080099 static final int ALARM_EVENT = 1;
100 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200101
Adam Lesinski182f73f2013-12-05 16:48:06 -0800102 static final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800104 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105
Adam Lesinski182f73f2013-12-05 16:48:06 -0800106 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700107
Adrian Roosc42a1e12014-07-07 23:35:53 +0200108 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT = new Intent(
109 AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED);
110
Adam Lesinski182f73f2013-12-05 16:48:06 -0800111 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800112
Adam Lesinski182f73f2013-12-05 16:48:06 -0800113 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800114
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800115 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800116 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700117 private long mNextNonWakeup;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800118 int mBroadcastRefCount = 0;
119 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700120 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700121 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
122 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800123 final AlarmHandler mHandler = new AlarmHandler();
124 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700125 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126 private UninstallReceiver mUninstallReceiver;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800127 final ResultReceiver mResultReceiver = new ResultReceiver();
128 PendingIntent mTimeTickSender;
129 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700130 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700131 boolean mInteractive = true;
132 long mNonInteractiveStartTime;
133 long mNonInteractiveTime;
134 long mLastAlarmDeliveryTime;
135 long mStartCurrentDelayTime;
136 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700137 long mLastTimeChangeClockTime;
138 long mLastTimeChangeRealtime;
Dianne Hackborna750a632015-06-16 17:18:23 -0700139 long mAllowWhileIdleMinTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700140 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800141
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700142 /**
143 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
144 * used to determine the earliest we can dispatch the next such alarm.
145 */
146 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
147
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700148 final static class IdleDispatchEntry {
149 int uid;
150 String pkg;
151 String tag;
152 String op;
153 long elapsedRealtime;
154 long argRealtime;
155 }
156 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
157
Dianne Hackborna750a632015-06-16 17:18:23 -0700158 /**
159 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
160 */
161 Bundle mIdleOptions;
162
Jose Lima235510e2014-08-13 12:50:01 -0700163 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
164 new SparseArray<>();
165 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
166 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200167 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
168 new SparseBooleanArray();
169 private boolean mNextAlarmClockMayChange;
170
171 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700172 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
173 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200174
Dianne Hackborna750a632015-06-16 17:18:23 -0700175 /**
176 * All times are in milliseconds. These constants are kept synchronized with the system
177 * global Settings. Any access to this class or its fields should be done while
178 * holding the AlarmManagerService.mLock lock.
179 */
180 private final class Constants extends ContentObserver {
181 // Key names stored in the settings value.
182 private static final String KEY_MIN_FUTURITY = "min_futurity";
183 private static final String KEY_MIN_INTERVAL = "min_interval";
184 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
185 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
186 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
187 = "allow_while_idle_whitelist_duration";
188
189 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
190 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tateaa244da2015-08-27 15:57:57 -0700191 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborna750a632015-06-16 17:18:23 -0700192 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 15*60*1000;
193 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
194
195 // Minimum futurity of a new alarm
196 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
197
198 // Minimum alarm recurrence interval
199 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
200
201 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
202 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
203
204 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
205 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
206
207 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
208 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
209 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
210
211 private ContentResolver mResolver;
212 private final KeyValueListParser mParser = new KeyValueListParser(',');
213 private long mLastAllowWhileIdleWhitelistDuration = -1;
214
215 public Constants(Handler handler) {
216 super(handler);
217 updateAllowWhileIdleMinTimeLocked();
218 updateAllowWhileIdleWhitelistDurationLocked();
219 }
220
221 public void start(ContentResolver resolver) {
222 mResolver = resolver;
223 mResolver.registerContentObserver(Settings.Global.getUriFor(
224 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
225 updateConstants();
226 }
227
228 public void updateAllowWhileIdleMinTimeLocked() {
229 mAllowWhileIdleMinTime = mPendingIdleUntil != null
230 ? ALLOW_WHILE_IDLE_LONG_TIME : ALLOW_WHILE_IDLE_SHORT_TIME;
231 }
232
233 public void updateAllowWhileIdleWhitelistDurationLocked() {
234 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
235 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
236 BroadcastOptions opts = BroadcastOptions.makeBasic();
237 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
238 mIdleOptions = opts.toBundle();
239 }
240 }
241
242 @Override
243 public void onChange(boolean selfChange, Uri uri) {
244 updateConstants();
245 }
246
247 private void updateConstants() {
248 synchronized (mLock) {
249 try {
250 mParser.setString(Settings.Global.getString(mResolver,
251 Settings.Global.ALARM_MANAGER_CONSTANTS));
252 } catch (IllegalArgumentException e) {
253 // Failed to parse the settings string, log this and move on
254 // with defaults.
255 Slog.e(TAG, "Bad device idle settings", e);
256 }
257
258 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
259 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
260 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
261 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
262 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
263 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
264 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
265 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
266 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
267
268 updateAllowWhileIdleMinTimeLocked();
269 updateAllowWhileIdleWhitelistDurationLocked();
270 }
271 }
272
273 void dump(PrintWriter pw) {
274 pw.println(" Settings:");
275
276 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
277 TimeUtils.formatDuration(MIN_FUTURITY, pw);
278 pw.println();
279
280 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
281 TimeUtils.formatDuration(MIN_INTERVAL, pw);
282 pw.println();
283
284 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
285 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
286 pw.println();
287
288 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
289 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
290 pw.println();
291
292 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
293 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
294 pw.println();
295 }
296 }
297
298 final Constants mConstants;
299
Christopher Tate1590f1e2014-10-02 17:27:57 -0700300 // Alarm delivery ordering bookkeeping
301 static final int PRIO_TICK = 0;
302 static final int PRIO_WAKEUP = 1;
303 static final int PRIO_NORMAL = 2;
304
Dianne Hackborna750a632015-06-16 17:18:23 -0700305 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700306 int seq;
307 int priority;
308
309 PriorityClass() {
310 seq = mCurrentSeq - 1;
311 priority = PRIO_NORMAL;
312 }
313 }
314
Dianne Hackborna750a632015-06-16 17:18:23 -0700315 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700316 int mCurrentSeq = 0;
317
Dianne Hackborna750a632015-06-16 17:18:23 -0700318 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700319 public long when;
320 public int uid;
321 public String action;
322
323 public WakeupEvent(long theTime, int theUid, String theAction) {
324 when = theTime;
325 uid = theUid;
326 action = theAction;
327 }
328 }
329
Adam Lesinski182f73f2013-12-05 16:48:06 -0800330 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
331 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700332
Adrian Roosc42a1e12014-07-07 23:35:53 +0200333 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700334 long start; // These endpoints are always in ELAPSED
335 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700336 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700337
338 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
339
340 Batch() {
341 start = 0;
342 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700343 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700344 }
345
346 Batch(Alarm seed) {
347 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700348 end = seed.maxWhenElapsed;
349 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700350 alarms.add(seed);
351 }
352
353 int size() {
354 return alarms.size();
355 }
356
357 Alarm get(int index) {
358 return alarms.get(index);
359 }
360
361 boolean canHold(long whenElapsed, long maxWhen) {
362 return (end >= whenElapsed) && (start <= maxWhen);
363 }
364
365 boolean add(Alarm alarm) {
366 boolean newStart = false;
367 // narrows the batch if necessary; presumes that canHold(alarm) is true
368 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
369 if (index < 0) {
370 index = 0 - index - 1;
371 }
372 alarms.add(index, alarm);
373 if (DEBUG_BATCH) {
374 Slog.v(TAG, "Adding " + alarm + " to " + this);
375 }
376 if (alarm.whenElapsed > start) {
377 start = alarm.whenElapsed;
378 newStart = true;
379 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700380 if (alarm.maxWhenElapsed < end) {
381 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700382 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700383 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700384
385 if (DEBUG_BATCH) {
386 Slog.v(TAG, " => now " + this);
387 }
388 return newStart;
389 }
390
391 boolean remove(final PendingIntent operation) {
392 boolean didRemove = false;
393 long newStart = 0; // recalculate endpoints as we go
394 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700395 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700396 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700397 Alarm alarm = alarms.get(i);
398 if (alarm.operation.equals(operation)) {
399 alarms.remove(i);
400 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200401 if (alarm.alarmClock != null) {
402 mNextAlarmClockMayChange = true;
403 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700404 } else {
405 if (alarm.whenElapsed > newStart) {
406 newStart = alarm.whenElapsed;
407 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700408 if (alarm.maxWhenElapsed < newEnd) {
409 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700410 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700411 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700412 i++;
413 }
414 }
415 if (didRemove) {
416 // commit the new batch bounds
417 start = newStart;
418 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700419 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700420 }
421 return didRemove;
422 }
423
424 boolean remove(final String packageName) {
425 boolean didRemove = false;
426 long newStart = 0; // recalculate endpoints as we go
427 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700428 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700429 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700430 Alarm alarm = alarms.get(i);
431 if (alarm.operation.getTargetPackage().equals(packageName)) {
432 alarms.remove(i);
433 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200434 if (alarm.alarmClock != null) {
435 mNextAlarmClockMayChange = true;
436 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700437 } else {
438 if (alarm.whenElapsed > newStart) {
439 newStart = alarm.whenElapsed;
440 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700441 if (alarm.maxWhenElapsed < newEnd) {
442 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700443 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700444 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700445 i++;
446 }
447 }
448 if (didRemove) {
449 // commit the new batch bounds
450 start = newStart;
451 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700452 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700453 }
454 return didRemove;
455 }
456
457 boolean remove(final int userHandle) {
458 boolean didRemove = false;
459 long newStart = 0; // recalculate endpoints as we go
460 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700461 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700462 Alarm alarm = alarms.get(i);
463 if (UserHandle.getUserId(alarm.operation.getCreatorUid()) == userHandle) {
464 alarms.remove(i);
465 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200466 if (alarm.alarmClock != null) {
467 mNextAlarmClockMayChange = true;
468 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700469 } else {
470 if (alarm.whenElapsed > newStart) {
471 newStart = alarm.whenElapsed;
472 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700473 if (alarm.maxWhenElapsed < newEnd) {
474 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700475 }
476 i++;
477 }
478 }
479 if (didRemove) {
480 // commit the new batch bounds
481 start = newStart;
482 end = newEnd;
483 }
484 return didRemove;
485 }
486
487 boolean hasPackage(final String packageName) {
488 final int N = alarms.size();
489 for (int i = 0; i < N; i++) {
490 Alarm a = alarms.get(i);
491 if (a.operation.getTargetPackage().equals(packageName)) {
492 return true;
493 }
494 }
495 return false;
496 }
497
498 boolean hasWakeups() {
499 final int N = alarms.size();
500 for (int i = 0; i < N; i++) {
501 Alarm a = alarms.get(i);
502 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
503 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
504 return true;
505 }
506 }
507 return false;
508 }
509
510 @Override
511 public String toString() {
512 StringBuilder b = new StringBuilder(40);
513 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
514 b.append(" num="); b.append(size());
515 b.append(" start="); b.append(start);
516 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700517 if (flags != 0) {
518 b.append(" flgs=0x");
519 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700520 }
521 b.append('}');
522 return b.toString();
523 }
524 }
525
526 static class BatchTimeOrder implements Comparator<Batch> {
527 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800528 long when1 = b1.start;
529 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800530 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700531 return 1;
532 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800533 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700534 return -1;
535 }
536 return 0;
537 }
538 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800539
540 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
541 @Override
542 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700543 // priority class trumps everything. TICK < WAKEUP < NORMAL
544 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
545 return -1;
546 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
547 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800548 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700549
550 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800551 if (lhs.whenElapsed < rhs.whenElapsed) {
552 return -1;
553 } else if (lhs.whenElapsed > rhs.whenElapsed) {
554 return 1;
555 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700556
557 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800558 return 0;
559 }
560 };
561
Christopher Tate1590f1e2014-10-02 17:27:57 -0700562 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
563 final int N = alarms.size();
564 for (int i = 0; i < N; i++) {
565 Alarm a = alarms.get(i);
566
567 final int alarmPrio;
568 if (Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
569 alarmPrio = PRIO_TICK;
570 } else if (a.wakeup) {
571 alarmPrio = PRIO_WAKEUP;
572 } else {
573 alarmPrio = PRIO_NORMAL;
574 }
575
576 PriorityClass packagePrio = a.priorityClass;
577 if (packagePrio == null) packagePrio = mPriorities.get(a.operation.getCreatorPackage());
578 if (packagePrio == null) {
579 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
580 mPriorities.put(a.operation.getCreatorPackage(), packagePrio);
581 }
582 a.priorityClass = packagePrio;
583
584 if (packagePrio.seq != mCurrentSeq) {
585 // first alarm we've seen in the current delivery generation from this package
586 packagePrio.priority = alarmPrio;
587 packagePrio.seq = mCurrentSeq;
588 } else {
589 // Multiple alarms from this package being delivered in this generation;
590 // bump the package's delivery class if it's warranted.
591 // TICK < WAKEUP < NORMAL
592 if (alarmPrio < packagePrio.priority) {
593 packagePrio.priority = alarmPrio;
594 }
595 }
596 }
597 }
598
Christopher Tatee0a22b32013-07-11 14:43:13 -0700599 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800600 static final long MIN_FUZZABLE_INTERVAL = 10000;
601 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700602 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
603
604 // set to null if in idle mode; while in this mode, any alarms we don't want
605 // to run during this time are placed in mPendingWhileIdleAlarms
606 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700607 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700608 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700609
Jeff Brownb880d882014-02-10 19:47:07 -0800610 public AlarmManagerService(Context context) {
611 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700612 mConstants = new Constants(mHandler);
Jeff Brownb880d882014-02-10 19:47:07 -0800613 }
614
Christopher Tatee0a22b32013-07-11 14:43:13 -0700615 static long convertToElapsed(long when, int type) {
616 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
617 if (isRtc) {
618 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
619 }
620 return when;
621 }
622
623 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
624 // calculate the end of our nominal delivery window for the alarm.
625 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
626 // Current heuristic: batchable window is 75% of either the recurrence interval
627 // [for a periodic alarm] or of the time from now to the desired delivery time,
628 // with a minimum delay/interval of 10 seconds, under which we will simply not
629 // defer the alarm.
630 long futurity = (interval == 0)
631 ? (triggerAtTime - now)
632 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700633 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700634 futurity = 0;
635 }
636 return triggerAtTime + (long)(.75 * futurity);
637 }
638
639 // returns true if the batch was added at the head
640 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
641 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
642 if (index < 0) {
643 index = 0 - index - 1;
644 }
645 list.add(index, newBatch);
646 return (index == 0);
647 }
648
Christopher Tate385e4982013-07-23 18:22:29 -0700649 // Return the index of the matching batch, or -1 if none found.
650 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700651 final int N = mAlarmBatches.size();
652 for (int i = 0; i < N; i++) {
653 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700654 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700655 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700656 }
657 }
Christopher Tate385e4982013-07-23 18:22:29 -0700658 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700659 }
660
661 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
662 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700663 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700664 rebatchAllAlarmsLocked(true);
665 }
666 }
667
668 void rebatchAllAlarmsLocked(boolean doValidate) {
669 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
670 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700671 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700672 final long nowElapsed = SystemClock.elapsedRealtime();
673 final int oldBatches = oldSet.size();
674 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
675 Batch batch = oldSet.get(batchNum);
676 final int N = batch.size();
677 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700678 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700679 }
680 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700681 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
682 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
683 + " to " + mPendingIdleUntil);
684 if (mPendingIdleUntil == null) {
685 // Somehow we lost this... we need to restore all of the pending alarms.
686 restorePendingWhileIdleAlarmsLocked();
687 }
688 }
689 rescheduleKernelAlarmsLocked();
690 updateNextAlarmClockLocked();
691 }
692
693 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
694 a.when = a.origWhen;
695 long whenElapsed = convertToElapsed(a.when, a.type);
696 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700697 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700698 // Exact
699 maxElapsed = whenElapsed;
700 } else {
701 // Not exact. Preserve any explicit window, otherwise recalculate
702 // the window based on the alarm's new futurity. Note that this
703 // reflects a policy of preferring timely to deferred delivery.
704 maxElapsed = (a.windowLength > 0)
705 ? (whenElapsed + a.windowLength)
706 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
707 }
708 a.whenElapsed = whenElapsed;
709 a.maxWhenElapsed = maxElapsed;
710 setImplLocked(a, true, doValidate);
711 }
712
713 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700714 if (RECORD_DEVICE_IDLE_ALARMS) {
715 IdleDispatchEntry ent = new IdleDispatchEntry();
716 ent.uid = 0;
717 ent.pkg = "FINISH IDLE";
718 ent.elapsedRealtime = SystemClock.elapsedRealtime();
719 mAllowWhileIdleDispatches.add(ent);
720 }
721
Dianne Hackborn35d54032015-04-23 10:30:43 -0700722 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700723 if (mPendingWhileIdleAlarms.size() > 0) {
724 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
725 mPendingWhileIdleAlarms = new ArrayList<>();
726 final long nowElapsed = SystemClock.elapsedRealtime();
727 for (int i=alarms.size() - 1; i >= 0; i--) {
728 Alarm a = alarms.get(i);
729 reAddAlarmLocked(a, nowElapsed, false);
730 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700731 }
Dianne Hackborn35d54032015-04-23 10:30:43 -0700732
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700733 // Make sure we are using the correct ALLOW_WHILE_IDLE min time.
Dianne Hackborna750a632015-06-16 17:18:23 -0700734 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700735
Dianne Hackborn35d54032015-04-23 10:30:43 -0700736 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700737 rescheduleKernelAlarmsLocked();
738 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -0700739
740 // And send a TIME_TICK right now, since it is important to get the UI updated.
741 try {
742 mTimeTickSender.send();
743 } catch (PendingIntent.CanceledException e) {
744 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700745 }
746
Adam Lesinski182f73f2013-12-05 16:48:06 -0800747 static final class InFlight extends Intent {
Dianne Hackborn81038902012-11-26 17:04:09 -0800748 final PendingIntent mPendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700749 final WorkSource mWorkSource;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700750 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800751 final BroadcastStats mBroadcastStats;
752 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800753 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800754
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800755 InFlight(AlarmManagerService service, PendingIntent pendingIntent, WorkSource workSource,
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700756 int alarmType, String tag, long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800757 mPendingIntent = pendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700758 mWorkSource = workSource;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700759 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800760 mBroadcastStats = service.getStatsLocked(pendingIntent);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700761 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -0800762 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700763 fs = new FilterStats(mBroadcastStats, mTag);
764 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -0800765 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700766 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -0800767 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800768 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800769 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800771
Adam Lesinski182f73f2013-12-05 16:48:06 -0800772 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -0800773 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700774 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800775
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700776 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800778 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779 int numWakeup;
780 long startTime;
781 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -0800782
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700783 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800784 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700785 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800786 }
787 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700788
Adam Lesinski182f73f2013-12-05 16:48:06 -0800789 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800790 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800791 final String mPackageName;
792
793 long aggregateTime;
794 int count;
795 int numWakeup;
796 long startTime;
797 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700798 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -0800799
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800800 BroadcastStats(int uid, String packageName) {
801 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800802 mPackageName = packageName;
803 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800804 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700805
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800806 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
807 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700808
809 int mNumDelayedAlarms = 0;
810 long mTotalDelayTime = 0;
811 long mMaxDelayTime = 0;
812
Adam Lesinski182f73f2013-12-05 16:48:06 -0800813 @Override
814 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800815 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800816 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800817
818 // We have to set current TimeZone info to kernel
819 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -0800820 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800821
Adam Lesinski182f73f2013-12-05 16:48:06 -0800822 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800823 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800824
Adam Lesinski182f73f2013-12-05 16:48:06 -0800825 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700827 Intent.FLAG_RECEIVER_REGISTERED_ONLY
828 | Intent.FLAG_RECEIVER_FOREGROUND), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700829 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800830 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
831 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800832 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700833 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834
835 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -0800836 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 mClockReceiver.scheduleTimeTickEvent();
838 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700839 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 mUninstallReceiver = new UninstallReceiver();
841
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800842 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800843 AlarmThread waitThread = new AlarmThread();
844 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800846 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800848
849 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800851
852 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -0700853 public void onBootPhase(int phase) {
854 if (phase == PHASE_SYSTEM_SERVICES_READY) {
855 mConstants.start(getContext().getContentResolver());
856 }
857 }
858
859 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 protected void finalize() throws Throwable {
861 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800862 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 } finally {
864 super.finalize();
865 }
866 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700867
Adam Lesinski182f73f2013-12-05 16:48:06 -0800868 void setTimeZoneImpl(String tz) {
869 if (TextUtils.isEmpty(tz)) {
870 return;
David Christieebe51fc2013-07-26 13:23:29 -0700871 }
872
Adam Lesinski182f73f2013-12-05 16:48:06 -0800873 TimeZone zone = TimeZone.getTimeZone(tz);
874 // Prevent reentrant calls from stepping on each other when writing
875 // the time zone property
876 boolean timeZoneWasChanged = false;
877 synchronized (this) {
878 String current = SystemProperties.get(TIMEZONE_PROPERTY);
879 if (current == null || !current.equals(zone.getID())) {
880 if (localLOGV) {
881 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
882 }
883 timeZoneWasChanged = true;
884 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
885 }
886
887 // Update the kernel timezone information
888 // Kernel tracks time offsets as 'minutes west of GMT'
889 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800890 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -0800891 }
892
893 TimeZone.setDefault(null);
894
895 if (timeZoneWasChanged) {
896 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
897 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
898 intent.putExtra("time-zone", zone.getID());
899 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
900 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700902
Adam Lesinski182f73f2013-12-05 16:48:06 -0800903 void removeImpl(PendingIntent operation) {
904 if (operation == null) {
905 return;
906 }
907 synchronized (mLock) {
908 removeLocked(operation);
909 }
910 }
911
912 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700913 PendingIntent operation, int flags, WorkSource workSource,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700914 AlarmManager.AlarmClockInfo alarmClock, int callingUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 if (operation == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800916 Slog.w(TAG, "set/setRepeating ignored because there is no intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 return;
918 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700919
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700920 // Sanity check the window length. This will catch people mistakenly
921 // trying to pass an end-of-window timestamp rather than a duration.
922 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
923 Slog.w(TAG, "Window length " + windowLength
924 + "ms suspiciously long; limiting to 1 hour");
925 windowLength = AlarmManager.INTERVAL_HOUR;
926 }
927
Christopher Tate498c6cb2014-11-17 16:09:27 -0800928 // Sanity check the recurrence interval. This will catch people who supply
929 // seconds when the API expects milliseconds.
Dianne Hackborna750a632015-06-16 17:18:23 -0700930 final long minInterval = mConstants.MIN_INTERVAL;
931 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -0800932 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -0700933 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -0800934 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -0700935 interval = minInterval;
Christopher Tate498c6cb2014-11-17 16:09:27 -0800936 }
937
Christopher Tatee0a22b32013-07-11 14:43:13 -0700938 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
939 throw new IllegalArgumentException("Invalid alarm type " + type);
940 }
941
Christopher Tate5f221e82013-07-30 17:13:15 -0700942 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -0700943 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700944 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -0700945 + " pid=" + what);
946 triggerAtTime = 0;
947 }
948
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700949 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -0800950 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
951 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -0700952 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -0800953 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
954
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700955 final long maxElapsed;
956 if (windowLength == AlarmManager.WINDOW_EXACT) {
957 maxElapsed = triggerElapsed;
958 } else if (windowLength < 0) {
959 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700960 // Fix this window in place, so that as time approaches we don't collapse it.
961 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700962 } else {
963 maxElapsed = triggerElapsed + windowLength;
964 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700967 if (DEBUG_BATCH) {
968 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700969 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -0700970 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700971 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 }
Christopher Tate3e04b472013-10-21 17:51:31 -0700973 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700974 interval, operation, flags, true, workSource, alarmClock, callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 }
976 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977
Christopher Tate3e04b472013-10-21 17:51:31 -0700978 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700979 long maxWhen, long interval, PendingIntent operation, int flags,
Jose Lima235510e2014-08-13 12:50:01 -0700980 boolean doValidate, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700981 int uid) {
Christopher Tate3e04b472013-10-21 17:51:31 -0700982 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700983 operation, workSource, flags, alarmClock, uid);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700984 removeLocked(operation);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700985 setImplLocked(a, false, doValidate);
986 }
Christopher Tateb8849c12011-02-08 13:39:01 -0800987
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700988 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
989 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700990 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700991 // The caller has given the time they want this to happen at, however we need
992 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -0700993 // bring us out of idle at an earlier time.
994 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700995 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700996 }
997 // Add fuzz to make the alarm go off some time before the actual desired time.
998 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700999 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001000 if (fuzz > 0) {
1001 if (mRandom == null) {
1002 mRandom = new Random();
1003 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001004 final int delta = mRandom.nextInt(fuzz);
1005 a.whenElapsed -= delta;
1006 if (false) {
1007 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1008 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1009 Slog.d(TAG, "Applied fuzz: " + fuzz);
1010 Slog.d(TAG, "Final delta: " + delta);
1011 Slog.d(TAG, "Final when: " + a.whenElapsed);
1012 }
1013 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001014 }
1015
1016 } else if (mPendingIdleUntil != null) {
1017 // We currently have an idle until alarm scheduled; if the new alarm has
1018 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001019 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1020 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1021 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001022 == 0) {
1023 mPendingWhileIdleAlarms.add(a);
1024 return;
1025 }
1026 }
1027
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001028 if (RECORD_DEVICE_IDLE_ALARMS) {
1029 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1030 IdleDispatchEntry ent = new IdleDispatchEntry();
1031 ent.uid = a.uid;
1032 ent.pkg = a.operation.getCreatorPackage();
1033 ent.tag = a.operation.getTag("");
1034 ent.op = "SET";
1035 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1036 ent.argRealtime = a.whenElapsed;
1037 mAllowWhileIdleDispatches.add(ent);
1038 }
1039 }
1040
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001041 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
1042 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -07001043 if (whichBatch < 0) {
1044 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001045 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 } else {
Christopher Tate385e4982013-07-23 18:22:29 -07001047 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001048 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001049 // The start time of this batch advanced, so batch ordering may
1050 // have just been broken. Move it to where it now belongs.
1051 mAlarmBatches.remove(whichBatch);
1052 addBatchLocked(mAlarmBatches, batch);
1053 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 }
1055
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001056 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001057 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001058 }
1059
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001060 boolean needRebatch = false;
1061
1062 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001063 if (RECORD_DEVICE_IDLE_ALARMS) {
1064 if (mPendingIdleUntil == null) {
1065 IdleDispatchEntry ent = new IdleDispatchEntry();
1066 ent.uid = 0;
1067 ent.pkg = "START IDLE";
1068 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1069 mAllowWhileIdleDispatches.add(ent);
1070 }
1071 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001072 mPendingIdleUntil = a;
Dianne Hackborna750a632015-06-16 17:18:23 -07001073 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001074 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001075 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1076 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1077 mNextWakeFromIdle = a;
1078 // If this wake from idle is earlier than whatever was previously scheduled,
1079 // and we are currently idling, then we need to rebatch alarms in case the idle
1080 // until time needs to be updated.
1081 if (mPendingIdleUntil != null) {
1082 needRebatch = true;
1083 }
1084 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001085 }
1086
1087 if (!rebatching) {
1088 if (DEBUG_VALIDATE) {
1089 if (doValidate && !validateConsistencyLocked()) {
1090 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1091 + " when(hex)=" + Long.toHexString(a.when)
1092 + " whenElapsed=" + a.whenElapsed
1093 + " maxWhenElapsed=" + a.maxWhenElapsed
1094 + " interval=" + a.repeatInterval + " op=" + a.operation
1095 + " flags=0x" + Integer.toHexString(a.flags));
1096 rebatchAllAlarmsLocked(false);
1097 needRebatch = false;
1098 }
1099 }
1100
1101 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001102 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001103 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001104
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001105 rescheduleKernelAlarmsLocked();
1106 updateNextAlarmClockLocked();
1107 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001108 }
1109
Adam Lesinski182f73f2013-12-05 16:48:06 -08001110 private final IBinder mService = new IAlarmManager.Stub() {
1111 @Override
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001112 public void set(int type, long triggerAtTime, long windowLength, long interval, int flags,
Jose Lima235510e2014-08-13 12:50:01 -07001113 PendingIntent operation, WorkSource workSource,
1114 AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001115 final int callingUid = Binder.getCallingUid();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001116 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001117 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001118 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001119 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001120 }
1121
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001122 // No incoming callers can request either WAKE_FROM_IDLE or
1123 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1124 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1125 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1126
1127 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1128 // manager when to come out of idle mode, which is only for DeviceIdleController.
1129 if (callingUid != Process.SYSTEM_UID) {
1130 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1131 }
1132
1133 // If the caller is a core system component, and not calling to do work on behalf
1134 // of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED. This means we
1135 // will allow these alarms to go off as normal even while idle, with no timing
1136 // restrictions.
1137 if (callingUid < Process.FIRST_APPLICATION_UID && workSource == null) {
1138 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1139 }
1140
1141 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001142 if (windowLength == AlarmManager.WINDOW_EXACT) {
1143 flags |= AlarmManager.FLAG_STANDALONE;
1144 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001145
1146 // If this alarm is for an alarm clock, then it must be standalone and we will
1147 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001148 if (alarmClock != null) {
1149 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
1150 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001151
Adam Lesinski182f73f2013-12-05 16:48:06 -08001152 setImpl(type, triggerAtTime, windowLength, interval, operation,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001153 flags, workSource, alarmClock, callingUid);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001154 }
Christopher Tate89779822012-08-31 14:40:03 -07001155
Adam Lesinski182f73f2013-12-05 16:48:06 -08001156 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001157 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001158 getContext().enforceCallingOrSelfPermission(
1159 "android.permission.SET_TIME",
1160 "setTime");
1161
Greg Hackmann0cab8962014-02-21 16:35:52 -08001162 if (mNativeData == 0) {
1163 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1164 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001165 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001166
1167 synchronized (mLock) {
1168 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001170 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001171
1172 @Override
1173 public void setTimeZone(String tz) {
1174 getContext().enforceCallingOrSelfPermission(
1175 "android.permission.SET_TIME_ZONE",
1176 "setTimeZone");
1177
1178 final long oldId = Binder.clearCallingIdentity();
1179 try {
1180 setTimeZoneImpl(tz);
1181 } finally {
1182 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 }
1184 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001185
Adam Lesinski182f73f2013-12-05 16:48:06 -08001186 @Override
1187 public void remove(PendingIntent operation) {
1188 removeImpl(operation);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001191
Adam Lesinski182f73f2013-12-05 16:48:06 -08001192 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001193 public long getNextWakeFromIdleTime() {
1194 return getNextWakeFromIdleTimeImpl();
1195 }
1196
1197 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001198 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001199 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1200 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1201 "getNextAlarmClock", null);
1202
1203 return getNextAlarmClockImpl(userId);
1204 }
1205
1206 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001207 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1208 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1209 != PackageManager.PERMISSION_GRANTED) {
1210 pw.println("Permission Denial: can't dump AlarmManager from from pid="
1211 + Binder.getCallingPid()
1212 + ", uid=" + Binder.getCallingUid());
1213 return;
Christopher Tate4cb338d2013-07-26 13:11:31 -07001214 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001215
Adam Lesinski182f73f2013-12-05 16:48:06 -08001216 dumpImpl(pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001217 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001218 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001219
Adam Lesinski182f73f2013-12-05 16:48:06 -08001220 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001221 synchronized (mLock) {
1222 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001223 mConstants.dump(pw);
1224 pw.println();
1225
Christopher Tatee0a22b32013-07-11 14:43:13 -07001226 final long nowRTC = System.currentTimeMillis();
1227 final long nowELAPSED = SystemClock.elapsedRealtime();
1228 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1229
Dianne Hackborna750a632015-06-16 17:18:23 -07001230 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001231 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001232 pw.print(" nowELAPSED="); TimeUtils.formatDuration(nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001233 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001234 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001235 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001236 pw.print(" mLastTimeChangeRealtime=");
Dianne Hackbornc3527222015-05-13 14:03:20 -07001237 TimeUtils.formatDuration(mLastTimeChangeRealtime, pw);
1238 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001239 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001240 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001241 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1242 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001243 pw.print(" Max wakeup delay: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001244 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1245 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001246 pw.print(" Time since last dispatch: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001247 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1248 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001249 pw.print(" Next non-wakeup delivery time: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001250 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1251 pw.println();
1252 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001253
1254 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1255 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001256 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001257 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001258 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001259 pw.print(" Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001260 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001261 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001262
John Spurlock604a5ee2015-06-01 12:27:22 -04001263 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001264 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001265 final TreeSet<Integer> users = new TreeSet<>();
1266 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1267 users.add(mNextAlarmClockForUser.keyAt(i));
1268 }
1269 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1270 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1271 }
1272 for (int user : users) {
1273 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1274 final long time = next != null ? next.getTriggerTime() : 0;
1275 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001276 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001277 pw.print(" pendingSend:"); pw.print(pendingSend);
1278 pw.print(" time:"); pw.print(time);
1279 if (time > 0) {
1280 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1281 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1282 }
1283 pw.println();
1284 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001285 if (mAlarmBatches.size() > 0) {
1286 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001287 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001288 pw.println(mAlarmBatches.size());
1289 for (Batch b : mAlarmBatches) {
1290 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001291 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001292 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001294 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001295 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001296 pw.println(" Idle mode state:");
1297 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001298 if (mPendingIdleUntil != null) {
1299 pw.println(mPendingIdleUntil);
Dianne Hackbornf3831292015-10-15 14:51:06 -07001300 mPendingIdleUntil.dump(pw, " ", nowRTC, nowELAPSED, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001301 } else {
1302 pw.println("null");
1303 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001304 pw.println(" Pending alarms:");
1305 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001306 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001307 if (mNextWakeFromIdle != null) {
1308 pw.println();
1309 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
1310 mNextWakeFromIdle.dump(pw, " ", nowRTC, nowELAPSED, sdf);
1311 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001312
1313 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001314 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001315 if (mPendingNonWakeupAlarms.size() > 0) {
1316 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001317 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001318 } else {
1319 pw.println("(none)");
1320 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001321 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001322 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1323 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001324 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001325 pw.print(", max non-interactive time: ");
1326 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1327 pw.println();
1328
1329 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001330 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001331 pw.println();
1332
Dianne Hackborna750a632015-06-16 17:18:23 -07001333 pw.print(" mAllowWhileIdleMinTime=");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001334 TimeUtils.formatDuration(mAllowWhileIdleMinTime, pw);
1335 pw.println();
1336 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001337 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001338 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
1339 pw.print(" UID ");
1340 UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
1341 pw.print(": ");
1342 TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i),
1343 nowELAPSED, pw);
1344 pw.println();
1345 }
1346 }
1347 pw.println();
1348
Dianne Hackborn81038902012-11-26 17:04:09 -08001349 if (mLog.dump(pw, " Recent problems", " ")) {
1350 pw.println();
1351 }
1352
1353 final FilterStats[] topFilters = new FilterStats[10];
1354 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1355 @Override
1356 public int compare(FilterStats lhs, FilterStats rhs) {
1357 if (lhs.aggregateTime < rhs.aggregateTime) {
1358 return 1;
1359 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1360 return -1;
1361 }
1362 return 0;
1363 }
1364 };
1365 int len = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001366 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1367 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1368 for (int ip=0; ip<uidStats.size(); ip++) {
1369 BroadcastStats bs = uidStats.valueAt(ip);
1370 for (int is=0; is<bs.filterStats.size(); is++) {
1371 FilterStats fs = bs.filterStats.valueAt(is);
1372 int pos = len > 0
1373 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1374 if (pos < 0) {
1375 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001376 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001377 if (pos < topFilters.length) {
1378 int copylen = topFilters.length - pos - 1;
1379 if (copylen > 0) {
1380 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1381 }
1382 topFilters[pos] = fs;
1383 if (len < topFilters.length) {
1384 len++;
1385 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001386 }
1387 }
1388 }
1389 }
1390 if (len > 0) {
1391 pw.println(" Top Alarms:");
1392 for (int i=0; i<len; i++) {
1393 FilterStats fs = topFilters[i];
1394 pw.print(" ");
1395 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1396 TimeUtils.formatDuration(fs.aggregateTime, pw);
1397 pw.print(" running, "); pw.print(fs.numWakeup);
1398 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001399 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1400 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001401 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001402 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001403 pw.println();
1404 }
1405 }
1406
1407 pw.println(" ");
1408 pw.println(" Alarm Stats:");
1409 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001410 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1411 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1412 for (int ip=0; ip<uidStats.size(); ip++) {
1413 BroadcastStats bs = uidStats.valueAt(ip);
1414 pw.print(" ");
1415 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1416 UserHandle.formatUid(pw, bs.mUid);
1417 pw.print(":");
1418 pw.print(bs.mPackageName);
1419 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1420 pw.print(" running, "); pw.print(bs.numWakeup);
1421 pw.println(" wakeups:");
1422 tmpFilters.clear();
1423 for (int is=0; is<bs.filterStats.size(); is++) {
1424 tmpFilters.add(bs.filterStats.valueAt(is));
1425 }
1426 Collections.sort(tmpFilters, comparator);
1427 for (int i=0; i<tmpFilters.size(); i++) {
1428 FilterStats fs = tmpFilters.get(i);
1429 pw.print(" ");
1430 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1431 TimeUtils.formatDuration(fs.aggregateTime, pw);
1432 pw.print(" "); pw.print(fs.numWakeup);
1433 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001434 pw.print(" alarms, last ");
1435 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1436 pw.println(":");
1437 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001438 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001439 pw.println();
1440 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 }
1442 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001443
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001444 if (RECORD_DEVICE_IDLE_ALARMS) {
1445 pw.println();
1446 pw.println(" Allow while idle dispatches:");
1447 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
1448 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
1449 pw.print(" ");
1450 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
1451 pw.print(": ");
1452 UserHandle.formatUid(pw, ent.uid);
1453 pw.print(":");
1454 pw.println(ent.pkg);
1455 if (ent.op != null) {
1456 pw.print(" ");
1457 pw.print(ent.op);
1458 pw.print(" / ");
1459 pw.print(ent.tag);
1460 if (ent.argRealtime != 0) {
1461 pw.print(" (");
1462 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
1463 pw.print(")");
1464 }
1465 pw.println();
1466 }
1467 }
1468 }
1469
Christopher Tate18a75f12013-07-01 18:18:59 -07001470 if (WAKEUP_STATS) {
1471 pw.println();
1472 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001473 long last = -1;
1474 for (WakeupEvent event : mRecentWakeups) {
1475 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1476 pw.print('|');
1477 if (last < 0) {
1478 pw.print('0');
1479 } else {
1480 pw.print(event.when - last);
1481 }
1482 last = event.when;
1483 pw.print('|'); pw.print(event.uid);
1484 pw.print('|'); pw.print(event.action);
1485 pw.println();
1486 }
1487 pw.println();
1488 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 }
1490 }
1491
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001492 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001493 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
1494 PrintWriter pw = new PrintWriter(bs);
1495 final long nowRTC = System.currentTimeMillis();
1496 final long nowELAPSED = SystemClock.elapsedRealtime();
1497 final int NZ = mAlarmBatches.size();
1498 for (int iz = 0; iz < NZ; iz++) {
1499 Batch bz = mAlarmBatches.get(iz);
1500 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001501 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001502 pw.flush();
1503 Slog.v(TAG, bs.toString());
1504 bs.reset();
1505 }
1506 }
1507
1508 private boolean validateConsistencyLocked() {
1509 if (DEBUG_VALIDATE) {
1510 long lastTime = Long.MIN_VALUE;
1511 final int N = mAlarmBatches.size();
1512 for (int i = 0; i < N; i++) {
1513 Batch b = mAlarmBatches.get(i);
1514 if (b.start >= lastTime) {
1515 // duplicate start times are okay because of standalone batches
1516 lastTime = b.start;
1517 } else {
1518 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001519 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1520 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001521 return false;
1522 }
1523 }
1524 }
1525 return true;
1526 }
1527
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001528 private Batch findFirstWakeupBatchLocked() {
1529 final int N = mAlarmBatches.size();
1530 for (int i = 0; i < N; i++) {
1531 Batch b = mAlarmBatches.get(i);
1532 if (b.hasWakeups()) {
1533 return b;
1534 }
1535 }
1536 return null;
1537 }
1538
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001539 long getNextWakeFromIdleTimeImpl() {
1540 synchronized (mLock) {
1541 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
1542 }
1543 }
1544
1545 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001546 synchronized (mLock) {
1547 return mNextAlarmClockForUser.get(userId);
1548 }
1549 }
1550
1551 /**
1552 * Recomputes the next alarm clock for all users.
1553 */
1554 private void updateNextAlarmClockLocked() {
1555 if (!mNextAlarmClockMayChange) {
1556 return;
1557 }
1558 mNextAlarmClockMayChange = false;
1559
Jose Lima235510e2014-08-13 12:50:01 -07001560 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001561 nextForUser.clear();
1562
1563 final int N = mAlarmBatches.size();
1564 for (int i = 0; i < N; i++) {
1565 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
1566 final int M = alarms.size();
1567
1568 for (int j = 0; j < M; j++) {
1569 Alarm a = alarms.get(j);
1570 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001571 final int userId = UserHandle.getUserId(a.uid);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001572
1573 if (DEBUG_ALARM_CLOCK) {
1574 Log.v(TAG, "Found AlarmClockInfo at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001575 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02001576 " for user " + userId);
1577 }
1578
1579 // Alarms and batches are sorted by time, no need to compare times here.
1580 if (nextForUser.get(userId) == null) {
1581 nextForUser.put(userId, a.alarmClock);
1582 }
1583 }
1584 }
1585 }
1586
1587 // Update mNextAlarmForUser with new values.
1588 final int NN = nextForUser.size();
1589 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07001590 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001591 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001592 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001593 if (!newAlarm.equals(currentAlarm)) {
1594 updateNextAlarmInfoForUserLocked(userId, newAlarm);
1595 }
1596 }
1597
1598 // Remove users without any alarm clocks scheduled.
1599 final int NNN = mNextAlarmClockForUser.size();
1600 for (int i = NNN - 1; i >= 0; i--) {
1601 int userId = mNextAlarmClockForUser.keyAt(i);
1602 if (nextForUser.get(userId) == null) {
1603 updateNextAlarmInfoForUserLocked(userId, null);
1604 }
1605 }
1606 }
1607
Jose Lima235510e2014-08-13 12:50:01 -07001608 private void updateNextAlarmInfoForUserLocked(int userId,
1609 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001610 if (alarmClock != null) {
1611 if (DEBUG_ALARM_CLOCK) {
1612 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001613 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02001614 }
1615 mNextAlarmClockForUser.put(userId, alarmClock);
1616 } else {
1617 if (DEBUG_ALARM_CLOCK) {
1618 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
1619 }
1620 mNextAlarmClockForUser.remove(userId);
1621 }
1622
1623 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
1624 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1625 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1626 }
1627
1628 /**
1629 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
1630 * for which alarm clocks have changed since the last call to this.
1631 *
1632 * Do not call with a lock held. Only call from mHandler's thread.
1633 *
1634 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
1635 */
1636 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07001637 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001638 pendingUsers.clear();
1639
1640 synchronized (mLock) {
1641 final int N = mPendingSendNextAlarmClockChangedForUser.size();
1642 for (int i = 0; i < N; i++) {
1643 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
1644 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
1645 }
1646 mPendingSendNextAlarmClockChangedForUser.clear();
1647 }
1648
1649 final int N = pendingUsers.size();
1650 for (int i = 0; i < N; i++) {
1651 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001652 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001653 Settings.System.putStringForUser(getContext().getContentResolver(),
1654 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01001655 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02001656 userId);
1657
1658 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
1659 new UserHandle(userId));
1660 }
1661 }
1662
1663 /**
1664 * Formats an alarm like platform/packages/apps/DeskClock used to.
1665 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01001666 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
1667 int userId) {
1668 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02001669 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
1670 return (info == null) ? "" :
1671 DateFormat.format(pattern, info.getTriggerTime()).toString();
1672 }
1673
Adam Lesinski182f73f2013-12-05 16:48:06 -08001674 void rescheduleKernelAlarmsLocked() {
1675 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
1676 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001677 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001678 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001679 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001680 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07001681 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001682 mNextWakeup = firstWakeup.start;
1683 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001684 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001685 if (firstBatch != firstWakeup) {
1686 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001687 }
1688 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001689 if (mPendingNonWakeupAlarms.size() > 0) {
1690 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
1691 nextNonWakeup = mNextNonWakeupDeliveryTime;
1692 }
1693 }
Prashant Malani753e9e02015-06-10 17:43:49 -07001694 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001695 mNextNonWakeup = nextNonWakeup;
1696 setLocked(ELAPSED_REALTIME, nextNonWakeup);
1697 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001698 }
1699
1700 private void removeLocked(PendingIntent operation) {
1701 boolean didRemove = false;
1702 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1703 Batch b = mAlarmBatches.get(i);
1704 didRemove |= b.remove(operation);
1705 if (b.size() == 0) {
1706 mAlarmBatches.remove(i);
1707 }
1708 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001709 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1710 if (mPendingWhileIdleAlarms.get(i).operation.equals(operation)) {
1711 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1712 mPendingWhileIdleAlarms.remove(i);
1713 }
1714 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001715
1716 if (didRemove) {
1717 if (DEBUG_BATCH) {
1718 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
1719 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001720 boolean restorePending = false;
1721 if (mPendingIdleUntil != null && mPendingIdleUntil.operation.equals(operation)) {
1722 mPendingIdleUntil = null;
1723 restorePending = true;
1724 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001725 if (mNextWakeFromIdle != null && mNextWakeFromIdle.operation.equals(operation)) {
1726 mNextWakeFromIdle = null;
1727 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001728 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001729 if (restorePending) {
1730 restorePendingWhileIdleAlarmsLocked();
1731 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001732 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001733 }
1734 }
1735
1736 void removeLocked(String packageName) {
1737 boolean didRemove = false;
1738 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1739 Batch b = mAlarmBatches.get(i);
1740 didRemove |= b.remove(packageName);
1741 if (b.size() == 0) {
1742 mAlarmBatches.remove(i);
1743 }
1744 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001745 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1746 if (mPendingWhileIdleAlarms.get(i).operation.getTargetPackage().equals(packageName)) {
1747 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1748 mPendingWhileIdleAlarms.remove(i);
1749 }
1750 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001751
1752 if (didRemove) {
1753 if (DEBUG_BATCH) {
1754 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1755 }
1756 rebatchAllAlarmsLocked(true);
1757 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001758 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001759 }
1760 }
1761
1762 void removeUserLocked(int userHandle) {
1763 boolean didRemove = false;
1764 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1765 Batch b = mAlarmBatches.get(i);
1766 didRemove |= b.remove(userHandle);
1767 if (b.size() == 0) {
1768 mAlarmBatches.remove(i);
1769 }
1770 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001771 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1772 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).operation.getCreatorUid())
1773 == userHandle) {
1774 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1775 mPendingWhileIdleAlarms.remove(i);
1776 }
1777 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001778 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
1779 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
1780 mLastAllowWhileIdleDispatch.removeAt(i);
1781 }
1782 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001783
1784 if (didRemove) {
1785 if (DEBUG_BATCH) {
1786 Slog.v(TAG, "remove(user) changed bounds; rebatching");
1787 }
1788 rebatchAllAlarmsLocked(true);
1789 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001790 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001791 }
1792 }
1793
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001794 void interactiveStateChangedLocked(boolean interactive) {
1795 if (mInteractive != interactive) {
1796 mInteractive = interactive;
1797 final long nowELAPSED = SystemClock.elapsedRealtime();
1798 if (interactive) {
1799 if (mPendingNonWakeupAlarms.size() > 0) {
1800 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1801 mTotalDelayTime += thisDelayTime;
1802 if (mMaxDelayTime < thisDelayTime) {
1803 mMaxDelayTime = thisDelayTime;
1804 }
1805 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
1806 mPendingNonWakeupAlarms.clear();
1807 }
1808 if (mNonInteractiveStartTime > 0) {
1809 long dur = nowELAPSED - mNonInteractiveStartTime;
1810 if (dur > mNonInteractiveTime) {
1811 mNonInteractiveTime = dur;
1812 }
1813 }
1814 } else {
1815 mNonInteractiveStartTime = nowELAPSED;
1816 }
1817 }
1818 }
1819
Adam Lesinski182f73f2013-12-05 16:48:06 -08001820 boolean lookForPackageLocked(String packageName) {
1821 for (int i = 0; i < mAlarmBatches.size(); i++) {
1822 Batch b = mAlarmBatches.get(i);
1823 if (b.hasPackage(packageName)) {
1824 return true;
1825 }
1826 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001827 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
1828 if (mPendingWhileIdleAlarms.get(i).operation.getTargetPackage().equals(packageName)) {
1829 return true;
1830 }
1831 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001832 return false;
1833 }
1834
1835 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001836 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001837 // The kernel never triggers alarms with negative wakeup times
1838 // so we ensure they are positive.
1839 long alarmSeconds, alarmNanoseconds;
1840 if (when < 0) {
1841 alarmSeconds = 0;
1842 alarmNanoseconds = 0;
1843 } else {
1844 alarmSeconds = when / 1000;
1845 alarmNanoseconds = (when % 1000) * 1000 * 1000;
1846 }
1847
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001848 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001849 } else {
1850 Message msg = Message.obtain();
1851 msg.what = ALARM_EVENT;
1852
1853 mHandler.removeMessages(ALARM_EVENT);
1854 mHandler.sendMessageAtTime(msg, when);
1855 }
1856 }
1857
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001858 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001859 String prefix, String label, long nowRTC, long nowELAPSED, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 for (int i=list.size()-1; i>=0; i--) {
1861 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001862 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1863 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001864 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 }
1866 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001867
1868 private static final String labelForType(int type) {
1869 switch (type) {
1870 case RTC: return "RTC";
1871 case RTC_WAKEUP : return "RTC_WAKEUP";
1872 case ELAPSED_REALTIME : return "ELAPSED";
1873 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
1874 default:
1875 break;
1876 }
1877 return "--unknown--";
1878 }
1879
1880 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001881 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001882 for (int i=list.size()-1; i>=0; i--) {
1883 Alarm a = list.get(i);
1884 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001885 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1886 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001887 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001888 }
1889 }
1890
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001891 private native long init();
1892 private native void close(long nativeData);
1893 private native void set(long nativeData, int type, long seconds, long nanoseconds);
1894 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08001895 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001896 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001897
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001898 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001899 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001900 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001901 // batches are temporally sorted, so we need only pull from the
1902 // start of the list until we either empty it or hit a batch
1903 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07001904 while (mAlarmBatches.size() > 0) {
1905 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001906 if (batch.start > nowELAPSED) {
1907 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 break;
1909 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001910
Christopher Tatee0a22b32013-07-11 14:43:13 -07001911 // We will (re)schedule some alarms now; don't let that interfere
1912 // with delivery of this current batch
1913 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001914
Christopher Tatee0a22b32013-07-11 14:43:13 -07001915 final int N = batch.size();
1916 for (int i = 0; i < N; i++) {
1917 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001918
1919 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1920 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
1921 // schedule such alarms.
1922 long lastTime = mLastAllowWhileIdleDispatch.get(alarm.uid, 0);
1923 long minTime = lastTime + mAllowWhileIdleMinTime;
1924 if (nowELAPSED < minTime) {
1925 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
1926 // alarm went off for this app. Reschedule the alarm to be in the
1927 // correct time period.
1928 alarm.whenElapsed = minTime;
1929 if (alarm.maxWhenElapsed < minTime) {
1930 alarm.maxWhenElapsed = minTime;
1931 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001932 if (RECORD_DEVICE_IDLE_ALARMS) {
1933 IdleDispatchEntry ent = new IdleDispatchEntry();
1934 ent.uid = alarm.uid;
1935 ent.pkg = alarm.operation.getCreatorPackage();
1936 ent.tag = alarm.operation.getTag("");
1937 ent.op = "RESCHEDULE";
1938 ent.elapsedRealtime = nowELAPSED;
1939 ent.argRealtime = lastTime;
1940 mAllowWhileIdleDispatches.add(ent);
1941 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001942 setImplLocked(alarm, true, false);
1943 continue;
1944 }
1945 }
1946
Christopher Tatee0a22b32013-07-11 14:43:13 -07001947 alarm.count = 1;
1948 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001949 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1950 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
1951 alarm.tag);
1952 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001953 if (mPendingIdleUntil == alarm) {
1954 mPendingIdleUntil = null;
1955 rebatchAllAlarmsLocked(false);
1956 restorePendingWhileIdleAlarmsLocked();
1957 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001958 if (mNextWakeFromIdle == alarm) {
1959 mNextWakeFromIdle = null;
1960 rebatchAllAlarmsLocked(false);
1961 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001962
1963 // Recurring alarms may have passed several alarm intervals while the
1964 // phone was asleep or off, so pass a trigger count when sending them.
1965 if (alarm.repeatInterval > 0) {
1966 // this adjustment will be zero if we're late by
1967 // less than one full repeat interval
1968 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
1969
1970 // Also schedule its next recurrence
1971 final long delta = alarm.count * alarm.repeatInterval;
1972 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07001973 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07001974 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001975 alarm.repeatInterval, alarm.operation, alarm.flags, true,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001976 alarm.workSource, alarm.alarmClock, alarm.uid);
Christopher Tate864d42e2014-12-02 11:48:53 -08001977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978
Christopher Tate864d42e2014-12-02 11:48:53 -08001979 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001980 hasWakeup = true;
1981 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001982
1983 // We removed an alarm clock. Let the caller recompute the next alarm clock.
1984 if (alarm.alarmClock != null) {
1985 mNextAlarmClockMayChange = true;
1986 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07001987 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001988 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001989
Christopher Tate1590f1e2014-10-02 17:27:57 -07001990 // This is a new alarm delivery set; bump the sequence number to indicate that
1991 // all apps' alarm delivery classes should be recalculated.
1992 mCurrentSeq++;
1993 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001994 Collections.sort(triggerList, mAlarmDispatchComparator);
1995
1996 if (localLOGV) {
1997 for (int i=0; i<triggerList.size(); i++) {
1998 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
1999 }
2000 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002001
2002 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002004
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002005 /**
2006 * This Comparator sorts Alarms into increasing time order.
2007 */
2008 public static class IncreasingTimeOrder implements Comparator<Alarm> {
2009 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09002010 long when1 = a1.whenElapsed;
2011 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002012 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002013 return 1;
2014 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002015 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002016 return -1;
2017 }
2018 return 0;
2019 }
2020 }
2021
2022 private static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002023 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002024 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002025 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002026 public final PendingIntent operation;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002027 public final String tag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002028 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002029 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002030 public final AlarmManager.AlarmClockInfo alarmClock;
2031 public final int uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 public int count;
2033 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07002034 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002035 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002036 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002037 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07002038 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002039
Christopher Tate3e04b472013-10-21 17:51:31 -07002040 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002041 long _interval, PendingIntent _op, WorkSource _ws, int _flags,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002042 AlarmManager.AlarmClockInfo _info, int _uid) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002043 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002044 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002045 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
2046 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002047 when = _when;
2048 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07002049 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002050 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002051 repeatInterval = _interval;
2052 operation = _op;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002053 tag = makeTag(_op, _type);
David Christieebe51fc2013-07-26 13:23:29 -07002054 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002055 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002056 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002057 uid = _uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002059
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002060 public static String makeTag(PendingIntent pi, int type) {
2061 return pi.getTag(type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
2062 ? "*walarm*:" : "*alarm*:");
2063 }
2064
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002065 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002066 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002067 StringBuilder sb = new StringBuilder(128);
2068 sb.append("Alarm{");
2069 sb.append(Integer.toHexString(System.identityHashCode(this)));
2070 sb.append(" type ");
2071 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002072 sb.append(" when ");
2073 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002074 sb.append(" ");
2075 sb.append(operation.getTargetPackage());
2076 sb.append('}');
2077 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002078 }
2079
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002080 public void dump(PrintWriter pw, String prefix, long nowRTC, long nowELAPSED,
2081 SimpleDateFormat sdf) {
2082 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
2083 pw.print(prefix); pw.print("tag="); pw.println(tag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002084 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002085 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
2086 nowELAPSED, pw);
2087 if (isRtc) {
2088 pw.print(" when="); pw.print(sdf.format(new Date(when)));
2089 } else {
2090 pw.print(" when="); TimeUtils.formatDuration(when, nowELAPSED, pw);
2091 }
2092 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002093 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002094 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002095 pw.print(" count="); pw.print(count);
2096 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002097 if (alarmClock != null) {
2098 pw.print(prefix); pw.println("Alarm clock:");
2099 pw.print(prefix); pw.print(" triggerTime=");
2100 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
2101 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
2102 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002103 pw.print(prefix); pw.print("operation="); pw.println(operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002104 }
2105 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002106
Christopher Tatee0a22b32013-07-11 14:43:13 -07002107 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
2108 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002109 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
2110 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002111 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07002112 break;
2113 }
2114
Christopher Tatee0a22b32013-07-11 14:43:13 -07002115 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002116 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
2117 Alarm a = b.alarms.get(nextAlarm);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002118 WakeupEvent e = new WakeupEvent(nowRTC,
2119 a.operation.getCreatorUid(),
2120 a.operation.getIntent().getAction());
2121 mRecentWakeups.add(e);
2122 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002123 }
2124 }
2125
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002126 long currentNonWakeupFuzzLocked(long nowELAPSED) {
2127 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
2128 if (timeSinceOn < 5*60*1000) {
2129 // If the screen has been off for 5 minutes, only delay by at most two minutes.
2130 return 2*60*1000;
2131 } else if (timeSinceOn < 30*60*1000) {
2132 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
2133 return 15*60*1000;
2134 } else {
2135 // Otherwise, we will delay by at most an hour.
2136 return 60*60*1000;
2137 }
2138 }
2139
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002140 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002141 if (duration < 15*60*1000) {
2142 // If the duration until the time is less than 15 minutes, the maximum fuzz
2143 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002144 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002145 } else if (duration < 90*60*1000) {
2146 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
2147 return 15*60*1000;
2148 } else {
2149 // Otherwise, we will fuzz by at most half an hour.
2150 return 30*60*1000;
2151 }
2152 }
2153
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002154 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
2155 if (mInteractive) {
2156 return false;
2157 }
2158 if (mLastAlarmDeliveryTime <= 0) {
2159 return false;
2160 }
minho.choo649acab2014-12-12 16:13:55 +09002161 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002162 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
2163 // and the next delivery time is in the past, then just deliver them all. This
2164 // avoids bugs where we get stuck in a loop trying to poll for alarms.
2165 return false;
2166 }
2167 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
2168 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
2169 }
2170
2171 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
2172 mLastAlarmDeliveryTime = nowELAPSED;
2173 for (int i=0; i<triggerList.size(); i++) {
2174 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07002175 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002176 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07002177 if (localLOGV) {
2178 Slog.v(TAG, "sending alarm " + alarm);
2179 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07002180 if (RECORD_ALARMS_IN_HISTORY) {
2181 if (alarm.workSource != null && alarm.workSource.size() > 0) {
2182 for (int wi=0; wi<alarm.workSource.size(); wi++) {
2183 ActivityManagerNative.noteAlarmStart(
2184 alarm.operation, alarm.workSource.get(wi), alarm.tag);
2185 }
2186 } else {
2187 ActivityManagerNative.noteAlarmStart(
2188 alarm.operation, -1, alarm.tag);
2189 }
2190 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002191 alarm.operation.send(getContext(), 0,
2192 mBackgroundIntent.putExtra(
2193 Intent.EXTRA_ALARM_COUNT, alarm.count),
Dianne Hackborna750a632015-06-16 17:18:23 -07002194 mResultReceiver, mHandler, null, allowWhileIdle ? mIdleOptions : null);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002195
2196 // we have an active broadcast so stay awake.
2197 if (mBroadcastRefCount == 0) {
2198 setWakelockWorkSource(alarm.operation, alarm.workSource,
2199 alarm.type, alarm.tag, true);
2200 mWakeLock.acquire();
2201 }
2202 final InFlight inflight = new InFlight(AlarmManagerService.this,
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002203 alarm.operation, alarm.workSource, alarm.type, alarm.tag, nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002204 mInFlight.add(inflight);
2205 mBroadcastRefCount++;
2206
Dianne Hackborna750a632015-06-16 17:18:23 -07002207 if (allowWhileIdle) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002208 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
2209 mLastAllowWhileIdleDispatch.put(alarm.uid, nowELAPSED);
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002210 if (RECORD_DEVICE_IDLE_ALARMS) {
2211 IdleDispatchEntry ent = new IdleDispatchEntry();
2212 ent.uid = alarm.uid;
2213 ent.pkg = alarm.operation.getCreatorPackage();
2214 ent.tag = alarm.operation.getTag("");
2215 ent.op = "DELIVER";
2216 ent.elapsedRealtime = nowELAPSED;
2217 mAllowWhileIdleDispatches.add(ent);
2218 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002219 }
2220
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002221 final BroadcastStats bs = inflight.mBroadcastStats;
2222 bs.count++;
2223 if (bs.nesting == 0) {
2224 bs.nesting = 1;
2225 bs.startTime = nowELAPSED;
2226 } else {
2227 bs.nesting++;
2228 }
2229 final FilterStats fs = inflight.mFilterStats;
2230 fs.count++;
2231 if (fs.nesting == 0) {
2232 fs.nesting = 1;
2233 fs.startTime = nowELAPSED;
2234 } else {
2235 fs.nesting++;
2236 }
2237 if (alarm.type == ELAPSED_REALTIME_WAKEUP
2238 || alarm.type == RTC_WAKEUP) {
2239 bs.numWakeup++;
2240 fs.numWakeup++;
2241 if (alarm.workSource != null && alarm.workSource.size() > 0) {
2242 for (int wi=0; wi<alarm.workSource.size(); wi++) {
2243 ActivityManagerNative.noteWakeupAlarm(
2244 alarm.operation, alarm.workSource.get(wi),
Dianne Hackborn1e383822015-04-10 14:02:33 -07002245 alarm.workSource.getName(wi), alarm.tag);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002246 }
2247 } else {
2248 ActivityManagerNative.noteWakeupAlarm(
Dianne Hackborn1e383822015-04-10 14:02:33 -07002249 alarm.operation, -1, null, alarm.tag);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002250 }
2251 }
2252 } catch (PendingIntent.CanceledException e) {
2253 if (alarm.repeatInterval > 0) {
2254 // This IntentSender is no longer valid, but this
2255 // is a repeating alarm, so toss the hoser.
2256 removeImpl(alarm.operation);
2257 }
2258 } catch (RuntimeException e) {
2259 Slog.w(TAG, "Failure sending alarm.", e);
2260 }
2261 }
2262 }
2263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002264 private class AlarmThread extends Thread
2265 {
2266 public AlarmThread()
2267 {
2268 super("AlarmManager");
2269 }
2270
2271 public void run()
2272 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002273 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002275 while (true)
2276 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002277 int result = waitForAlarm(mNativeData);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002278
2279 triggerList.clear();
2280
Dianne Hackbornc3527222015-05-13 14:03:20 -07002281 final long nowRTC = System.currentTimeMillis();
2282 final long nowELAPSED = SystemClock.elapsedRealtime();
2283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002284 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002285 // The kernel can give us spurious time change notifications due to
2286 // small adjustments it makes internally; we want to filter those out.
2287 final long lastTimeChangeClockTime;
2288 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07002289 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002290 lastTimeChangeClockTime = mLastTimeChangeClockTime;
2291 expectedClockTime = lastTimeChangeClockTime
2292 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07002293 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002294 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-500)
2295 || nowRTC > (expectedClockTime+500)) {
2296 // The change is by at least +/- 500 ms (or this is the first change),
2297 // let's do it!
2298 if (DEBUG_BATCH) {
2299 Slog.v(TAG, "Time changed notification from kernel; rebatching");
2300 }
2301 removeImpl(mTimeTickSender);
2302 rebatchAllAlarms();
2303 mClockReceiver.scheduleTimeTickEvent();
2304 synchronized (mLock) {
2305 mNumTimeChanged++;
2306 mLastTimeChangeClockTime = nowRTC;
2307 mLastTimeChangeRealtime = nowELAPSED;
2308 }
2309 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
2310 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
2311 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2312 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
2313
2314 // The world has changed on us, so we need to re-evaluate alarms
2315 // regardless of whether the kernel has told us one went off.
2316 result |= IS_WAKEUP_MASK;
2317 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002318 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002319
Dianne Hackbornc3527222015-05-13 14:03:20 -07002320 if (result != TIME_CHANGED_MASK) {
2321 // If this was anything besides just a time change, then figure what if
2322 // anything to do about alarms.
2323 synchronized (mLock) {
2324 if (localLOGV) Slog.v(
2325 TAG, "Checking for alarms... rtc=" + nowRTC
2326 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07002327
Dianne Hackbornc3527222015-05-13 14:03:20 -07002328 if (WAKEUP_STATS) {
2329 if ((result & IS_WAKEUP_MASK) != 0) {
2330 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
2331 int n = 0;
2332 for (WakeupEvent event : mRecentWakeups) {
2333 if (event.when > newEarliest) break;
2334 n++; // number of now-stale entries at the list head
2335 }
2336 for (int i = 0; i < n; i++) {
2337 mRecentWakeups.remove();
2338 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002339
Dianne Hackbornc3527222015-05-13 14:03:20 -07002340 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002341 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002342 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002343
2344 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2345 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
2346 // if there are no wakeup alarms and the screen is off, we can
2347 // delay what we have so far until the future.
2348 if (mPendingNonWakeupAlarms.size() == 0) {
2349 mStartCurrentDelayTime = nowELAPSED;
2350 mNextNonWakeupDeliveryTime = nowELAPSED
2351 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
2352 }
2353 mPendingNonWakeupAlarms.addAll(triggerList);
2354 mNumDelayedAlarms += triggerList.size();
2355 rescheduleKernelAlarmsLocked();
2356 updateNextAlarmClockLocked();
2357 } else {
2358 // now deliver the alarm intents; if there are pending non-wakeup
2359 // alarms, we need to merge them in to the list. note we don't
2360 // just deliver them first because we generally want non-wakeup
2361 // alarms delivered after wakeup alarms.
2362 rescheduleKernelAlarmsLocked();
2363 updateNextAlarmClockLocked();
2364 if (mPendingNonWakeupAlarms.size() > 0) {
2365 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
2366 triggerList.addAll(mPendingNonWakeupAlarms);
2367 Collections.sort(triggerList, mAlarmDispatchComparator);
2368 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2369 mTotalDelayTime += thisDelayTime;
2370 if (mMaxDelayTime < thisDelayTime) {
2371 mMaxDelayTime = thisDelayTime;
2372 }
2373 mPendingNonWakeupAlarms.clear();
2374 }
2375 deliverAlarmsLocked(triggerList, nowELAPSED);
2376 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002377 }
2378 }
2379 }
2380 }
2381 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002382
David Christieebe51fc2013-07-26 13:23:29 -07002383 /**
2384 * Attribute blame for a WakeLock.
2385 * @param pi PendingIntent to attribute blame to if ws is null.
2386 * @param ws WorkSource to attribute blame.
2387 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002388 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
2389 boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07002390 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002391 final boolean unimportant = pi == mTimeTickSender;
2392 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002393 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002394 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002395 } else {
2396 mWakeLock.setHistoryTag(null);
2397 }
2398 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07002399 if (ws != null) {
2400 mWakeLock.setWorkSource(ws);
2401 return;
2402 }
2403
Christopher Tatec4a07d12012-04-06 14:19:13 -07002404 final int uid = ActivityManagerNative.getDefault()
2405 .getUidForIntentSender(pi.getTarget());
2406 if (uid >= 0) {
2407 mWakeLock.setWorkSource(new WorkSource(uid));
2408 return;
2409 }
2410 } catch (Exception e) {
2411 }
2412
2413 // Something went wrong; fall back to attributing the lock to the OS
2414 mWakeLock.setWorkSource(null);
2415 }
2416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002417 private class AlarmHandler extends Handler {
2418 public static final int ALARM_EVENT = 1;
2419 public static final int MINUTE_CHANGE_EVENT = 2;
2420 public static final int DATE_CHANGE_EVENT = 3;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002421 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002422
2423 public AlarmHandler() {
2424 }
2425
2426 public void handleMessage(Message msg) {
2427 if (msg.what == ALARM_EVENT) {
2428 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2429 synchronized (mLock) {
2430 final long nowRTC = System.currentTimeMillis();
Christopher Tatee0a22b32013-07-11 14:43:13 -07002431 final long nowELAPSED = SystemClock.elapsedRealtime();
2432 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002433 updateNextAlarmClockLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002434 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002435
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002436 // now trigger the alarms without the lock held
Dianne Hackborn390517b2013-05-30 15:03:32 -07002437 for (int i=0; i<triggerList.size(); i++) {
2438 Alarm alarm = triggerList.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 try {
2440 alarm.operation.send();
2441 } catch (PendingIntent.CanceledException e) {
2442 if (alarm.repeatInterval > 0) {
2443 // This IntentSender is no longer valid, but this
2444 // is a repeating alarm, so toss the hoser.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002445 removeImpl(alarm.operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002446 }
2447 }
2448 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002449 } else if (msg.what == SEND_NEXT_ALARM_CLOCK_CHANGED) {
2450 sendNextAlarmClockChanged();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002451 }
2452 }
2453 }
2454
2455 class ClockReceiver extends BroadcastReceiver {
2456 public ClockReceiver() {
2457 IntentFilter filter = new IntentFilter();
2458 filter.addAction(Intent.ACTION_TIME_TICK);
2459 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002460 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002461 }
2462
2463 @Override
2464 public void onReceive(Context context, Intent intent) {
2465 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07002466 if (DEBUG_BATCH) {
2467 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
2468 }
2469 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002470 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
2471 // Since the kernel does not keep track of DST, we need to
2472 // reset the TZ information at the beginning of each day
2473 // based off of the current Zone gmt offset + userspace tracked
2474 // daylight savings information.
2475 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02002476 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002477 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07002478 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002479 }
2480 }
2481
2482 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07002483 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09002484 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07002485
2486 // Schedule this event for the amount of time that it would take to get to
2487 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09002488 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07002489
David Christieebe51fc2013-07-26 13:23:29 -07002490 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002491 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002492 0, mTimeTickSender, AlarmManager.FLAG_STANDALONE, workSource, null,
2493 Process.myUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002494 }
Christopher Tate385e4982013-07-23 18:22:29 -07002495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002496 public void scheduleDateChangedEvent() {
2497 Calendar calendar = Calendar.getInstance();
2498 calendar.setTimeInMillis(System.currentTimeMillis());
2499 calendar.set(Calendar.HOUR, 0);
2500 calendar.set(Calendar.MINUTE, 0);
2501 calendar.set(Calendar.SECOND, 0);
2502 calendar.set(Calendar.MILLISECOND, 0);
2503 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07002504
2505 final WorkSource workSource = null; // Let system take blame for date change events.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002506 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002507 AlarmManager.FLAG_STANDALONE, workSource, null, Process.myUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002508 }
2509 }
2510
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002511 class InteractiveStateReceiver extends BroadcastReceiver {
2512 public InteractiveStateReceiver() {
2513 IntentFilter filter = new IntentFilter();
2514 filter.addAction(Intent.ACTION_SCREEN_OFF);
2515 filter.addAction(Intent.ACTION_SCREEN_ON);
2516 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
2517 getContext().registerReceiver(this, filter);
2518 }
2519
2520 @Override
2521 public void onReceive(Context context, Intent intent) {
2522 synchronized (mLock) {
2523 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
2524 }
2525 }
2526 }
2527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002528 class UninstallReceiver extends BroadcastReceiver {
2529 public UninstallReceiver() {
2530 IntentFilter filter = new IntentFilter();
2531 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2532 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002533 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08002535 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002536 // Register for events related to sdcard installation.
2537 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08002538 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002539 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002540 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002541 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 }
2543
2544 @Override
2545 public void onReceive(Context context, Intent intent) {
2546 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002547 String action = intent.getAction();
2548 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002549 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
2550 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
2551 for (String packageName : pkgList) {
2552 if (lookForPackageLocked(packageName)) {
2553 setResultCode(Activity.RESULT_OK);
2554 return;
2555 }
2556 }
2557 return;
2558 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002559 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002560 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
2561 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
2562 if (userHandle >= 0) {
2563 removeUserLocked(userHandle);
2564 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002565 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
2566 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
2567 if (uid >= 0) {
2568 mLastAllowWhileIdleDispatch.delete(uid);
2569 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002570 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08002571 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
2572 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
2573 // This package is being updated; don't kill its alarms.
2574 return;
2575 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002576 Uri data = intent.getData();
2577 if (data != null) {
2578 String pkg = data.getSchemeSpecificPart();
2579 if (pkg != null) {
2580 pkgList = new String[]{pkg};
2581 }
2582 }
2583 }
2584 if (pkgList != null && (pkgList.length > 0)) {
2585 for (String pkg : pkgList) {
2586 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07002587 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002588 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
2589 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
2590 if (uidStats.remove(pkg) != null) {
2591 if (uidStats.size() <= 0) {
2592 mBroadcastStats.removeAt(i);
2593 }
2594 }
2595 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002596 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002597 }
2598 }
2599 }
2600 }
2601
2602 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002603 String pkg = pi.getCreatorPackage();
2604 int uid = pi.getCreatorUid();
2605 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
2606 if (uidStats == null) {
2607 uidStats = new ArrayMap<String, BroadcastStats>();
2608 mBroadcastStats.put(uid, uidStats);
2609 }
2610 BroadcastStats bs = uidStats.get(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002611 if (bs == null) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002612 bs = new BroadcastStats(uid, pkg);
2613 uidStats.put(pkg, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002614 }
2615 return bs;
2616 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002618 class ResultReceiver implements PendingIntent.OnFinished {
2619 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
2620 String resultData, Bundle resultExtras) {
2621 synchronized (mLock) {
Dianne Hackborn81038902012-11-26 17:04:09 -08002622 InFlight inflight = null;
2623 for (int i=0; i<mInFlight.size(); i++) {
2624 if (mInFlight.get(i).mPendingIntent == pi) {
2625 inflight = mInFlight.remove(i);
2626 break;
2627 }
2628 }
2629 if (inflight != null) {
2630 final long nowELAPSED = SystemClock.elapsedRealtime();
2631 BroadcastStats bs = inflight.mBroadcastStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002632 bs.nesting--;
2633 if (bs.nesting <= 0) {
2634 bs.nesting = 0;
Dianne Hackborn81038902012-11-26 17:04:09 -08002635 bs.aggregateTime += nowELAPSED - bs.startTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002636 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002637 FilterStats fs = inflight.mFilterStats;
2638 fs.nesting--;
2639 if (fs.nesting <= 0) {
2640 fs.nesting = 0;
2641 fs.aggregateTime += nowELAPSED - fs.startTime;
2642 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07002643 if (RECORD_ALARMS_IN_HISTORY) {
2644 if (inflight.mWorkSource != null && inflight.mWorkSource.size() > 0) {
2645 for (int wi=0; wi<inflight.mWorkSource.size(); wi++) {
2646 ActivityManagerNative.noteAlarmFinish(
2647 pi, inflight.mWorkSource.get(wi), inflight.mTag);
2648 }
2649 } else {
2650 ActivityManagerNative.noteAlarmFinish(
2651 pi, -1, inflight.mTag);
2652 }
2653 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002654 } else {
2655 mLog.w("No in-flight alarm for " + pi + " " + intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002656 }
2657 mBroadcastRefCount--;
2658 if (mBroadcastRefCount == 0) {
2659 mWakeLock.release();
Dianne Hackborn81038902012-11-26 17:04:09 -08002660 if (mInFlight.size() > 0) {
2661 mLog.w("Finished all broadcasts with " + mInFlight.size()
2662 + " remaining inflights");
2663 for (int i=0; i<mInFlight.size(); i++) {
2664 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
2665 }
2666 mInFlight.clear();
2667 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002668 } else {
2669 // the next of our alarms is now in flight. reattribute the wakelock.
Dianne Hackborn81038902012-11-26 17:04:09 -08002670 if (mInFlight.size() > 0) {
David Christieebe51fc2013-07-26 13:23:29 -07002671 InFlight inFlight = mInFlight.get(0);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08002672 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002673 inFlight.mAlarmType, inFlight.mTag, false);
Christopher Tatec4a07d12012-04-06 14:19:13 -07002674 } else {
2675 // should never happen
Dianne Hackborn81038902012-11-26 17:04:09 -08002676 mLog.w("Alarm wakelock still held but sent queue empty");
Christopher Tatec4a07d12012-04-06 14:19:13 -07002677 mWakeLock.setWorkSource(null);
2678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002679 }
2680 }
2681 }
2682 }
2683}