blob: a5ddc12a2afcb1b479d3e6bb79b8785632869f44 [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;
Christopher Tate14a7bb02015-10-01 10:24:31 -070023import android.app.AppOpsManager;
Dianne Hackborna750a632015-06-16 17:18:23 -070024import android.app.BroadcastOptions;
Christopher Tate14a7bb02015-10-01 10:24:31 -070025import android.app.IAlarmCompleteListener;
26import android.app.IAlarmListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.app.IAlarmManager;
28import android.app.PendingIntent;
29import android.content.BroadcastReceiver;
Dianne Hackborna750a632015-06-16 17:18:23 -070030import android.content.ContentResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.content.Context;
32import android.content.Intent;
33import android.content.IntentFilter;
34import android.content.pm.PackageManager;
Dianne Hackborna750a632015-06-16 17:18:23 -070035import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.net.Uri;
37import android.os.Binder;
38import android.os.Bundle;
39import android.os.Handler;
Adam Lesinski182f73f2013-12-05 16:48:06 -080040import android.os.IBinder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.os.Message;
42import android.os.PowerManager;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070043import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.os.SystemClock;
45import android.os.SystemProperties;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070046import android.os.UserHandle;
Christopher Tatec4a07d12012-04-06 14:19:13 -070047import android.os.WorkSource;
Adrian Roosc42a1e12014-07-07 23:35:53 +020048import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.text.TextUtils;
Adrian Roosc42a1e12014-07-07 23:35:53 +020050import android.text.format.DateFormat;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080051import android.util.ArrayMap;
Dianne Hackborna750a632015-06-16 17:18:23 -070052import android.util.KeyValueListParser;
Adrian Roosc42a1e12014-07-07 23:35:53 +020053import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080054import android.util.Slog;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080055import android.util.SparseArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +020056import android.util.SparseBooleanArray;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -070057import android.util.SparseLongArray;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070058import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059
Christopher Tate4cb338d2013-07-26 13:11:31 -070060import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import java.io.FileDescriptor;
62import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070063import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -080065import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import java.util.Calendar;
67import java.util.Collections;
68import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -050069import java.util.Date;
Christopher Tate1590f1e2014-10-02 17:27:57 -070070import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -070071import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +020072import java.util.Locale;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070073import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import java.util.TimeZone;
John Spurlock604a5ee2015-06-01 12:27:22 -040075import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076
Christopher Tatee0a22b32013-07-11 14:43:13 -070077import static android.app.AlarmManager.RTC_WAKEUP;
78import static android.app.AlarmManager.RTC;
79import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
80import static android.app.AlarmManager.ELAPSED_REALTIME;
81
Dianne Hackborn81038902012-11-26 17:04:09 -080082import com.android.internal.util.LocalLog;
83
Adam Lesinski182f73f2013-12-05 16:48:06 -080084class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -070085 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
86 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -080087 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -070088 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -080089 static final int TIME_CHANGED_MASK = 1 << 16;
90 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -080091
Christopher Tatee0a22b32013-07-11 14:43:13 -070092 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -080093 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -080094
Adam Lesinski182f73f2013-12-05 16:48:06 -080095 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -080096 static final boolean localLOGV = false;
97 static final boolean DEBUG_BATCH = localLOGV || false;
98 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +020099 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700100 static final boolean DEBUG_LISTENER_CALLBACK = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700101 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700102 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800103 static final int ALARM_EVENT = 1;
104 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200105
Christopher Tate14a7bb02015-10-01 10:24:31 -0700106 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800108 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109
Adam Lesinski182f73f2013-12-05 16:48:06 -0800110 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700111
Adrian Roosc42a1e12014-07-07 23:35:53 +0200112 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT = new Intent(
113 AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED);
114
Adam Lesinski182f73f2013-12-05 16:48:06 -0800115 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800116
Christopher Tate14a7bb02015-10-01 10:24:31 -0700117 AppOpsManager mAppOps;
118
Adam Lesinski182f73f2013-12-05 16:48:06 -0800119 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800120
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800121 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800122 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700123 private long mNextNonWakeup;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800124 int mBroadcastRefCount = 0;
125 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700126 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700127 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
128 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800129 final AlarmHandler mHandler = new AlarmHandler();
130 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700131 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700133 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800134 PendingIntent mTimeTickSender;
135 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700136 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700137 boolean mInteractive = true;
138 long mNonInteractiveStartTime;
139 long mNonInteractiveTime;
140 long mLastAlarmDeliveryTime;
141 long mStartCurrentDelayTime;
142 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700143 long mLastTimeChangeClockTime;
144 long mLastTimeChangeRealtime;
Dianne Hackborna750a632015-06-16 17:18:23 -0700145 long mAllowWhileIdleMinTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700146 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800147
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700148 /**
149 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
150 * used to determine the earliest we can dispatch the next such alarm.
151 */
152 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
153
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700154 final static class IdleDispatchEntry {
155 int uid;
156 String pkg;
157 String tag;
158 String op;
159 long elapsedRealtime;
160 long argRealtime;
161 }
162 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
163
Dianne Hackborna750a632015-06-16 17:18:23 -0700164 /**
165 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
166 */
167 Bundle mIdleOptions;
168
Jose Lima235510e2014-08-13 12:50:01 -0700169 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
170 new SparseArray<>();
171 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
172 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200173 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
174 new SparseBooleanArray();
175 private boolean mNextAlarmClockMayChange;
176
177 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700178 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
179 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200180
Dianne Hackborna750a632015-06-16 17:18:23 -0700181 /**
182 * All times are in milliseconds. These constants are kept synchronized with the system
183 * global Settings. Any access to this class or its fields should be done while
184 * holding the AlarmManagerService.mLock lock.
185 */
186 private final class Constants extends ContentObserver {
187 // Key names stored in the settings value.
188 private static final String KEY_MIN_FUTURITY = "min_futurity";
189 private static final String KEY_MIN_INTERVAL = "min_interval";
190 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
191 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
192 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
193 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700194 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Dianne Hackborna750a632015-06-16 17:18:23 -0700195
196 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
197 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tateaa244da2015-08-27 15:57:57 -0700198 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700199 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700200 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
201
Christopher Tate14a7bb02015-10-01 10:24:31 -0700202 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
203
Dianne Hackborna750a632015-06-16 17:18:23 -0700204 // Minimum futurity of a new alarm
205 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
206
207 // Minimum alarm recurrence interval
208 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
209
210 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
211 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
212
213 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
214 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
215
216 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
217 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
218 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
219
Christopher Tate14a7bb02015-10-01 10:24:31 -0700220 // Direct alarm listener callback timeout
221 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
222
Dianne Hackborna750a632015-06-16 17:18:23 -0700223 private ContentResolver mResolver;
224 private final KeyValueListParser mParser = new KeyValueListParser(',');
225 private long mLastAllowWhileIdleWhitelistDuration = -1;
226
227 public Constants(Handler handler) {
228 super(handler);
229 updateAllowWhileIdleMinTimeLocked();
230 updateAllowWhileIdleWhitelistDurationLocked();
231 }
232
233 public void start(ContentResolver resolver) {
234 mResolver = resolver;
235 mResolver.registerContentObserver(Settings.Global.getUriFor(
236 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
237 updateConstants();
238 }
239
240 public void updateAllowWhileIdleMinTimeLocked() {
241 mAllowWhileIdleMinTime = mPendingIdleUntil != null
242 ? ALLOW_WHILE_IDLE_LONG_TIME : ALLOW_WHILE_IDLE_SHORT_TIME;
243 }
244
245 public void updateAllowWhileIdleWhitelistDurationLocked() {
246 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
247 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
248 BroadcastOptions opts = BroadcastOptions.makeBasic();
249 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
250 mIdleOptions = opts.toBundle();
251 }
252 }
253
254 @Override
255 public void onChange(boolean selfChange, Uri uri) {
256 updateConstants();
257 }
258
259 private void updateConstants() {
260 synchronized (mLock) {
261 try {
262 mParser.setString(Settings.Global.getString(mResolver,
263 Settings.Global.ALARM_MANAGER_CONSTANTS));
264 } catch (IllegalArgumentException e) {
265 // Failed to parse the settings string, log this and move on
266 // with defaults.
267 Slog.e(TAG, "Bad device idle settings", e);
268 }
269
270 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
271 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
272 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
273 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
274 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
275 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
276 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
277 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
278 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700279 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
280 DEFAULT_LISTENER_TIMEOUT);
Dianne Hackborna750a632015-06-16 17:18:23 -0700281
282 updateAllowWhileIdleMinTimeLocked();
283 updateAllowWhileIdleWhitelistDurationLocked();
284 }
285 }
286
287 void dump(PrintWriter pw) {
288 pw.println(" Settings:");
289
290 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
291 TimeUtils.formatDuration(MIN_FUTURITY, pw);
292 pw.println();
293
294 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
295 TimeUtils.formatDuration(MIN_INTERVAL, pw);
296 pw.println();
297
Christopher Tate14a7bb02015-10-01 10:24:31 -0700298 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
299 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
300 pw.println();
301
Dianne Hackborna750a632015-06-16 17:18:23 -0700302 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
303 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
304 pw.println();
305
306 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
307 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
308 pw.println();
309
310 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
311 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
312 pw.println();
313 }
314 }
315
316 final Constants mConstants;
317
Christopher Tate1590f1e2014-10-02 17:27:57 -0700318 // Alarm delivery ordering bookkeeping
319 static final int PRIO_TICK = 0;
320 static final int PRIO_WAKEUP = 1;
321 static final int PRIO_NORMAL = 2;
322
Dianne Hackborna750a632015-06-16 17:18:23 -0700323 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700324 int seq;
325 int priority;
326
327 PriorityClass() {
328 seq = mCurrentSeq - 1;
329 priority = PRIO_NORMAL;
330 }
331 }
332
Dianne Hackborna750a632015-06-16 17:18:23 -0700333 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700334 int mCurrentSeq = 0;
335
Dianne Hackborna750a632015-06-16 17:18:23 -0700336 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700337 public long when;
338 public int uid;
339 public String action;
340
341 public WakeupEvent(long theTime, int theUid, String theAction) {
342 when = theTime;
343 uid = theUid;
344 action = theAction;
345 }
346 }
347
Adam Lesinski182f73f2013-12-05 16:48:06 -0800348 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
349 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700350
Adrian Roosc42a1e12014-07-07 23:35:53 +0200351 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700352 long start; // These endpoints are always in ELAPSED
353 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700354 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700355
356 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
357
358 Batch() {
359 start = 0;
360 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700361 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700362 }
363
364 Batch(Alarm seed) {
365 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700366 end = seed.maxWhenElapsed;
367 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700368 alarms.add(seed);
369 }
370
371 int size() {
372 return alarms.size();
373 }
374
375 Alarm get(int index) {
376 return alarms.get(index);
377 }
378
379 boolean canHold(long whenElapsed, long maxWhen) {
380 return (end >= whenElapsed) && (start <= maxWhen);
381 }
382
383 boolean add(Alarm alarm) {
384 boolean newStart = false;
385 // narrows the batch if necessary; presumes that canHold(alarm) is true
386 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
387 if (index < 0) {
388 index = 0 - index - 1;
389 }
390 alarms.add(index, alarm);
391 if (DEBUG_BATCH) {
392 Slog.v(TAG, "Adding " + alarm + " to " + this);
393 }
394 if (alarm.whenElapsed > start) {
395 start = alarm.whenElapsed;
396 newStart = true;
397 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700398 if (alarm.maxWhenElapsed < end) {
399 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700400 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700401 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700402
403 if (DEBUG_BATCH) {
404 Slog.v(TAG, " => now " + this);
405 }
406 return newStart;
407 }
408
Christopher Tate14a7bb02015-10-01 10:24:31 -0700409 boolean remove(final PendingIntent operation, final IAlarmListener listener) {
410 if (operation == null && listener == null) {
411 if (localLOGV) {
412 Slog.w(TAG, "requested remove() of null operation",
413 new RuntimeException("here"));
414 }
415 return false;
416 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700417 boolean didRemove = false;
418 long newStart = 0; // recalculate endpoints as we go
419 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700420 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700421 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700422 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700423 if (alarm.matches(operation, listener)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700424 alarms.remove(i);
425 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200426 if (alarm.alarmClock != null) {
427 mNextAlarmClockMayChange = true;
428 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700429 } else {
430 if (alarm.whenElapsed > newStart) {
431 newStart = alarm.whenElapsed;
432 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700433 if (alarm.maxWhenElapsed < newEnd) {
434 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700435 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700436 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700437 i++;
438 }
439 }
440 if (didRemove) {
441 // commit the new batch bounds
442 start = newStart;
443 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700444 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700445 }
446 return didRemove;
447 }
448
449 boolean remove(final String packageName) {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700450 if (packageName == null) {
451 if (localLOGV) {
452 Slog.w(TAG, "requested remove() of null packageName",
453 new RuntimeException("here"));
454 }
455 return false;
456 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700457 boolean didRemove = false;
458 long newStart = 0; // recalculate endpoints as we go
459 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700460 int newFlags = 0;
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);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700463 if (alarm.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700464 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 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700476 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700477 i++;
478 }
479 }
480 if (didRemove) {
481 // commit the new batch bounds
482 start = newStart;
483 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700484 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700485 }
486 return didRemove;
487 }
488
489 boolean remove(final int userHandle) {
490 boolean didRemove = false;
491 long newStart = 0; // recalculate endpoints as we go
492 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700493 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700494 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700495 if (UserHandle.getUserId(alarm.creatorUid) == userHandle) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700496 alarms.remove(i);
497 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200498 if (alarm.alarmClock != null) {
499 mNextAlarmClockMayChange = true;
500 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700501 } else {
502 if (alarm.whenElapsed > newStart) {
503 newStart = alarm.whenElapsed;
504 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700505 if (alarm.maxWhenElapsed < newEnd) {
506 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700507 }
508 i++;
509 }
510 }
511 if (didRemove) {
512 // commit the new batch bounds
513 start = newStart;
514 end = newEnd;
515 }
516 return didRemove;
517 }
518
519 boolean hasPackage(final String packageName) {
520 final int N = alarms.size();
521 for (int i = 0; i < N; i++) {
522 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700523 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700524 return true;
525 }
526 }
527 return false;
528 }
529
530 boolean hasWakeups() {
531 final int N = alarms.size();
532 for (int i = 0; i < N; i++) {
533 Alarm a = alarms.get(i);
534 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
535 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
536 return true;
537 }
538 }
539 return false;
540 }
541
542 @Override
543 public String toString() {
544 StringBuilder b = new StringBuilder(40);
545 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
546 b.append(" num="); b.append(size());
547 b.append(" start="); b.append(start);
548 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700549 if (flags != 0) {
550 b.append(" flgs=0x");
551 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700552 }
553 b.append('}');
554 return b.toString();
555 }
556 }
557
558 static class BatchTimeOrder implements Comparator<Batch> {
559 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800560 long when1 = b1.start;
561 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800562 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700563 return 1;
564 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800565 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700566 return -1;
567 }
568 return 0;
569 }
570 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800571
572 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
573 @Override
574 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700575 // priority class trumps everything. TICK < WAKEUP < NORMAL
576 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
577 return -1;
578 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
579 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800580 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700581
582 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800583 if (lhs.whenElapsed < rhs.whenElapsed) {
584 return -1;
585 } else if (lhs.whenElapsed > rhs.whenElapsed) {
586 return 1;
587 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700588
589 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800590 return 0;
591 }
592 };
593
Christopher Tate1590f1e2014-10-02 17:27:57 -0700594 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
595 final int N = alarms.size();
596 for (int i = 0; i < N; i++) {
597 Alarm a = alarms.get(i);
598
599 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700600 if (a.operation != null
601 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700602 alarmPrio = PRIO_TICK;
603 } else if (a.wakeup) {
604 alarmPrio = PRIO_WAKEUP;
605 } else {
606 alarmPrio = PRIO_NORMAL;
607 }
608
609 PriorityClass packagePrio = a.priorityClass;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700610 String alarmPackage = (a.operation != null)
611 ? a.operation.getCreatorPackage()
612 : a.packageName;
613 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700614 if (packagePrio == null) {
615 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700616 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700617 }
618 a.priorityClass = packagePrio;
619
620 if (packagePrio.seq != mCurrentSeq) {
621 // first alarm we've seen in the current delivery generation from this package
622 packagePrio.priority = alarmPrio;
623 packagePrio.seq = mCurrentSeq;
624 } else {
625 // Multiple alarms from this package being delivered in this generation;
626 // bump the package's delivery class if it's warranted.
627 // TICK < WAKEUP < NORMAL
628 if (alarmPrio < packagePrio.priority) {
629 packagePrio.priority = alarmPrio;
630 }
631 }
632 }
633 }
634
Christopher Tatee0a22b32013-07-11 14:43:13 -0700635 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800636 static final long MIN_FUZZABLE_INTERVAL = 10000;
637 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700638 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
639
640 // set to null if in idle mode; while in this mode, any alarms we don't want
641 // to run during this time are placed in mPendingWhileIdleAlarms
642 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700643 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700644 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700645
Jeff Brownb880d882014-02-10 19:47:07 -0800646 public AlarmManagerService(Context context) {
647 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700648 mConstants = new Constants(mHandler);
Jeff Brownb880d882014-02-10 19:47:07 -0800649 }
650
Christopher Tatee0a22b32013-07-11 14:43:13 -0700651 static long convertToElapsed(long when, int type) {
652 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
653 if (isRtc) {
654 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
655 }
656 return when;
657 }
658
659 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
660 // calculate the end of our nominal delivery window for the alarm.
661 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
662 // Current heuristic: batchable window is 75% of either the recurrence interval
663 // [for a periodic alarm] or of the time from now to the desired delivery time,
664 // with a minimum delay/interval of 10 seconds, under which we will simply not
665 // defer the alarm.
666 long futurity = (interval == 0)
667 ? (triggerAtTime - now)
668 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700669 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700670 futurity = 0;
671 }
672 return triggerAtTime + (long)(.75 * futurity);
673 }
674
675 // returns true if the batch was added at the head
676 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
677 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
678 if (index < 0) {
679 index = 0 - index - 1;
680 }
681 list.add(index, newBatch);
682 return (index == 0);
683 }
684
Christopher Tate385e4982013-07-23 18:22:29 -0700685 // Return the index of the matching batch, or -1 if none found.
686 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700687 final int N = mAlarmBatches.size();
688 for (int i = 0; i < N; i++) {
689 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700690 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700691 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700692 }
693 }
Christopher Tate385e4982013-07-23 18:22:29 -0700694 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700695 }
696
697 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
698 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700699 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700700 rebatchAllAlarmsLocked(true);
701 }
702 }
703
704 void rebatchAllAlarmsLocked(boolean doValidate) {
705 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
706 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700707 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700708 final long nowElapsed = SystemClock.elapsedRealtime();
709 final int oldBatches = oldSet.size();
710 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
711 Batch batch = oldSet.get(batchNum);
712 final int N = batch.size();
713 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700714 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700715 }
716 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700717 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
718 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
719 + " to " + mPendingIdleUntil);
720 if (mPendingIdleUntil == null) {
721 // Somehow we lost this... we need to restore all of the pending alarms.
722 restorePendingWhileIdleAlarmsLocked();
723 }
724 }
725 rescheduleKernelAlarmsLocked();
726 updateNextAlarmClockLocked();
727 }
728
729 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
730 a.when = a.origWhen;
731 long whenElapsed = convertToElapsed(a.when, a.type);
732 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700733 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700734 // Exact
735 maxElapsed = whenElapsed;
736 } else {
737 // Not exact. Preserve any explicit window, otherwise recalculate
738 // the window based on the alarm's new futurity. Note that this
739 // reflects a policy of preferring timely to deferred delivery.
740 maxElapsed = (a.windowLength > 0)
741 ? (whenElapsed + a.windowLength)
742 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
743 }
744 a.whenElapsed = whenElapsed;
745 a.maxWhenElapsed = maxElapsed;
746 setImplLocked(a, true, doValidate);
747 }
748
749 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700750 if (RECORD_DEVICE_IDLE_ALARMS) {
751 IdleDispatchEntry ent = new IdleDispatchEntry();
752 ent.uid = 0;
753 ent.pkg = "FINISH IDLE";
754 ent.elapsedRealtime = SystemClock.elapsedRealtime();
755 mAllowWhileIdleDispatches.add(ent);
756 }
757
Dianne Hackborn35d54032015-04-23 10:30:43 -0700758 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700759 if (mPendingWhileIdleAlarms.size() > 0) {
760 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
761 mPendingWhileIdleAlarms = new ArrayList<>();
762 final long nowElapsed = SystemClock.elapsedRealtime();
763 for (int i=alarms.size() - 1; i >= 0; i--) {
764 Alarm a = alarms.get(i);
765 reAddAlarmLocked(a, nowElapsed, false);
766 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700767 }
Dianne Hackborn35d54032015-04-23 10:30:43 -0700768
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700769 // Make sure we are using the correct ALLOW_WHILE_IDLE min time.
Dianne Hackborna750a632015-06-16 17:18:23 -0700770 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700771
Dianne Hackborn35d54032015-04-23 10:30:43 -0700772 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700773 rescheduleKernelAlarmsLocked();
774 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -0700775
776 // And send a TIME_TICK right now, since it is important to get the UI updated.
777 try {
778 mTimeTickSender.send();
779 } catch (PendingIntent.CanceledException e) {
780 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700781 }
782
Christopher Tate14a7bb02015-10-01 10:24:31 -0700783 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -0800784 final PendingIntent mPendingIntent;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700785 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -0700786 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700787 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700788 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800789 final BroadcastStats mBroadcastStats;
790 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800791 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800792
Christopher Tate14a7bb02015-10-01 10:24:31 -0700793 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
794 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
795 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800796 mPendingIntent = pendingIntent;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700797 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -0700798 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700799 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700800 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700801 mBroadcastStats = (pendingIntent != null)
802 ? service.getStatsLocked(pendingIntent)
803 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700804 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -0800805 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700806 fs = new FilterStats(mBroadcastStats, mTag);
807 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -0800808 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700809 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -0800810 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800811 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800812 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800813 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800814
Adam Lesinski182f73f2013-12-05 16:48:06 -0800815 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -0800816 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700817 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800818
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700819 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800821 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800822 int numWakeup;
823 long startTime;
824 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -0800825
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700826 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800827 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700828 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800829 }
830 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700831
Adam Lesinski182f73f2013-12-05 16:48:06 -0800832 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800833 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800834 final String mPackageName;
835
836 long aggregateTime;
837 int count;
838 int numWakeup;
839 long startTime;
840 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700841 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -0800842
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800843 BroadcastStats(int uid, String packageName) {
844 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800845 mPackageName = packageName;
846 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700848
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800849 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
850 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700851
852 int mNumDelayedAlarms = 0;
853 long mTotalDelayTime = 0;
854 long mMaxDelayTime = 0;
855
Adam Lesinski182f73f2013-12-05 16:48:06 -0800856 @Override
857 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800858 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800859 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800860
861 // We have to set current TimeZone info to kernel
862 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -0800863 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800864
Adam Lesinski182f73f2013-12-05 16:48:06 -0800865 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800866 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800867
Adam Lesinski182f73f2013-12-05 16:48:06 -0800868 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700870 Intent.FLAG_RECEIVER_REGISTERED_ONLY
871 | Intent.FLAG_RECEIVER_FOREGROUND), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700872 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800873 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
874 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800875 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700876 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877
878 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -0800879 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 mClockReceiver.scheduleTimeTickEvent();
881 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700882 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 mUninstallReceiver = new UninstallReceiver();
884
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800885 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800886 AlarmThread waitThread = new AlarmThread();
887 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800889 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800891
892 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800894
895 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -0700896 public void onBootPhase(int phase) {
897 if (phase == PHASE_SYSTEM_SERVICES_READY) {
898 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -0700899 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborna750a632015-06-16 17:18:23 -0700900 }
901 }
902
903 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 protected void finalize() throws Throwable {
905 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800906 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 } finally {
908 super.finalize();
909 }
910 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700911
Adam Lesinski182f73f2013-12-05 16:48:06 -0800912 void setTimeZoneImpl(String tz) {
913 if (TextUtils.isEmpty(tz)) {
914 return;
David Christieebe51fc2013-07-26 13:23:29 -0700915 }
916
Adam Lesinski182f73f2013-12-05 16:48:06 -0800917 TimeZone zone = TimeZone.getTimeZone(tz);
918 // Prevent reentrant calls from stepping on each other when writing
919 // the time zone property
920 boolean timeZoneWasChanged = false;
921 synchronized (this) {
922 String current = SystemProperties.get(TIMEZONE_PROPERTY);
923 if (current == null || !current.equals(zone.getID())) {
924 if (localLOGV) {
925 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
926 }
927 timeZoneWasChanged = true;
928 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
929 }
930
931 // Update the kernel timezone information
932 // Kernel tracks time offsets as 'minutes west of GMT'
933 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800934 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -0800935 }
936
937 TimeZone.setDefault(null);
938
939 if (timeZoneWasChanged) {
940 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
941 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
942 intent.putExtra("time-zone", zone.getID());
943 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
944 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700946
Adam Lesinski182f73f2013-12-05 16:48:06 -0800947 void removeImpl(PendingIntent operation) {
948 if (operation == null) {
949 return;
950 }
951 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700952 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800953 }
954 }
955
956 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -0700957 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
958 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
959 int callingUid, String callingPackage) {
960 // must be *either* PendingIntent or AlarmReceiver, but not both
961 if ((operation == null && directReceiver == null)
962 || (operation != null && directReceiver != null)) {
963 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
964 // NB: previous releases failed silently here, so we are continuing to do the same
965 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 return;
967 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700968
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700969 // Sanity check the window length. This will catch people mistakenly
970 // trying to pass an end-of-window timestamp rather than a duration.
971 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
972 Slog.w(TAG, "Window length " + windowLength
973 + "ms suspiciously long; limiting to 1 hour");
974 windowLength = AlarmManager.INTERVAL_HOUR;
975 }
976
Christopher Tate498c6cb2014-11-17 16:09:27 -0800977 // Sanity check the recurrence interval. This will catch people who supply
978 // seconds when the API expects milliseconds.
Dianne Hackborna750a632015-06-16 17:18:23 -0700979 final long minInterval = mConstants.MIN_INTERVAL;
980 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -0800981 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -0700982 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -0800983 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -0700984 interval = minInterval;
Christopher Tate498c6cb2014-11-17 16:09:27 -0800985 }
986
Christopher Tatee0a22b32013-07-11 14:43:13 -0700987 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
988 throw new IllegalArgumentException("Invalid alarm type " + type);
989 }
990
Christopher Tate5f221e82013-07-30 17:13:15 -0700991 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -0700992 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700993 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -0700994 + " pid=" + what);
995 triggerAtTime = 0;
996 }
997
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700998 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -0800999 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1000 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001001 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001002 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1003
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001004 final long maxElapsed;
1005 if (windowLength == AlarmManager.WINDOW_EXACT) {
1006 maxElapsed = triggerElapsed;
1007 } else if (windowLength < 0) {
1008 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001009 // Fix this window in place, so that as time approaches we don't collapse it.
1010 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001011 } else {
1012 maxElapsed = triggerElapsed + windowLength;
1013 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001014
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001016 if (DEBUG_BATCH) {
1017 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001018 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001019 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001020 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001022 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001023 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1024 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025 }
1026 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027
Christopher Tate3e04b472013-10-21 17:51:31 -07001028 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001029 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1030 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1031 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001032 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001033 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1034 callingUid, callingPackage);
1035 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001036 setImplLocked(a, false, doValidate);
1037 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001038
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001039 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1040 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001041 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001042 // The caller has given the time they want this to happen at, however we need
1043 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001044 // bring us out of idle at an earlier time.
1045 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001046 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001047 }
1048 // Add fuzz to make the alarm go off some time before the actual desired time.
1049 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001050 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001051 if (fuzz > 0) {
1052 if (mRandom == null) {
1053 mRandom = new Random();
1054 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001055 final int delta = mRandom.nextInt(fuzz);
1056 a.whenElapsed -= delta;
1057 if (false) {
1058 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1059 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1060 Slog.d(TAG, "Applied fuzz: " + fuzz);
1061 Slog.d(TAG, "Final delta: " + delta);
1062 Slog.d(TAG, "Final when: " + a.whenElapsed);
1063 }
1064 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001065 }
1066
1067 } else if (mPendingIdleUntil != null) {
1068 // We currently have an idle until alarm scheduled; if the new alarm has
1069 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001070 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1071 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1072 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001073 == 0) {
1074 mPendingWhileIdleAlarms.add(a);
1075 return;
1076 }
1077 }
1078
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001079 if (RECORD_DEVICE_IDLE_ALARMS) {
1080 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1081 IdleDispatchEntry ent = new IdleDispatchEntry();
1082 ent.uid = a.uid;
1083 ent.pkg = a.operation.getCreatorPackage();
1084 ent.tag = a.operation.getTag("");
1085 ent.op = "SET";
1086 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1087 ent.argRealtime = a.whenElapsed;
1088 mAllowWhileIdleDispatches.add(ent);
1089 }
1090 }
1091
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001092 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
1093 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -07001094 if (whichBatch < 0) {
1095 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001096 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 } else {
Christopher Tate385e4982013-07-23 18:22:29 -07001098 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001099 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001100 // The start time of this batch advanced, so batch ordering may
1101 // have just been broken. Move it to where it now belongs.
1102 mAlarmBatches.remove(whichBatch);
1103 addBatchLocked(mAlarmBatches, batch);
1104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 }
1106
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001107 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001108 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001109 }
1110
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001111 boolean needRebatch = false;
1112
1113 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001114 if (RECORD_DEVICE_IDLE_ALARMS) {
1115 if (mPendingIdleUntil == null) {
1116 IdleDispatchEntry ent = new IdleDispatchEntry();
1117 ent.uid = 0;
1118 ent.pkg = "START IDLE";
1119 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1120 mAllowWhileIdleDispatches.add(ent);
1121 }
1122 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001123 mPendingIdleUntil = a;
Dianne Hackborna750a632015-06-16 17:18:23 -07001124 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001125 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001126 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1127 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1128 mNextWakeFromIdle = a;
1129 // If this wake from idle is earlier than whatever was previously scheduled,
1130 // and we are currently idling, then we need to rebatch alarms in case the idle
1131 // until time needs to be updated.
1132 if (mPendingIdleUntil != null) {
1133 needRebatch = true;
1134 }
1135 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001136 }
1137
1138 if (!rebatching) {
1139 if (DEBUG_VALIDATE) {
1140 if (doValidate && !validateConsistencyLocked()) {
1141 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1142 + " when(hex)=" + Long.toHexString(a.when)
1143 + " whenElapsed=" + a.whenElapsed
1144 + " maxWhenElapsed=" + a.maxWhenElapsed
1145 + " interval=" + a.repeatInterval + " op=" + a.operation
1146 + " flags=0x" + Integer.toHexString(a.flags));
1147 rebatchAllAlarmsLocked(false);
1148 needRebatch = false;
1149 }
1150 }
1151
1152 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001153 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001154 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001155
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001156 rescheduleKernelAlarmsLocked();
1157 updateNextAlarmClockLocked();
1158 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001159 }
1160
Adam Lesinski182f73f2013-12-05 16:48:06 -08001161 private final IBinder mService = new IAlarmManager.Stub() {
1162 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001163 public void set(String callingPackage,
1164 int type, long triggerAtTime, long windowLength, long interval, int flags,
1165 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1166 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001167 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001168
1169 // make sure the caller is not lying about which package should be blamed for
1170 // wakelock time spent in alarm delivery
1171 mAppOps.checkPackage(callingUid, callingPackage);
1172
1173 // Repeating alarms must use PendingIntent, not direct listener
1174 if (interval != 0) {
1175 if (directReceiver != null) {
1176 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1177 }
1178 }
1179
1180 // direct-callback alarms must be wakeup alarms (otherwise they should just be
1181 // posting work to a Handler)
1182 if (directReceiver != null) {
1183 if (type != RTC_WAKEUP && type != ELAPSED_REALTIME_WAKEUP) {
1184 throw new IllegalArgumentException("Only wakeup alarms can use AlarmReceivers");
1185 }
1186 }
1187
Adam Lesinski182f73f2013-12-05 16:48:06 -08001188 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001189 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001190 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001191 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001192 }
1193
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001194 // No incoming callers can request either WAKE_FROM_IDLE or
1195 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1196 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1197 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1198
1199 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1200 // manager when to come out of idle mode, which is only for DeviceIdleController.
1201 if (callingUid != Process.SYSTEM_UID) {
1202 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1203 }
1204
1205 // If the caller is a core system component, and not calling to do work on behalf
1206 // of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED. This means we
1207 // will allow these alarms to go off as normal even while idle, with no timing
1208 // restrictions.
1209 if (callingUid < Process.FIRST_APPLICATION_UID && workSource == null) {
1210 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1211 }
1212
1213 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001214 if (windowLength == AlarmManager.WINDOW_EXACT) {
1215 flags |= AlarmManager.FLAG_STANDALONE;
1216 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001217
1218 // If this alarm is for an alarm clock, then it must be standalone and we will
1219 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001220 if (alarmClock != null) {
1221 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
1222 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001223
Christopher Tate14a7bb02015-10-01 10:24:31 -07001224 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1225 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001226 }
Christopher Tate89779822012-08-31 14:40:03 -07001227
Adam Lesinski182f73f2013-12-05 16:48:06 -08001228 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001229 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001230 getContext().enforceCallingOrSelfPermission(
1231 "android.permission.SET_TIME",
1232 "setTime");
1233
Greg Hackmann0cab8962014-02-21 16:35:52 -08001234 if (mNativeData == 0) {
1235 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1236 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001237 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001238
1239 synchronized (mLock) {
1240 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001241 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001242 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001243
1244 @Override
1245 public void setTimeZone(String tz) {
1246 getContext().enforceCallingOrSelfPermission(
1247 "android.permission.SET_TIME_ZONE",
1248 "setTimeZone");
1249
1250 final long oldId = Binder.clearCallingIdentity();
1251 try {
1252 setTimeZoneImpl(tz);
1253 } finally {
1254 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 }
1256 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001257
Adam Lesinski182f73f2013-12-05 16:48:06 -08001258 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001259 public void remove(PendingIntent operation, IAlarmListener listener) {
1260 if (operation == null && listener == null) {
1261 Slog.w(TAG, "remove() with no intent or listener");
1262 return;
1263 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001264
Christopher Tate14a7bb02015-10-01 10:24:31 -07001265 synchronized (mLock) {
1266 removeLocked(operation, listener);
1267 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001269
Adam Lesinski182f73f2013-12-05 16:48:06 -08001270 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001271 public long getNextWakeFromIdleTime() {
1272 return getNextWakeFromIdleTimeImpl();
1273 }
1274
1275 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001276 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001277 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1278 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1279 "getNextAlarmClock", null);
1280
1281 return getNextAlarmClockImpl(userId);
1282 }
1283
1284 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001285 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1286 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1287 != PackageManager.PERMISSION_GRANTED) {
1288 pw.println("Permission Denial: can't dump AlarmManager from from pid="
1289 + Binder.getCallingPid()
1290 + ", uid=" + Binder.getCallingUid());
1291 return;
Christopher Tate4cb338d2013-07-26 13:11:31 -07001292 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001293
Adam Lesinski182f73f2013-12-05 16:48:06 -08001294 dumpImpl(pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001295 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001296 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001297
Adam Lesinski182f73f2013-12-05 16:48:06 -08001298 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 synchronized (mLock) {
1300 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001301 mConstants.dump(pw);
1302 pw.println();
1303
Christopher Tatee0a22b32013-07-11 14:43:13 -07001304 final long nowRTC = System.currentTimeMillis();
1305 final long nowELAPSED = SystemClock.elapsedRealtime();
1306 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1307
Dianne Hackborna750a632015-06-16 17:18:23 -07001308 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001309 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001310 pw.print(" nowELAPSED="); TimeUtils.formatDuration(nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001311 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001312 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001313 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001314 pw.print(" mLastTimeChangeRealtime=");
Dianne Hackbornc3527222015-05-13 14:03:20 -07001315 TimeUtils.formatDuration(mLastTimeChangeRealtime, pw);
1316 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001317 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001318 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001319 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1320 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001321 pw.print(" Max wakeup delay: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001322 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1323 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001324 pw.print(" Time since last dispatch: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001325 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1326 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001327 pw.print(" Next non-wakeup delivery time: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001328 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1329 pw.println();
1330 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001331
1332 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1333 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001334 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001335 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001336 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001337 pw.print(" Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001338 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001339 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001340
John Spurlock604a5ee2015-06-01 12:27:22 -04001341 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001342 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001343 final TreeSet<Integer> users = new TreeSet<>();
1344 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1345 users.add(mNextAlarmClockForUser.keyAt(i));
1346 }
1347 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1348 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1349 }
1350 for (int user : users) {
1351 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1352 final long time = next != null ? next.getTriggerTime() : 0;
1353 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001354 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001355 pw.print(" pendingSend:"); pw.print(pendingSend);
1356 pw.print(" time:"); pw.print(time);
1357 if (time > 0) {
1358 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1359 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1360 }
1361 pw.println();
1362 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001363 if (mAlarmBatches.size() > 0) {
1364 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001365 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001366 pw.println(mAlarmBatches.size());
1367 for (Batch b : mAlarmBatches) {
1368 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001369 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001371 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001372 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001373 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001374 pw.println(" Idle mode state:");
1375 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001376 if (mPendingIdleUntil != null) {
1377 pw.println(mPendingIdleUntil);
Dianne Hackbornf3831292015-10-15 14:51:06 -07001378 mPendingIdleUntil.dump(pw, " ", nowRTC, nowELAPSED, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001379 } else {
1380 pw.println("null");
1381 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001382 pw.println(" Pending alarms:");
1383 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001384 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001385 if (mNextWakeFromIdle != null) {
1386 pw.println();
1387 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
1388 mNextWakeFromIdle.dump(pw, " ", nowRTC, nowELAPSED, sdf);
1389 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001390
1391 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001392 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001393 if (mPendingNonWakeupAlarms.size() > 0) {
1394 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001395 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001396 } else {
1397 pw.println("(none)");
1398 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001399 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001400 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1401 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001402 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001403 pw.print(", max non-interactive time: ");
1404 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1405 pw.println();
1406
1407 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001408 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001409 pw.println();
1410
Dianne Hackborna750a632015-06-16 17:18:23 -07001411 pw.print(" mAllowWhileIdleMinTime=");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001412 TimeUtils.formatDuration(mAllowWhileIdleMinTime, pw);
1413 pw.println();
1414 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001415 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001416 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
1417 pw.print(" UID ");
1418 UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
1419 pw.print(": ");
1420 TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i),
1421 nowELAPSED, pw);
1422 pw.println();
1423 }
1424 }
1425 pw.println();
1426
Dianne Hackborn81038902012-11-26 17:04:09 -08001427 if (mLog.dump(pw, " Recent problems", " ")) {
1428 pw.println();
1429 }
1430
1431 final FilterStats[] topFilters = new FilterStats[10];
1432 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1433 @Override
1434 public int compare(FilterStats lhs, FilterStats rhs) {
1435 if (lhs.aggregateTime < rhs.aggregateTime) {
1436 return 1;
1437 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1438 return -1;
1439 }
1440 return 0;
1441 }
1442 };
1443 int len = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001444 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1445 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1446 for (int ip=0; ip<uidStats.size(); ip++) {
1447 BroadcastStats bs = uidStats.valueAt(ip);
1448 for (int is=0; is<bs.filterStats.size(); is++) {
1449 FilterStats fs = bs.filterStats.valueAt(is);
1450 int pos = len > 0
1451 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1452 if (pos < 0) {
1453 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001454 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001455 if (pos < topFilters.length) {
1456 int copylen = topFilters.length - pos - 1;
1457 if (copylen > 0) {
1458 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1459 }
1460 topFilters[pos] = fs;
1461 if (len < topFilters.length) {
1462 len++;
1463 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001464 }
1465 }
1466 }
1467 }
1468 if (len > 0) {
1469 pw.println(" Top Alarms:");
1470 for (int i=0; i<len; i++) {
1471 FilterStats fs = topFilters[i];
1472 pw.print(" ");
1473 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1474 TimeUtils.formatDuration(fs.aggregateTime, pw);
1475 pw.print(" running, "); pw.print(fs.numWakeup);
1476 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001477 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1478 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001479 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001480 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001481 pw.println();
1482 }
1483 }
1484
1485 pw.println(" ");
1486 pw.println(" Alarm Stats:");
1487 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001488 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1489 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1490 for (int ip=0; ip<uidStats.size(); ip++) {
1491 BroadcastStats bs = uidStats.valueAt(ip);
1492 pw.print(" ");
1493 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1494 UserHandle.formatUid(pw, bs.mUid);
1495 pw.print(":");
1496 pw.print(bs.mPackageName);
1497 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1498 pw.print(" running, "); pw.print(bs.numWakeup);
1499 pw.println(" wakeups:");
1500 tmpFilters.clear();
1501 for (int is=0; is<bs.filterStats.size(); is++) {
1502 tmpFilters.add(bs.filterStats.valueAt(is));
1503 }
1504 Collections.sort(tmpFilters, comparator);
1505 for (int i=0; i<tmpFilters.size(); i++) {
1506 FilterStats fs = tmpFilters.get(i);
1507 pw.print(" ");
1508 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1509 TimeUtils.formatDuration(fs.aggregateTime, pw);
1510 pw.print(" "); pw.print(fs.numWakeup);
1511 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001512 pw.print(" alarms, last ");
1513 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1514 pw.println(":");
1515 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001516 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001517 pw.println();
1518 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 }
1520 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001521
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001522 if (RECORD_DEVICE_IDLE_ALARMS) {
1523 pw.println();
1524 pw.println(" Allow while idle dispatches:");
1525 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
1526 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
1527 pw.print(" ");
1528 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
1529 pw.print(": ");
1530 UserHandle.formatUid(pw, ent.uid);
1531 pw.print(":");
1532 pw.println(ent.pkg);
1533 if (ent.op != null) {
1534 pw.print(" ");
1535 pw.print(ent.op);
1536 pw.print(" / ");
1537 pw.print(ent.tag);
1538 if (ent.argRealtime != 0) {
1539 pw.print(" (");
1540 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
1541 pw.print(")");
1542 }
1543 pw.println();
1544 }
1545 }
1546 }
1547
Christopher Tate18a75f12013-07-01 18:18:59 -07001548 if (WAKEUP_STATS) {
1549 pw.println();
1550 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001551 long last = -1;
1552 for (WakeupEvent event : mRecentWakeups) {
1553 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1554 pw.print('|');
1555 if (last < 0) {
1556 pw.print('0');
1557 } else {
1558 pw.print(event.when - last);
1559 }
1560 last = event.when;
1561 pw.print('|'); pw.print(event.uid);
1562 pw.print('|'); pw.print(event.action);
1563 pw.println();
1564 }
1565 pw.println();
1566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 }
1568 }
1569
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001570 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001571 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
1572 PrintWriter pw = new PrintWriter(bs);
1573 final long nowRTC = System.currentTimeMillis();
1574 final long nowELAPSED = SystemClock.elapsedRealtime();
1575 final int NZ = mAlarmBatches.size();
1576 for (int iz = 0; iz < NZ; iz++) {
1577 Batch bz = mAlarmBatches.get(iz);
1578 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001579 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001580 pw.flush();
1581 Slog.v(TAG, bs.toString());
1582 bs.reset();
1583 }
1584 }
1585
1586 private boolean validateConsistencyLocked() {
1587 if (DEBUG_VALIDATE) {
1588 long lastTime = Long.MIN_VALUE;
1589 final int N = mAlarmBatches.size();
1590 for (int i = 0; i < N; i++) {
1591 Batch b = mAlarmBatches.get(i);
1592 if (b.start >= lastTime) {
1593 // duplicate start times are okay because of standalone batches
1594 lastTime = b.start;
1595 } else {
1596 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001597 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1598 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001599 return false;
1600 }
1601 }
1602 }
1603 return true;
1604 }
1605
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001606 private Batch findFirstWakeupBatchLocked() {
1607 final int N = mAlarmBatches.size();
1608 for (int i = 0; i < N; i++) {
1609 Batch b = mAlarmBatches.get(i);
1610 if (b.hasWakeups()) {
1611 return b;
1612 }
1613 }
1614 return null;
1615 }
1616
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001617 long getNextWakeFromIdleTimeImpl() {
1618 synchronized (mLock) {
1619 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
1620 }
1621 }
1622
1623 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001624 synchronized (mLock) {
1625 return mNextAlarmClockForUser.get(userId);
1626 }
1627 }
1628
1629 /**
1630 * Recomputes the next alarm clock for all users.
1631 */
1632 private void updateNextAlarmClockLocked() {
1633 if (!mNextAlarmClockMayChange) {
1634 return;
1635 }
1636 mNextAlarmClockMayChange = false;
1637
Jose Lima235510e2014-08-13 12:50:01 -07001638 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001639 nextForUser.clear();
1640
1641 final int N = mAlarmBatches.size();
1642 for (int i = 0; i < N; i++) {
1643 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
1644 final int M = alarms.size();
1645
1646 for (int j = 0; j < M; j++) {
1647 Alarm a = alarms.get(j);
1648 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001649 final int userId = UserHandle.getUserId(a.uid);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001650
1651 if (DEBUG_ALARM_CLOCK) {
1652 Log.v(TAG, "Found AlarmClockInfo at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001653 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02001654 " for user " + userId);
1655 }
1656
1657 // Alarms and batches are sorted by time, no need to compare times here.
1658 if (nextForUser.get(userId) == null) {
1659 nextForUser.put(userId, a.alarmClock);
1660 }
1661 }
1662 }
1663 }
1664
1665 // Update mNextAlarmForUser with new values.
1666 final int NN = nextForUser.size();
1667 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07001668 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001669 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001670 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001671 if (!newAlarm.equals(currentAlarm)) {
1672 updateNextAlarmInfoForUserLocked(userId, newAlarm);
1673 }
1674 }
1675
1676 // Remove users without any alarm clocks scheduled.
1677 final int NNN = mNextAlarmClockForUser.size();
1678 for (int i = NNN - 1; i >= 0; i--) {
1679 int userId = mNextAlarmClockForUser.keyAt(i);
1680 if (nextForUser.get(userId) == null) {
1681 updateNextAlarmInfoForUserLocked(userId, null);
1682 }
1683 }
1684 }
1685
Jose Lima235510e2014-08-13 12:50:01 -07001686 private void updateNextAlarmInfoForUserLocked(int userId,
1687 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001688 if (alarmClock != null) {
1689 if (DEBUG_ALARM_CLOCK) {
1690 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001691 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02001692 }
1693 mNextAlarmClockForUser.put(userId, alarmClock);
1694 } else {
1695 if (DEBUG_ALARM_CLOCK) {
1696 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
1697 }
1698 mNextAlarmClockForUser.remove(userId);
1699 }
1700
1701 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
1702 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1703 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1704 }
1705
1706 /**
1707 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
1708 * for which alarm clocks have changed since the last call to this.
1709 *
1710 * Do not call with a lock held. Only call from mHandler's thread.
1711 *
1712 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
1713 */
1714 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07001715 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001716 pendingUsers.clear();
1717
1718 synchronized (mLock) {
1719 final int N = mPendingSendNextAlarmClockChangedForUser.size();
1720 for (int i = 0; i < N; i++) {
1721 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
1722 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
1723 }
1724 mPendingSendNextAlarmClockChangedForUser.clear();
1725 }
1726
1727 final int N = pendingUsers.size();
1728 for (int i = 0; i < N; i++) {
1729 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001730 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001731 Settings.System.putStringForUser(getContext().getContentResolver(),
1732 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01001733 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02001734 userId);
1735
1736 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
1737 new UserHandle(userId));
1738 }
1739 }
1740
1741 /**
1742 * Formats an alarm like platform/packages/apps/DeskClock used to.
1743 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01001744 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
1745 int userId) {
1746 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02001747 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
1748 return (info == null) ? "" :
1749 DateFormat.format(pattern, info.getTriggerTime()).toString();
1750 }
1751
Adam Lesinski182f73f2013-12-05 16:48:06 -08001752 void rescheduleKernelAlarmsLocked() {
1753 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
1754 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001755 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001756 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001757 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001758 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07001759 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001760 mNextWakeup = firstWakeup.start;
1761 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001762 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001763 if (firstBatch != firstWakeup) {
1764 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001765 }
1766 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001767 if (mPendingNonWakeupAlarms.size() > 0) {
1768 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
1769 nextNonWakeup = mNextNonWakeupDeliveryTime;
1770 }
1771 }
Prashant Malani753e9e02015-06-10 17:43:49 -07001772 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001773 mNextNonWakeup = nextNonWakeup;
1774 setLocked(ELAPSED_REALTIME, nextNonWakeup);
1775 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001776 }
1777
Christopher Tate14a7bb02015-10-01 10:24:31 -07001778 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001779 boolean didRemove = false;
1780 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1781 Batch b = mAlarmBatches.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -07001782 didRemove |= b.remove(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001783 if (b.size() == 0) {
1784 mAlarmBatches.remove(i);
1785 }
1786 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001787 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001788 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001789 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1790 mPendingWhileIdleAlarms.remove(i);
1791 }
1792 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001793
1794 if (didRemove) {
1795 if (DEBUG_BATCH) {
1796 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
1797 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001798 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001799 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001800 mPendingIdleUntil = null;
1801 restorePending = true;
1802 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001803 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001804 mNextWakeFromIdle = null;
1805 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001806 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001807 if (restorePending) {
1808 restorePendingWhileIdleAlarmsLocked();
1809 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001810 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001811 }
1812 }
1813
1814 void removeLocked(String packageName) {
1815 boolean didRemove = false;
1816 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1817 Batch b = mAlarmBatches.get(i);
1818 didRemove |= b.remove(packageName);
1819 if (b.size() == 0) {
1820 mAlarmBatches.remove(i);
1821 }
1822 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001823 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001824 final Alarm a = mPendingWhileIdleAlarms.get(i);
1825 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001826 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1827 mPendingWhileIdleAlarms.remove(i);
1828 }
1829 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001830
1831 if (didRemove) {
1832 if (DEBUG_BATCH) {
1833 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1834 }
1835 rebatchAllAlarmsLocked(true);
1836 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001837 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001838 }
1839 }
1840
1841 void removeUserLocked(int userHandle) {
1842 boolean didRemove = false;
1843 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1844 Batch b = mAlarmBatches.get(i);
1845 didRemove |= b.remove(userHandle);
1846 if (b.size() == 0) {
1847 mAlarmBatches.remove(i);
1848 }
1849 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001850 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001851 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001852 == userHandle) {
1853 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1854 mPendingWhileIdleAlarms.remove(i);
1855 }
1856 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001857 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
1858 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
1859 mLastAllowWhileIdleDispatch.removeAt(i);
1860 }
1861 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001862
1863 if (didRemove) {
1864 if (DEBUG_BATCH) {
1865 Slog.v(TAG, "remove(user) changed bounds; rebatching");
1866 }
1867 rebatchAllAlarmsLocked(true);
1868 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001869 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001870 }
1871 }
1872
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001873 void interactiveStateChangedLocked(boolean interactive) {
1874 if (mInteractive != interactive) {
1875 mInteractive = interactive;
1876 final long nowELAPSED = SystemClock.elapsedRealtime();
1877 if (interactive) {
1878 if (mPendingNonWakeupAlarms.size() > 0) {
1879 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1880 mTotalDelayTime += thisDelayTime;
1881 if (mMaxDelayTime < thisDelayTime) {
1882 mMaxDelayTime = thisDelayTime;
1883 }
1884 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
1885 mPendingNonWakeupAlarms.clear();
1886 }
1887 if (mNonInteractiveStartTime > 0) {
1888 long dur = nowELAPSED - mNonInteractiveStartTime;
1889 if (dur > mNonInteractiveTime) {
1890 mNonInteractiveTime = dur;
1891 }
1892 }
1893 } else {
1894 mNonInteractiveStartTime = nowELAPSED;
1895 }
1896 }
1897 }
1898
Adam Lesinski182f73f2013-12-05 16:48:06 -08001899 boolean lookForPackageLocked(String packageName) {
1900 for (int i = 0; i < mAlarmBatches.size(); i++) {
1901 Batch b = mAlarmBatches.get(i);
1902 if (b.hasPackage(packageName)) {
1903 return true;
1904 }
1905 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001906 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001907 final Alarm a = mPendingWhileIdleAlarms.get(i);
1908 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001909 return true;
1910 }
1911 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001912 return false;
1913 }
1914
1915 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001916 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001917 // The kernel never triggers alarms with negative wakeup times
1918 // so we ensure they are positive.
1919 long alarmSeconds, alarmNanoseconds;
1920 if (when < 0) {
1921 alarmSeconds = 0;
1922 alarmNanoseconds = 0;
1923 } else {
1924 alarmSeconds = when / 1000;
1925 alarmNanoseconds = (when % 1000) * 1000 * 1000;
1926 }
1927
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001928 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001929 } else {
1930 Message msg = Message.obtain();
1931 msg.what = ALARM_EVENT;
1932
1933 mHandler.removeMessages(ALARM_EVENT);
1934 mHandler.sendMessageAtTime(msg, when);
1935 }
1936 }
1937
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001938 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001939 String prefix, String label, long nowRTC, long nowELAPSED, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940 for (int i=list.size()-1; i>=0; i--) {
1941 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001942 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1943 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001944 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001945 }
1946 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001947
1948 private static final String labelForType(int type) {
1949 switch (type) {
1950 case RTC: return "RTC";
1951 case RTC_WAKEUP : return "RTC_WAKEUP";
1952 case ELAPSED_REALTIME : return "ELAPSED";
1953 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
1954 default:
1955 break;
1956 }
1957 return "--unknown--";
1958 }
1959
1960 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001961 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001962 for (int i=list.size()-1; i>=0; i--) {
1963 Alarm a = list.get(i);
1964 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001965 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1966 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001967 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001968 }
1969 }
1970
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001971 private native long init();
1972 private native void close(long nativeData);
1973 private native void set(long nativeData, int type, long seconds, long nanoseconds);
1974 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08001975 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001976 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001977
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001978 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001979 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001980 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001981 // batches are temporally sorted, so we need only pull from the
1982 // start of the list until we either empty it or hit a batch
1983 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07001984 while (mAlarmBatches.size() > 0) {
1985 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001986 if (batch.start > nowELAPSED) {
1987 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001988 break;
1989 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990
Christopher Tatee0a22b32013-07-11 14:43:13 -07001991 // We will (re)schedule some alarms now; don't let that interfere
1992 // with delivery of this current batch
1993 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001994
Christopher Tatee0a22b32013-07-11 14:43:13 -07001995 final int N = batch.size();
1996 for (int i = 0; i < N; i++) {
1997 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001998
1999 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
2000 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
2001 // schedule such alarms.
2002 long lastTime = mLastAllowWhileIdleDispatch.get(alarm.uid, 0);
2003 long minTime = lastTime + mAllowWhileIdleMinTime;
2004 if (nowELAPSED < minTime) {
2005 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
2006 // alarm went off for this app. Reschedule the alarm to be in the
2007 // correct time period.
2008 alarm.whenElapsed = minTime;
2009 if (alarm.maxWhenElapsed < minTime) {
2010 alarm.maxWhenElapsed = minTime;
2011 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002012 if (RECORD_DEVICE_IDLE_ALARMS) {
2013 IdleDispatchEntry ent = new IdleDispatchEntry();
2014 ent.uid = alarm.uid;
2015 ent.pkg = alarm.operation.getCreatorPackage();
2016 ent.tag = alarm.operation.getTag("");
2017 ent.op = "RESCHEDULE";
2018 ent.elapsedRealtime = nowELAPSED;
2019 ent.argRealtime = lastTime;
2020 mAllowWhileIdleDispatches.add(ent);
2021 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002022 setImplLocked(alarm, true, false);
2023 continue;
2024 }
2025 }
2026
Christopher Tatee0a22b32013-07-11 14:43:13 -07002027 alarm.count = 1;
2028 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002029 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
2030 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002031 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002032 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002033 if (mPendingIdleUntil == alarm) {
2034 mPendingIdleUntil = null;
2035 rebatchAllAlarmsLocked(false);
2036 restorePendingWhileIdleAlarmsLocked();
2037 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002038 if (mNextWakeFromIdle == alarm) {
2039 mNextWakeFromIdle = null;
2040 rebatchAllAlarmsLocked(false);
2041 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002042
2043 // Recurring alarms may have passed several alarm intervals while the
2044 // phone was asleep or off, so pass a trigger count when sending them.
2045 if (alarm.repeatInterval > 0) {
2046 // this adjustment will be zero if we're late by
2047 // less than one full repeat interval
2048 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
2049
2050 // Also schedule its next recurrence
2051 final long delta = alarm.count * alarm.repeatInterval;
2052 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07002053 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07002054 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07002055 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
2056 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08002057 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058
Christopher Tate864d42e2014-12-02 11:48:53 -08002059 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002060 hasWakeup = true;
2061 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002062
2063 // We removed an alarm clock. Let the caller recompute the next alarm clock.
2064 if (alarm.alarmClock != null) {
2065 mNextAlarmClockMayChange = true;
2066 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07002067 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002068 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002069
Christopher Tate1590f1e2014-10-02 17:27:57 -07002070 // This is a new alarm delivery set; bump the sequence number to indicate that
2071 // all apps' alarm delivery classes should be recalculated.
2072 mCurrentSeq++;
2073 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002074 Collections.sort(triggerList, mAlarmDispatchComparator);
2075
2076 if (localLOGV) {
2077 for (int i=0; i<triggerList.size(); i++) {
2078 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
2079 }
2080 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002081
2082 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002083 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002085 /**
2086 * This Comparator sorts Alarms into increasing time order.
2087 */
2088 public static class IncreasingTimeOrder implements Comparator<Alarm> {
2089 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09002090 long when1 = a1.whenElapsed;
2091 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002092 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093 return 1;
2094 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002095 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002096 return -1;
2097 }
2098 return 0;
2099 }
2100 }
2101
2102 private static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002103 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002104 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002105 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002106 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002107 public final IAlarmListener listener;
2108 public final String listenerTag;
2109 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002110 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002111 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002112 public final AlarmManager.AlarmClockInfo alarmClock;
2113 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002114 public final int creatorUid;
2115 public final String packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002116 public int count;
2117 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07002118 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002119 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002120 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002121 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07002122 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002123
Christopher Tate3e04b472013-10-21 17:51:31 -07002124 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002125 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
2126 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
2127 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002128 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002129 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002130 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
2131 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002132 when = _when;
2133 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07002134 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002135 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002136 repeatInterval = _interval;
2137 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002138 listener = _rec;
2139 listenerTag = _listenerTag;
2140 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07002141 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002142 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002143 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002144 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002145 packageName = _pkgName;
2146
2147 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002148 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002149
Christopher Tate14a7bb02015-10-01 10:24:31 -07002150 public static String makeTag(PendingIntent pi, String tag, int type) {
2151 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
2152 ? "*walarm*:" : "*alarm*:";
2153 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
2154 }
2155
2156 public WakeupEvent makeWakeupEvent(long nowRTC) {
2157 return new WakeupEvent(nowRTC, creatorUid,
2158 (operation != null)
2159 ? operation.getIntent().getAction()
2160 : ("<listener>:" + listenerTag));
2161 }
2162
2163 // Returns true if either matches
2164 public boolean matches(PendingIntent pi, IAlarmListener rec) {
2165 return (operation != null)
2166 ? operation.equals(pi)
2167 : listener.asBinder().equals(rec.asBinder());
2168 }
2169
2170 public boolean matches(String packageName) {
2171 return (operation != null)
2172 ? packageName.equals(operation.getTargetPackage())
2173 : packageName.equals(this.packageName);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002174 }
2175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002177 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002178 StringBuilder sb = new StringBuilder(128);
2179 sb.append("Alarm{");
2180 sb.append(Integer.toHexString(System.identityHashCode(this)));
2181 sb.append(" type ");
2182 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002183 sb.append(" when ");
2184 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002185 sb.append(" ");
Christopher Tate14a7bb02015-10-01 10:24:31 -07002186 if (operation != null) {
2187 sb.append(operation.getTargetPackage());
2188 } else {
2189 sb.append(listener.asBinder().toString());
2190 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002191 sb.append('}');
2192 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002193 }
2194
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002195 public void dump(PrintWriter pw, String prefix, long nowRTC, long nowELAPSED,
2196 SimpleDateFormat sdf) {
2197 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002198 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002199 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002200 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
2201 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002202 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002203 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002204 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002205 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002206 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002207 }
2208 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002209 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002210 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002211 pw.print(" count="); pw.print(count);
2212 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002213 if (alarmClock != null) {
2214 pw.print(prefix); pw.println("Alarm clock:");
2215 pw.print(prefix); pw.print(" triggerTime=");
2216 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
2217 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
2218 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002219 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002220 if (listener != null) {
2221 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
2222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002223 }
2224 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002225
Christopher Tatee0a22b32013-07-11 14:43:13 -07002226 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
2227 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002228 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
2229 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002230 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07002231 break;
2232 }
2233
Christopher Tatee0a22b32013-07-11 14:43:13 -07002234 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002235 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
2236 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002237 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07002238 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002239 }
2240 }
2241
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002242 long currentNonWakeupFuzzLocked(long nowELAPSED) {
2243 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
2244 if (timeSinceOn < 5*60*1000) {
2245 // If the screen has been off for 5 minutes, only delay by at most two minutes.
2246 return 2*60*1000;
2247 } else if (timeSinceOn < 30*60*1000) {
2248 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
2249 return 15*60*1000;
2250 } else {
2251 // Otherwise, we will delay by at most an hour.
2252 return 60*60*1000;
2253 }
2254 }
2255
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002256 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002257 if (duration < 15*60*1000) {
2258 // If the duration until the time is less than 15 minutes, the maximum fuzz
2259 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002260 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002261 } else if (duration < 90*60*1000) {
2262 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
2263 return 15*60*1000;
2264 } else {
2265 // Otherwise, we will fuzz by at most half an hour.
2266 return 30*60*1000;
2267 }
2268 }
2269
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002270 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
2271 if (mInteractive) {
2272 return false;
2273 }
2274 if (mLastAlarmDeliveryTime <= 0) {
2275 return false;
2276 }
minho.choo649acab2014-12-12 16:13:55 +09002277 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002278 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
2279 // and the next delivery time is in the past, then just deliver them all. This
2280 // avoids bugs where we get stuck in a loop trying to poll for alarms.
2281 return false;
2282 }
2283 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
2284 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
2285 }
2286
2287 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
2288 mLastAlarmDeliveryTime = nowELAPSED;
2289 for (int i=0; i<triggerList.size(); i++) {
2290 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07002291 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002292 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07002293 if (localLOGV) {
2294 Slog.v(TAG, "sending alarm " + alarm);
2295 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07002296 if (RECORD_ALARMS_IN_HISTORY) {
2297 if (alarm.workSource != null && alarm.workSource.size() > 0) {
2298 for (int wi=0; wi<alarm.workSource.size(); wi++) {
2299 ActivityManagerNative.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002300 alarm.operation, alarm.workSource.get(wi), alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002301 }
2302 } else {
2303 ActivityManagerNative.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002304 alarm.operation, alarm.uid, alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002305 }
2306 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002307 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002308 } catch (RuntimeException e) {
2309 Slog.w(TAG, "Failure sending alarm.", e);
2310 }
2311 }
2312 }
2313
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002314 private class AlarmThread extends Thread
2315 {
2316 public AlarmThread()
2317 {
2318 super("AlarmManager");
2319 }
2320
2321 public void run()
2322 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002323 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002325 while (true)
2326 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002327 int result = waitForAlarm(mNativeData);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002328
2329 triggerList.clear();
2330
Dianne Hackbornc3527222015-05-13 14:03:20 -07002331 final long nowRTC = System.currentTimeMillis();
2332 final long nowELAPSED = SystemClock.elapsedRealtime();
2333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002334 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002335 // The kernel can give us spurious time change notifications due to
2336 // small adjustments it makes internally; we want to filter those out.
2337 final long lastTimeChangeClockTime;
2338 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07002339 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002340 lastTimeChangeClockTime = mLastTimeChangeClockTime;
2341 expectedClockTime = lastTimeChangeClockTime
2342 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07002343 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002344 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-500)
2345 || nowRTC > (expectedClockTime+500)) {
2346 // The change is by at least +/- 500 ms (or this is the first change),
2347 // let's do it!
2348 if (DEBUG_BATCH) {
2349 Slog.v(TAG, "Time changed notification from kernel; rebatching");
2350 }
2351 removeImpl(mTimeTickSender);
2352 rebatchAllAlarms();
2353 mClockReceiver.scheduleTimeTickEvent();
2354 synchronized (mLock) {
2355 mNumTimeChanged++;
2356 mLastTimeChangeClockTime = nowRTC;
2357 mLastTimeChangeRealtime = nowELAPSED;
2358 }
2359 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
2360 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
2361 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2362 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
2363
2364 // The world has changed on us, so we need to re-evaluate alarms
2365 // regardless of whether the kernel has told us one went off.
2366 result |= IS_WAKEUP_MASK;
2367 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002368 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002369
Dianne Hackbornc3527222015-05-13 14:03:20 -07002370 if (result != TIME_CHANGED_MASK) {
2371 // If this was anything besides just a time change, then figure what if
2372 // anything to do about alarms.
2373 synchronized (mLock) {
2374 if (localLOGV) Slog.v(
2375 TAG, "Checking for alarms... rtc=" + nowRTC
2376 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07002377
Dianne Hackbornc3527222015-05-13 14:03:20 -07002378 if (WAKEUP_STATS) {
2379 if ((result & IS_WAKEUP_MASK) != 0) {
2380 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
2381 int n = 0;
2382 for (WakeupEvent event : mRecentWakeups) {
2383 if (event.when > newEarliest) break;
2384 n++; // number of now-stale entries at the list head
2385 }
2386 for (int i = 0; i < n; i++) {
2387 mRecentWakeups.remove();
2388 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002389
Dianne Hackbornc3527222015-05-13 14:03:20 -07002390 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002391 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002392 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002393
2394 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2395 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
2396 // if there are no wakeup alarms and the screen is off, we can
2397 // delay what we have so far until the future.
2398 if (mPendingNonWakeupAlarms.size() == 0) {
2399 mStartCurrentDelayTime = nowELAPSED;
2400 mNextNonWakeupDeliveryTime = nowELAPSED
2401 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
2402 }
2403 mPendingNonWakeupAlarms.addAll(triggerList);
2404 mNumDelayedAlarms += triggerList.size();
2405 rescheduleKernelAlarmsLocked();
2406 updateNextAlarmClockLocked();
2407 } else {
2408 // now deliver the alarm intents; if there are pending non-wakeup
2409 // alarms, we need to merge them in to the list. note we don't
2410 // just deliver them first because we generally want non-wakeup
2411 // alarms delivered after wakeup alarms.
2412 rescheduleKernelAlarmsLocked();
2413 updateNextAlarmClockLocked();
2414 if (mPendingNonWakeupAlarms.size() > 0) {
2415 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
2416 triggerList.addAll(mPendingNonWakeupAlarms);
2417 Collections.sort(triggerList, mAlarmDispatchComparator);
2418 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2419 mTotalDelayTime += thisDelayTime;
2420 if (mMaxDelayTime < thisDelayTime) {
2421 mMaxDelayTime = thisDelayTime;
2422 }
2423 mPendingNonWakeupAlarms.clear();
2424 }
2425 deliverAlarmsLocked(triggerList, nowELAPSED);
2426 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002427 }
2428 }
2429 }
2430 }
2431 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002432
David Christieebe51fc2013-07-26 13:23:29 -07002433 /**
2434 * Attribute blame for a WakeLock.
2435 * @param pi PendingIntent to attribute blame to if ws is null.
2436 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002437 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07002438 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002439 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002440 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07002441 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002442 final boolean unimportant = pi == mTimeTickSender;
2443 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002444 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002445 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002446 } else {
2447 mWakeLock.setHistoryTag(null);
2448 }
2449 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07002450 if (ws != null) {
2451 mWakeLock.setWorkSource(ws);
2452 return;
2453 }
2454
Christopher Tate14a7bb02015-10-01 10:24:31 -07002455 final int uid = (knownUid >= 0)
2456 ? knownUid
2457 : ActivityManagerNative.getDefault().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07002458 if (uid >= 0) {
2459 mWakeLock.setWorkSource(new WorkSource(uid));
2460 return;
2461 }
2462 } catch (Exception e) {
2463 }
2464
2465 // Something went wrong; fall back to attributing the lock to the OS
2466 mWakeLock.setWorkSource(null);
2467 }
2468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002469 private class AlarmHandler extends Handler {
2470 public static final int ALARM_EVENT = 1;
2471 public static final int MINUTE_CHANGE_EVENT = 2;
2472 public static final int DATE_CHANGE_EVENT = 3;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002473 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 4;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002474 public static final int LISTENER_TIMEOUT = 5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002475
2476 public AlarmHandler() {
2477 }
2478
2479 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002480 switch (msg.what) {
2481 case ALARM_EVENT: {
2482 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2483 synchronized (mLock) {
2484 final long nowRTC = System.currentTimeMillis();
2485 final long nowELAPSED = SystemClock.elapsedRealtime();
2486 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2487 updateNextAlarmClockLocked();
2488 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002489
Christopher Tate14a7bb02015-10-01 10:24:31 -07002490 // now trigger the alarms without the lock held
2491 for (int i=0; i<triggerList.size(); i++) {
2492 Alarm alarm = triggerList.get(i);
2493 try {
2494 alarm.operation.send();
2495 } catch (PendingIntent.CanceledException e) {
2496 if (alarm.repeatInterval > 0) {
2497 // This IntentSender is no longer valid, but this
2498 // is a repeating alarm, so toss the hoser.
2499 removeImpl(alarm.operation);
2500 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002501 }
2502 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002503 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002504 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002505
2506 case SEND_NEXT_ALARM_CLOCK_CHANGED:
2507 sendNextAlarmClockChanged();
2508 break;
2509
2510 case LISTENER_TIMEOUT:
2511 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
2512 break;
2513
2514 default:
2515 // nope, just ignore it
2516 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002517 }
2518 }
2519 }
2520
2521 class ClockReceiver extends BroadcastReceiver {
2522 public ClockReceiver() {
2523 IntentFilter filter = new IntentFilter();
2524 filter.addAction(Intent.ACTION_TIME_TICK);
2525 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002526 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527 }
2528
2529 @Override
2530 public void onReceive(Context context, Intent intent) {
2531 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07002532 if (DEBUG_BATCH) {
2533 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
2534 }
2535 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
2537 // Since the kernel does not keep track of DST, we need to
2538 // reset the TZ information at the beginning of each day
2539 // based off of the current Zone gmt offset + userspace tracked
2540 // daylight savings information.
2541 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02002542 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002543 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07002544 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545 }
2546 }
2547
2548 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07002549 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09002550 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07002551
2552 // Schedule this event for the amount of time that it would take to get to
2553 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09002554 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07002555
David Christieebe51fc2013-07-26 13:23:29 -07002556 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002557 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002558 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
2559 null, Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002560 }
Christopher Tate385e4982013-07-23 18:22:29 -07002561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 public void scheduleDateChangedEvent() {
2563 Calendar calendar = Calendar.getInstance();
2564 calendar.setTimeInMillis(System.currentTimeMillis());
2565 calendar.set(Calendar.HOUR, 0);
2566 calendar.set(Calendar.MINUTE, 0);
2567 calendar.set(Calendar.SECOND, 0);
2568 calendar.set(Calendar.MILLISECOND, 0);
2569 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07002570
2571 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002572 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
2573 AlarmManager.FLAG_STANDALONE, workSource, null,
2574 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002575 }
2576 }
2577
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002578 class InteractiveStateReceiver extends BroadcastReceiver {
2579 public InteractiveStateReceiver() {
2580 IntentFilter filter = new IntentFilter();
2581 filter.addAction(Intent.ACTION_SCREEN_OFF);
2582 filter.addAction(Intent.ACTION_SCREEN_ON);
2583 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
2584 getContext().registerReceiver(this, filter);
2585 }
2586
2587 @Override
2588 public void onReceive(Context context, Intent intent) {
2589 synchronized (mLock) {
2590 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
2591 }
2592 }
2593 }
2594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002595 class UninstallReceiver extends BroadcastReceiver {
2596 public UninstallReceiver() {
2597 IntentFilter filter = new IntentFilter();
2598 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2599 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002600 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002601 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08002602 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002603 // Register for events related to sdcard installation.
2604 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08002605 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002606 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002607 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002608 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002609 }
2610
2611 @Override
2612 public void onReceive(Context context, Intent intent) {
2613 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002614 String action = intent.getAction();
2615 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002616 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
2617 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
2618 for (String packageName : pkgList) {
2619 if (lookForPackageLocked(packageName)) {
2620 setResultCode(Activity.RESULT_OK);
2621 return;
2622 }
2623 }
2624 return;
2625 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002626 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002627 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
2628 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
2629 if (userHandle >= 0) {
2630 removeUserLocked(userHandle);
2631 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002632 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
2633 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
2634 if (uid >= 0) {
2635 mLastAllowWhileIdleDispatch.delete(uid);
2636 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002637 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08002638 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
2639 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
2640 // This package is being updated; don't kill its alarms.
2641 return;
2642 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002643 Uri data = intent.getData();
2644 if (data != null) {
2645 String pkg = data.getSchemeSpecificPart();
2646 if (pkg != null) {
2647 pkgList = new String[]{pkg};
2648 }
2649 }
2650 }
2651 if (pkgList != null && (pkgList.length > 0)) {
2652 for (String pkg : pkgList) {
2653 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07002654 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002655 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
2656 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
2657 if (uidStats.remove(pkg) != null) {
2658 if (uidStats.size() <= 0) {
2659 mBroadcastStats.removeAt(i);
2660 }
2661 }
2662 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002663 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 }
2665 }
2666 }
2667 }
2668
2669 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002670 String pkg = pi.getCreatorPackage();
2671 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002672 return getStatsLocked(uid, pkg);
2673 }
2674
2675 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002676 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
2677 if (uidStats == null) {
2678 uidStats = new ArrayMap<String, BroadcastStats>();
2679 mBroadcastStats.put(uid, uidStats);
2680 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002681 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002683 bs = new BroadcastStats(uid, pkgName);
2684 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002685 }
2686 return bs;
2687 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002688
Christopher Tate14a7bb02015-10-01 10:24:31 -07002689 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
2690 private InFlight removeLocked(PendingIntent pi, Intent intent) {
2691 for (int i = 0; i < mInFlight.size(); i++) {
2692 if (mInFlight.get(i).mPendingIntent == pi) {
2693 return mInFlight.remove(i);
2694 }
2695 }
2696 mLog.w("No in-flight alarm for " + pi + " " + intent);
2697 return null;
2698 }
2699
2700 private InFlight removeLocked(IBinder listener) {
2701 for (int i = 0; i < mInFlight.size(); i++) {
2702 if (mInFlight.get(i).mListener == listener) {
2703 return mInFlight.remove(i);
2704 }
2705 }
2706 mLog.w("No in-flight alarm for listener " + listener);
2707 return null;
2708 }
2709
2710 private void updateStatsLocked(InFlight inflight) {
2711 final long nowELAPSED = SystemClock.elapsedRealtime();
2712 BroadcastStats bs = inflight.mBroadcastStats;
2713 bs.nesting--;
2714 if (bs.nesting <= 0) {
2715 bs.nesting = 0;
2716 bs.aggregateTime += nowELAPSED - bs.startTime;
2717 }
2718 FilterStats fs = inflight.mFilterStats;
2719 fs.nesting--;
2720 if (fs.nesting <= 0) {
2721 fs.nesting = 0;
2722 fs.aggregateTime += nowELAPSED - fs.startTime;
2723 }
2724 if (RECORD_ALARMS_IN_HISTORY) {
2725 if (inflight.mWorkSource != null && inflight.mWorkSource.size() > 0) {
2726 for (int wi=0; wi<inflight.mWorkSource.size(); wi++) {
2727 ActivityManagerNative.noteAlarmFinish(
2728 inflight.mPendingIntent, inflight.mWorkSource.get(wi), inflight.mTag);
2729 }
2730 } else {
2731 ActivityManagerNative.noteAlarmFinish(
2732 inflight.mPendingIntent, inflight.mUid, inflight.mTag);
2733 }
2734 }
2735 }
2736
2737 private void updateTrackingLocked(InFlight inflight) {
2738 if (inflight != null) {
2739 updateStatsLocked(inflight);
2740 }
2741 mBroadcastRefCount--;
2742 if (mBroadcastRefCount == 0) {
2743 mWakeLock.release();
2744 if (mInFlight.size() > 0) {
2745 mLog.w("Finished all dispatches with " + mInFlight.size()
2746 + " remaining inflights");
2747 for (int i=0; i<mInFlight.size(); i++) {
2748 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
2749 }
2750 mInFlight.clear();
2751 }
2752 } else {
2753 // the next of our alarms is now in flight. reattribute the wakelock.
2754 if (mInFlight.size() > 0) {
2755 InFlight inFlight = mInFlight.get(0);
2756 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
2757 inFlight.mAlarmType, inFlight.mTag, -1, false);
2758 } else {
2759 // should never happen
2760 mLog.w("Alarm wakelock still held but sent queue empty");
2761 mWakeLock.setWorkSource(null);
2762 }
2763 }
2764 }
2765
2766 /**
2767 * Callback that arrives when a direct-call alarm reports that delivery has finished
2768 */
2769 @Override
2770 public void alarmComplete(IBinder who) {
2771 if (who == null) {
2772 Slog.w(TAG, "Invalid alarmComplete: uid=" + Binder.getCallingUid()
2773 + " pid=" + Binder.getCallingPid());
2774 return;
2775 }
2776
2777 final long ident = Binder.clearCallingIdentity();
2778 try {
2779 synchronized (mLock) {
2780 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
2781 InFlight inflight = removeLocked(who);
2782 if (inflight != null) {
2783 if (DEBUG_LISTENER_CALLBACK) {
2784 Slog.i(TAG, "alarmComplete() from " + who);
2785 }
2786 updateTrackingLocked(inflight);
2787 } else {
2788 // Delivery timed out, and the timeout handling already took care of
2789 // updating our tracking here, so we needn't do anything further.
2790 if (DEBUG_LISTENER_CALLBACK) {
2791 Slog.i(TAG, "Late alarmComplete() from " + who);
2792 }
2793 }
2794 }
2795 } finally {
2796 Binder.restoreCallingIdentity(ident);
2797 }
2798 }
2799
2800 /**
2801 * Callback that arrives when a PendingIntent alarm has finished delivery
2802 */
2803 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002804 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
2805 String resultData, Bundle resultExtras) {
2806 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002807 updateTrackingLocked(removeLocked(pi, intent));
2808 }
2809 }
2810
2811 /**
2812 * Timeout of a direct-call alarm delivery
2813 */
2814 public void alarmTimedOut(IBinder who) {
2815 synchronized (mLock) {
2816 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08002817 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002818 // TODO: implement ANR policy for the target
2819 if (DEBUG_LISTENER_CALLBACK) {
2820 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002821 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002822 updateTrackingLocked(inflight);
Dianne Hackborn81038902012-11-26 17:04:09 -08002823 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002824 if (DEBUG_LISTENER_CALLBACK) {
2825 Slog.i(TAG, "Spurious timeout of listener " + who);
2826 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002827 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002828 }
2829 }
2830
2831 /**
2832 * Deliver an alarm and set up the post-delivery handling appropriately
2833 */
2834 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
2835 if (alarm.operation != null) {
2836 // PendingIntent alarm
2837 try {
2838 alarm.operation.send(getContext(), 0,
2839 mBackgroundIntent.putExtra(
2840 Intent.EXTRA_ALARM_COUNT, alarm.count),
2841 mDeliveryTracker, mHandler, null,
2842 allowWhileIdle ? mIdleOptions : null);
2843 } catch (PendingIntent.CanceledException e) {
2844 if (alarm.repeatInterval > 0) {
2845 // This IntentSender is no longer valid, but this
2846 // is a repeating alarm, so toss it
2847 removeImpl(alarm.operation);
2848 }
2849 }
2850 } else {
2851 // Direct listener callback alarm
2852 try {
2853 if (DEBUG_LISTENER_CALLBACK) {
2854 Slog.v(TAG, "Alarm to uid=" + alarm.uid
2855 + " listener=" + alarm.listener.asBinder());
2856 }
2857 alarm.listener.doAlarm(this);
2858 mHandler.sendMessageDelayed(
2859 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
2860 alarm.listener.asBinder()),
2861 mConstants.LISTENER_TIMEOUT);
2862 } catch (Exception e) {
2863 if (DEBUG_LISTENER_CALLBACK) {
2864 Slog.i(TAG, "Alarm undeliverable to listener "
2865 + alarm.listener.asBinder(), e);
2866 }
2867 }
2868 }
2869
2870 // The alarm is now in flight; now arrange wakelock and stats tracking
2871 if (mBroadcastRefCount == 0) {
2872 setWakelockWorkSource(alarm.operation, alarm.workSource,
2873 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
2874 true);
2875 mWakeLock.acquire();
2876 }
2877 final InFlight inflight = new InFlight(AlarmManagerService.this,
2878 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
2879 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
2880 mInFlight.add(inflight);
2881 mBroadcastRefCount++;
2882
2883 if (allowWhileIdle) {
2884 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
2885 mLastAllowWhileIdleDispatch.put(alarm.uid, nowELAPSED);
2886 if (RECORD_DEVICE_IDLE_ALARMS) {
2887 IdleDispatchEntry ent = new IdleDispatchEntry();
2888 ent.uid = alarm.uid;
2889 ent.pkg = alarm.packageName;
2890 ent.tag = alarm.statsTag;
2891 ent.op = "DELIVER";
2892 ent.elapsedRealtime = nowELAPSED;
2893 mAllowWhileIdleDispatches.add(ent);
2894 }
2895 }
2896
2897 final BroadcastStats bs = inflight.mBroadcastStats;
2898 bs.count++;
2899 if (bs.nesting == 0) {
2900 bs.nesting = 1;
2901 bs.startTime = nowELAPSED;
2902 } else {
2903 bs.nesting++;
2904 }
2905 final FilterStats fs = inflight.mFilterStats;
2906 fs.count++;
2907 if (fs.nesting == 0) {
2908 fs.nesting = 1;
2909 fs.startTime = nowELAPSED;
2910 } else {
2911 fs.nesting++;
2912 }
2913 if (alarm.type == ELAPSED_REALTIME_WAKEUP
2914 || alarm.type == RTC_WAKEUP) {
2915 bs.numWakeup++;
2916 fs.numWakeup++;
2917 if (alarm.workSource != null && alarm.workSource.size() > 0) {
2918 for (int wi=0; wi<alarm.workSource.size(); wi++) {
2919 ActivityManagerNative.noteWakeupAlarm(
2920 alarm.operation, alarm.workSource.get(wi),
2921 alarm.workSource.getName(wi), alarm.statsTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08002922 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002923 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002924 ActivityManagerNative.noteWakeupAlarm(
2925 alarm.operation, -1, alarm.packageName, alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002926 }
2927 }
2928 }
2929 }
2930}