blob: 21dae4f2139a18416b33064d9201abf68d090d4a [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;
Christopher Tate57ceaaa2013-07-19 16:30:43 -070021import android.app.AlarmManager;
Christopher Tate14a7bb02015-10-01 10:24:31 -070022import android.app.AppOpsManager;
Dianne Hackborna750a632015-06-16 17:18:23 -070023import android.app.BroadcastOptions;
Christopher Tate14a7bb02015-10-01 10:24:31 -070024import android.app.IAlarmCompleteListener;
25import android.app.IAlarmListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.app.IAlarmManager;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070027import android.app.IUidObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import 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;
Christopher Tate247571462017-04-10 11:45:05 -070039import android.os.Environment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.os.Handler;
Adam Lesinski182f73f2013-12-05 16:48:06 -080041import android.os.IBinder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.os.Message;
43import android.os.PowerManager;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070044import android.os.Process;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070045import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.os.SystemClock;
47import android.os.SystemProperties;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070048import android.os.UserHandle;
Christopher Tatec4a07d12012-04-06 14:19:13 -070049import android.os.WorkSource;
Adrian Roosc42a1e12014-07-07 23:35:53 +020050import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.text.TextUtils;
Adrian Roosc42a1e12014-07-07 23:35:53 +020052import android.text.format.DateFormat;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080053import android.util.ArrayMap;
Dianne Hackborna750a632015-06-16 17:18:23 -070054import android.util.KeyValueListParser;
Adrian Roosc42a1e12014-07-07 23:35:53 +020055import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080056import android.util.Slog;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080057import android.util.SparseArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +020058import android.util.SparseBooleanArray;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -070059import android.util.SparseLongArray;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070060import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061
Christopher Tate4cb338d2013-07-26 13:11:31 -070062import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import java.io.FileDescriptor;
64import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070065import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -080067import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import java.util.Calendar;
69import java.util.Collections;
70import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -050071import java.util.Date;
Christopher Tate1590f1e2014-10-02 17:27:57 -070072import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -070073import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +020074import java.util.Locale;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070075import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import java.util.TimeZone;
John Spurlock604a5ee2015-06-01 12:27:22 -040077import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078
Christopher Tatee0a22b32013-07-11 14:43:13 -070079import static android.app.AlarmManager.RTC_WAKEUP;
80import static android.app.AlarmManager.RTC;
81import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
82import static android.app.AlarmManager.ELAPSED_REALTIME;
83
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060084import com.android.internal.util.DumpUtils;
Dianne Hackborn81038902012-11-26 17:04:09 -080085import com.android.internal.util.LocalLog;
86
Adam Lesinski182f73f2013-12-05 16:48:06 -080087class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -070088 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
89 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -080090 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -070091 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -080092 static final int TIME_CHANGED_MASK = 1 << 16;
93 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -080094
Christopher Tatee0a22b32013-07-11 14:43:13 -070095 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -080096 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -080097
Adam Lesinski182f73f2013-12-05 16:48:06 -080098 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -080099 static final boolean localLOGV = false;
100 static final boolean DEBUG_BATCH = localLOGV || false;
101 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200102 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700103 static final boolean DEBUG_LISTENER_CALLBACK = localLOGV || false;
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800104 static final boolean DEBUG_WAKELOCK = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700105 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700106 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800107 static final int ALARM_EVENT = 1;
108 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200109
Christopher Tate14a7bb02015-10-01 10:24:31 -0700110 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800112 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113
Adam Lesinski182f73f2013-12-05 16:48:06 -0800114 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700115
Christopher Tate24cd46f2016-02-02 14:28:01 -0800116 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT =
117 new Intent(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED)
118 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Adrian Roosc42a1e12014-07-07 23:35:53 +0200119
Adam Lesinski182f73f2013-12-05 16:48:06 -0800120 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800121
Christopher Tate14a7bb02015-10-01 10:24:31 -0700122 AppOpsManager mAppOps;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800123 DeviceIdleController.LocalService mLocalDeviceIdleController;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700124
Adam Lesinski182f73f2013-12-05 16:48:06 -0800125 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800126
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800127 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800128 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700129 private long mNextNonWakeup;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -0700130 private long mLastWakeupSet;
131 private long mLastWakeup;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800132 int mBroadcastRefCount = 0;
133 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700134 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700135 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
136 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800137 final AlarmHandler mHandler = new AlarmHandler();
138 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700139 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700141 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800142 PendingIntent mTimeTickSender;
143 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700144 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700145 boolean mInteractive = true;
146 long mNonInteractiveStartTime;
147 long mNonInteractiveTime;
148 long mLastAlarmDeliveryTime;
149 long mStartCurrentDelayTime;
150 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700151 long mLastTimeChangeClockTime;
152 long mLastTimeChangeRealtime;
Dianne Hackborna750a632015-06-16 17:18:23 -0700153 long mAllowWhileIdleMinTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700154 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800155
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700156 /**
Dianne Hackborn262ae5c2016-02-10 16:28:29 -0800157 * The current set of user whitelisted apps for device idle mode, meaning these are allowed
158 * to freely schedule alarms.
159 */
160 int[] mDeviceIdleUserWhitelist = new int[0];
161
162 /**
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700163 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
164 * used to determine the earliest we can dispatch the next such alarm.
165 */
166 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
167
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700168 final static class IdleDispatchEntry {
169 int uid;
170 String pkg;
171 String tag;
172 String op;
173 long elapsedRealtime;
174 long argRealtime;
175 }
176 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
177
Dianne Hackborna750a632015-06-16 17:18:23 -0700178 /**
179 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
180 */
181 Bundle mIdleOptions;
182
Jose Lima235510e2014-08-13 12:50:01 -0700183 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
184 new SparseArray<>();
185 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
186 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200187 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
188 new SparseBooleanArray();
189 private boolean mNextAlarmClockMayChange;
190
191 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700192 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
193 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200194
Dianne Hackborna750a632015-06-16 17:18:23 -0700195 /**
196 * All times are in milliseconds. These constants are kept synchronized with the system
197 * global Settings. Any access to this class or its fields should be done while
198 * holding the AlarmManagerService.mLock lock.
199 */
200 private final class Constants extends ContentObserver {
201 // Key names stored in the settings value.
202 private static final String KEY_MIN_FUTURITY = "min_futurity";
203 private static final String KEY_MIN_INTERVAL = "min_interval";
204 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
205 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
206 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
207 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700208 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Dianne Hackborna750a632015-06-16 17:18:23 -0700209
210 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
211 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tateaa244da2015-08-27 15:57:57 -0700212 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700213 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700214 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
215
Christopher Tate14a7bb02015-10-01 10:24:31 -0700216 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
217
Dianne Hackborna750a632015-06-16 17:18:23 -0700218 // Minimum futurity of a new alarm
219 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
220
221 // Minimum alarm recurrence interval
222 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
223
224 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
225 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
226
227 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
228 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
229
230 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
231 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
232 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
233
Christopher Tate14a7bb02015-10-01 10:24:31 -0700234 // Direct alarm listener callback timeout
235 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
236
Dianne Hackborna750a632015-06-16 17:18:23 -0700237 private ContentResolver mResolver;
238 private final KeyValueListParser mParser = new KeyValueListParser(',');
239 private long mLastAllowWhileIdleWhitelistDuration = -1;
240
241 public Constants(Handler handler) {
242 super(handler);
243 updateAllowWhileIdleMinTimeLocked();
244 updateAllowWhileIdleWhitelistDurationLocked();
245 }
246
247 public void start(ContentResolver resolver) {
248 mResolver = resolver;
249 mResolver.registerContentObserver(Settings.Global.getUriFor(
250 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
251 updateConstants();
252 }
253
254 public void updateAllowWhileIdleMinTimeLocked() {
255 mAllowWhileIdleMinTime = mPendingIdleUntil != null
256 ? ALLOW_WHILE_IDLE_LONG_TIME : ALLOW_WHILE_IDLE_SHORT_TIME;
257 }
258
259 public void updateAllowWhileIdleWhitelistDurationLocked() {
260 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
261 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
262 BroadcastOptions opts = BroadcastOptions.makeBasic();
263 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
264 mIdleOptions = opts.toBundle();
265 }
266 }
267
268 @Override
269 public void onChange(boolean selfChange, Uri uri) {
270 updateConstants();
271 }
272
273 private void updateConstants() {
274 synchronized (mLock) {
275 try {
276 mParser.setString(Settings.Global.getString(mResolver,
277 Settings.Global.ALARM_MANAGER_CONSTANTS));
278 } catch (IllegalArgumentException e) {
279 // Failed to parse the settings string, log this and move on
280 // with defaults.
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800281 Slog.e(TAG, "Bad alarm manager settings", e);
Dianne Hackborna750a632015-06-16 17:18:23 -0700282 }
283
284 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
285 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
286 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
287 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
288 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
289 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
290 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
291 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
292 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700293 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
294 DEFAULT_LISTENER_TIMEOUT);
Dianne Hackborna750a632015-06-16 17:18:23 -0700295
296 updateAllowWhileIdleMinTimeLocked();
297 updateAllowWhileIdleWhitelistDurationLocked();
298 }
299 }
300
301 void dump(PrintWriter pw) {
302 pw.println(" Settings:");
303
304 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
305 TimeUtils.formatDuration(MIN_FUTURITY, pw);
306 pw.println();
307
308 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
309 TimeUtils.formatDuration(MIN_INTERVAL, pw);
310 pw.println();
311
Christopher Tate14a7bb02015-10-01 10:24:31 -0700312 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
313 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
314 pw.println();
315
Dianne Hackborna750a632015-06-16 17:18:23 -0700316 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
317 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
318 pw.println();
319
320 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
321 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
322 pw.println();
323
324 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
325 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
326 pw.println();
327 }
328 }
329
330 final Constants mConstants;
331
Christopher Tate1590f1e2014-10-02 17:27:57 -0700332 // Alarm delivery ordering bookkeeping
333 static final int PRIO_TICK = 0;
334 static final int PRIO_WAKEUP = 1;
335 static final int PRIO_NORMAL = 2;
336
Dianne Hackborna750a632015-06-16 17:18:23 -0700337 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700338 int seq;
339 int priority;
340
341 PriorityClass() {
342 seq = mCurrentSeq - 1;
343 priority = PRIO_NORMAL;
344 }
345 }
346
Dianne Hackborna750a632015-06-16 17:18:23 -0700347 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700348 int mCurrentSeq = 0;
349
Dianne Hackborna750a632015-06-16 17:18:23 -0700350 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700351 public long when;
352 public int uid;
353 public String action;
354
355 public WakeupEvent(long theTime, int theUid, String theAction) {
356 when = theTime;
357 uid = theUid;
358 action = theAction;
359 }
360 }
361
Adam Lesinski182f73f2013-12-05 16:48:06 -0800362 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
363 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700364
Adrian Roosc42a1e12014-07-07 23:35:53 +0200365 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700366 long start; // These endpoints are always in ELAPSED
367 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700368 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700369
370 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
371
372 Batch() {
373 start = 0;
374 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700375 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700376 }
377
378 Batch(Alarm seed) {
379 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700380 end = seed.maxWhenElapsed;
381 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700382 alarms.add(seed);
383 }
384
385 int size() {
386 return alarms.size();
387 }
388
389 Alarm get(int index) {
390 return alarms.get(index);
391 }
392
393 boolean canHold(long whenElapsed, long maxWhen) {
394 return (end >= whenElapsed) && (start <= maxWhen);
395 }
396
397 boolean add(Alarm alarm) {
398 boolean newStart = false;
399 // narrows the batch if necessary; presumes that canHold(alarm) is true
400 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
401 if (index < 0) {
402 index = 0 - index - 1;
403 }
404 alarms.add(index, alarm);
405 if (DEBUG_BATCH) {
406 Slog.v(TAG, "Adding " + alarm + " to " + this);
407 }
408 if (alarm.whenElapsed > start) {
409 start = alarm.whenElapsed;
410 newStart = true;
411 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700412 if (alarm.maxWhenElapsed < end) {
413 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700414 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700415 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700416
417 if (DEBUG_BATCH) {
418 Slog.v(TAG, " => now " + this);
419 }
420 return newStart;
421 }
422
Christopher Tate14a7bb02015-10-01 10:24:31 -0700423 boolean remove(final PendingIntent operation, final IAlarmListener listener) {
424 if (operation == null && listener == null) {
425 if (localLOGV) {
426 Slog.w(TAG, "requested remove() of null operation",
427 new RuntimeException("here"));
428 }
429 return false;
430 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700431 boolean didRemove = false;
432 long newStart = 0; // recalculate endpoints as we go
433 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700434 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700435 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700436 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700437 if (alarm.matches(operation, listener)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700438 alarms.remove(i);
439 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200440 if (alarm.alarmClock != null) {
441 mNextAlarmClockMayChange = true;
442 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700443 } else {
444 if (alarm.whenElapsed > newStart) {
445 newStart = alarm.whenElapsed;
446 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700447 if (alarm.maxWhenElapsed < newEnd) {
448 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700449 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700450 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700451 i++;
452 }
453 }
454 if (didRemove) {
455 // commit the new batch bounds
456 start = newStart;
457 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700458 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700459 }
460 return didRemove;
461 }
462
463 boolean remove(final String packageName) {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700464 if (packageName == null) {
465 if (localLOGV) {
466 Slog.w(TAG, "requested remove() of null packageName",
467 new RuntimeException("here"));
468 }
469 return false;
470 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700471 boolean didRemove = false;
472 long newStart = 0; // recalculate endpoints as we go
473 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700474 int newFlags = 0;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700475 for (int i = alarms.size()-1; i >= 0; i--) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700476 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700477 if (alarm.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700478 alarms.remove(i);
479 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200480 if (alarm.alarmClock != null) {
481 mNextAlarmClockMayChange = true;
482 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700483 } else {
484 if (alarm.whenElapsed > newStart) {
485 newStart = alarm.whenElapsed;
486 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700487 if (alarm.maxWhenElapsed < newEnd) {
488 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700489 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700490 newFlags |= alarm.flags;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700491 }
492 }
493 if (didRemove) {
494 // commit the new batch bounds
495 start = newStart;
496 end = newEnd;
497 flags = newFlags;
498 }
499 return didRemove;
500 }
501
502 boolean removeForStopped(final int uid) {
503 boolean didRemove = false;
504 long newStart = 0; // recalculate endpoints as we go
505 long newEnd = Long.MAX_VALUE;
506 int newFlags = 0;
507 for (int i = alarms.size()-1; i >= 0; i--) {
508 Alarm alarm = alarms.get(i);
509 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800510 if (alarm.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
511 uid, alarm.packageName)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700512 alarms.remove(i);
513 didRemove = true;
514 if (alarm.alarmClock != null) {
515 mNextAlarmClockMayChange = true;
516 }
517 } else {
518 if (alarm.whenElapsed > newStart) {
519 newStart = alarm.whenElapsed;
520 }
521 if (alarm.maxWhenElapsed < newEnd) {
522 newEnd = alarm.maxWhenElapsed;
523 }
524 newFlags |= alarm.flags;
525 }
526 } catch (RemoteException e) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700527 }
528 }
529 if (didRemove) {
530 // commit the new batch bounds
531 start = newStart;
532 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700533 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700534 }
535 return didRemove;
536 }
537
538 boolean remove(final int userHandle) {
539 boolean didRemove = false;
540 long newStart = 0; // recalculate endpoints as we go
541 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700542 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700543 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700544 if (UserHandle.getUserId(alarm.creatorUid) == userHandle) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700545 alarms.remove(i);
546 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200547 if (alarm.alarmClock != null) {
548 mNextAlarmClockMayChange = true;
549 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700550 } else {
551 if (alarm.whenElapsed > newStart) {
552 newStart = alarm.whenElapsed;
553 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700554 if (alarm.maxWhenElapsed < newEnd) {
555 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700556 }
557 i++;
558 }
559 }
560 if (didRemove) {
561 // commit the new batch bounds
562 start = newStart;
563 end = newEnd;
564 }
565 return didRemove;
566 }
567
568 boolean hasPackage(final String packageName) {
569 final int N = alarms.size();
570 for (int i = 0; i < N; i++) {
571 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700572 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700573 return true;
574 }
575 }
576 return false;
577 }
578
579 boolean hasWakeups() {
580 final int N = alarms.size();
581 for (int i = 0; i < N; i++) {
582 Alarm a = alarms.get(i);
583 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
584 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
585 return true;
586 }
587 }
588 return false;
589 }
590
591 @Override
592 public String toString() {
593 StringBuilder b = new StringBuilder(40);
594 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
595 b.append(" num="); b.append(size());
596 b.append(" start="); b.append(start);
597 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700598 if (flags != 0) {
599 b.append(" flgs=0x");
600 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700601 }
602 b.append('}');
603 return b.toString();
604 }
605 }
606
607 static class BatchTimeOrder implements Comparator<Batch> {
608 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800609 long when1 = b1.start;
610 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800611 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700612 return 1;
613 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800614 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700615 return -1;
616 }
617 return 0;
618 }
619 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800620
621 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
622 @Override
623 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700624 // priority class trumps everything. TICK < WAKEUP < NORMAL
625 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
626 return -1;
627 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
628 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800629 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700630
631 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800632 if (lhs.whenElapsed < rhs.whenElapsed) {
633 return -1;
634 } else if (lhs.whenElapsed > rhs.whenElapsed) {
635 return 1;
636 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700637
638 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800639 return 0;
640 }
641 };
642
Christopher Tate1590f1e2014-10-02 17:27:57 -0700643 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
644 final int N = alarms.size();
645 for (int i = 0; i < N; i++) {
646 Alarm a = alarms.get(i);
647
648 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700649 if (a.operation != null
650 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700651 alarmPrio = PRIO_TICK;
652 } else if (a.wakeup) {
653 alarmPrio = PRIO_WAKEUP;
654 } else {
655 alarmPrio = PRIO_NORMAL;
656 }
657
658 PriorityClass packagePrio = a.priorityClass;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700659 String alarmPackage = (a.operation != null)
660 ? a.operation.getCreatorPackage()
661 : a.packageName;
662 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700663 if (packagePrio == null) {
664 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700665 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700666 }
667 a.priorityClass = packagePrio;
668
669 if (packagePrio.seq != mCurrentSeq) {
670 // first alarm we've seen in the current delivery generation from this package
671 packagePrio.priority = alarmPrio;
672 packagePrio.seq = mCurrentSeq;
673 } else {
674 // Multiple alarms from this package being delivered in this generation;
675 // bump the package's delivery class if it's warranted.
676 // TICK < WAKEUP < NORMAL
677 if (alarmPrio < packagePrio.priority) {
678 packagePrio.priority = alarmPrio;
679 }
680 }
681 }
682 }
683
Christopher Tatee0a22b32013-07-11 14:43:13 -0700684 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800685 static final long MIN_FUZZABLE_INTERVAL = 10000;
686 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700687 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
688
689 // set to null if in idle mode; while in this mode, any alarms we don't want
690 // to run during this time are placed in mPendingWhileIdleAlarms
691 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700692 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700693 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700694
Jeff Brownb880d882014-02-10 19:47:07 -0800695 public AlarmManagerService(Context context) {
696 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700697 mConstants = new Constants(mHandler);
Jeff Brownb880d882014-02-10 19:47:07 -0800698 }
699
Christopher Tatee0a22b32013-07-11 14:43:13 -0700700 static long convertToElapsed(long when, int type) {
701 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
702 if (isRtc) {
703 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
704 }
705 return when;
706 }
707
708 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
709 // calculate the end of our nominal delivery window for the alarm.
710 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
711 // Current heuristic: batchable window is 75% of either the recurrence interval
712 // [for a periodic alarm] or of the time from now to the desired delivery time,
713 // with a minimum delay/interval of 10 seconds, under which we will simply not
714 // defer the alarm.
715 long futurity = (interval == 0)
716 ? (triggerAtTime - now)
717 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700718 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700719 futurity = 0;
720 }
721 return triggerAtTime + (long)(.75 * futurity);
722 }
723
724 // returns true if the batch was added at the head
725 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
726 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
727 if (index < 0) {
728 index = 0 - index - 1;
729 }
730 list.add(index, newBatch);
731 return (index == 0);
732 }
733
Christopher Tate385e4982013-07-23 18:22:29 -0700734 // Return the index of the matching batch, or -1 if none found.
735 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700736 final int N = mAlarmBatches.size();
737 for (int i = 0; i < N; i++) {
738 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700739 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700740 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700741 }
742 }
Christopher Tate385e4982013-07-23 18:22:29 -0700743 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700744 }
745
746 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
747 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700748 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700749 rebatchAllAlarmsLocked(true);
750 }
751 }
752
753 void rebatchAllAlarmsLocked(boolean doValidate) {
754 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
755 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700756 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700757 final long nowElapsed = SystemClock.elapsedRealtime();
758 final int oldBatches = oldSet.size();
759 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
760 Batch batch = oldSet.get(batchNum);
761 final int N = batch.size();
762 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700763 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700764 }
765 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700766 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
767 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
768 + " to " + mPendingIdleUntil);
769 if (mPendingIdleUntil == null) {
770 // Somehow we lost this... we need to restore all of the pending alarms.
771 restorePendingWhileIdleAlarmsLocked();
772 }
773 }
774 rescheduleKernelAlarmsLocked();
775 updateNextAlarmClockLocked();
776 }
777
778 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
779 a.when = a.origWhen;
780 long whenElapsed = convertToElapsed(a.when, a.type);
781 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700782 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700783 // Exact
784 maxElapsed = whenElapsed;
785 } else {
786 // Not exact. Preserve any explicit window, otherwise recalculate
787 // the window based on the alarm's new futurity. Note that this
788 // reflects a policy of preferring timely to deferred delivery.
789 maxElapsed = (a.windowLength > 0)
790 ? (whenElapsed + a.windowLength)
791 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
792 }
793 a.whenElapsed = whenElapsed;
794 a.maxWhenElapsed = maxElapsed;
795 setImplLocked(a, true, doValidate);
796 }
797
798 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700799 if (RECORD_DEVICE_IDLE_ALARMS) {
800 IdleDispatchEntry ent = new IdleDispatchEntry();
801 ent.uid = 0;
802 ent.pkg = "FINISH IDLE";
803 ent.elapsedRealtime = SystemClock.elapsedRealtime();
804 mAllowWhileIdleDispatches.add(ent);
805 }
806
Dianne Hackborn35d54032015-04-23 10:30:43 -0700807 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700808 if (mPendingWhileIdleAlarms.size() > 0) {
809 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
810 mPendingWhileIdleAlarms = new ArrayList<>();
811 final long nowElapsed = SystemClock.elapsedRealtime();
812 for (int i=alarms.size() - 1; i >= 0; i--) {
813 Alarm a = alarms.get(i);
814 reAddAlarmLocked(a, nowElapsed, false);
815 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700816 }
Dianne Hackborn35d54032015-04-23 10:30:43 -0700817
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700818 // Make sure we are using the correct ALLOW_WHILE_IDLE min time.
Dianne Hackborna750a632015-06-16 17:18:23 -0700819 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700820
Dianne Hackborn35d54032015-04-23 10:30:43 -0700821 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700822 rescheduleKernelAlarmsLocked();
823 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -0700824
825 // And send a TIME_TICK right now, since it is important to get the UI updated.
826 try {
827 mTimeTickSender.send();
828 } catch (PendingIntent.CanceledException e) {
829 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700830 }
831
Christopher Tate14a7bb02015-10-01 10:24:31 -0700832 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -0800833 final PendingIntent mPendingIntent;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700834 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -0700835 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700836 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700837 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800838 final BroadcastStats mBroadcastStats;
839 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800840 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800841
Christopher Tate14a7bb02015-10-01 10:24:31 -0700842 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
843 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
844 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800845 mPendingIntent = pendingIntent;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700846 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -0700847 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700848 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700849 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700850 mBroadcastStats = (pendingIntent != null)
851 ? service.getStatsLocked(pendingIntent)
852 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700853 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -0800854 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700855 fs = new FilterStats(mBroadcastStats, mTag);
856 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -0800857 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700858 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -0800859 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800860 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800861 }
Makoto Onuki33955e12017-03-01 18:11:00 -0800862
863 @Override
864 public String toString() {
865 return "InFlight{"
866 + "pendingIntent=" + mPendingIntent
867 + ", workSource=" + mWorkSource
868 + ", uid=" + mUid
869 + ", tag=" + mTag
870 + ", broadcastStats=" + mBroadcastStats
871 + ", filterStats=" + mFilterStats
872 + ", alarmType=" + mAlarmType
873 + "}";
874 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800876
Adam Lesinski182f73f2013-12-05 16:48:06 -0800877 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -0800878 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700879 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800880
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700881 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800883 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884 int numWakeup;
885 long startTime;
886 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -0800887
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700888 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800889 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700890 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800891 }
Makoto Onuki33955e12017-03-01 18:11:00 -0800892
893 @Override
894 public String toString() {
895 return "FilterStats{"
896 + "tag=" + mTag
897 + ", lastTime=" + lastTime
898 + ", aggregateTime=" + aggregateTime
899 + ", count=" + count
900 + ", numWakeup=" + numWakeup
901 + ", startTime=" + startTime
902 + ", nesting=" + nesting
903 + "}";
904 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800905 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700906
Adam Lesinski182f73f2013-12-05 16:48:06 -0800907 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800908 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800909 final String mPackageName;
910
911 long aggregateTime;
912 int count;
913 int numWakeup;
914 long startTime;
915 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700916 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -0800917
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800918 BroadcastStats(int uid, String packageName) {
919 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800920 mPackageName = packageName;
921 }
Makoto Onuki33955e12017-03-01 18:11:00 -0800922
923 @Override
924 public String toString() {
925 return "BroadcastStats{"
926 + "uid=" + mUid
927 + ", packageName=" + mPackageName
928 + ", aggregateTime=" + aggregateTime
929 + ", count=" + count
930 + ", numWakeup=" + numWakeup
931 + ", startTime=" + startTime
932 + ", nesting=" + nesting
933 + "}";
934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700936
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800937 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
938 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700939
940 int mNumDelayedAlarms = 0;
941 long mTotalDelayTime = 0;
942 long mMaxDelayTime = 0;
943
Adam Lesinski182f73f2013-12-05 16:48:06 -0800944 @Override
945 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800946 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800947 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800948
949 // We have to set current TimeZone info to kernel
950 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -0800951 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800952
Christopher Tate247571462017-04-10 11:45:05 -0700953 // Also sure that we're booting with a halfway sensible current time
954 if (mNativeData != 0) {
955 final long systemBuildTime = Environment.getRootDirectory().lastModified();
956 if (System.currentTimeMillis() < systemBuildTime) {
957 Slog.i(TAG, "Current time only " + System.currentTimeMillis()
958 + ", advancing to build time " + systemBuildTime);
959 setKernelTime(mNativeData, systemBuildTime);
960 }
961 }
962
Adam Lesinski182f73f2013-12-05 16:48:06 -0800963 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800964 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800965
Adam Lesinski182f73f2013-12-05 16:48:06 -0800966 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700968 Intent.FLAG_RECEIVER_REGISTERED_ONLY
Chad Brubaker291df4f2017-03-14 10:23:02 -0700969 | Intent.FLAG_RECEIVER_FOREGROUND
970 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700971 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800972 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -0700973 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
974 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800975 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700976 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977
978 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -0800979 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 mClockReceiver.scheduleTimeTickEvent();
981 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700982 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 mUninstallReceiver = new UninstallReceiver();
984
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800985 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800986 AlarmThread waitThread = new AlarmThread();
987 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800989 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800991
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700992 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800993 ActivityManager.getService().registerUidObserver(new UidObserver(),
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800994 ActivityManager.UID_OBSERVER_IDLE, ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700995 } catch (RemoteException e) {
996 // ignored; both services live in system_server
997 }
998
Adam Lesinski182f73f2013-12-05 16:48:06 -0800999 publishBinderService(Context.ALARM_SERVICE, mService);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001000 publishLocalService(LocalService.class, new LocalService());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001002
1003 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001004 public void onBootPhase(int phase) {
1005 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1006 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -07001007 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001008 mLocalDeviceIdleController
1009 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackborna750a632015-06-16 17:18:23 -07001010 }
1011 }
1012
1013 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014 protected void finalize() throws Throwable {
1015 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001016 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 } finally {
1018 super.finalize();
1019 }
1020 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001021
Adam Lesinski182f73f2013-12-05 16:48:06 -08001022 void setTimeZoneImpl(String tz) {
1023 if (TextUtils.isEmpty(tz)) {
1024 return;
David Christieebe51fc2013-07-26 13:23:29 -07001025 }
1026
Adam Lesinski182f73f2013-12-05 16:48:06 -08001027 TimeZone zone = TimeZone.getTimeZone(tz);
1028 // Prevent reentrant calls from stepping on each other when writing
1029 // the time zone property
1030 boolean timeZoneWasChanged = false;
1031 synchronized (this) {
1032 String current = SystemProperties.get(TIMEZONE_PROPERTY);
1033 if (current == null || !current.equals(zone.getID())) {
1034 if (localLOGV) {
1035 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
1036 }
1037 timeZoneWasChanged = true;
1038 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
1039 }
1040
1041 // Update the kernel timezone information
1042 // Kernel tracks time offsets as 'minutes west of GMT'
1043 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001044 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001045 }
1046
1047 TimeZone.setDefault(null);
1048
1049 if (timeZoneWasChanged) {
1050 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001051 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1052 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001053 intent.putExtra("time-zone", zone.getID());
1054 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001057
Adam Lesinski182f73f2013-12-05 16:48:06 -08001058 void removeImpl(PendingIntent operation) {
1059 if (operation == null) {
1060 return;
1061 }
1062 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001063 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001064 }
1065 }
1066
1067 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001068 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1069 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1070 int callingUid, String callingPackage) {
1071 // must be *either* PendingIntent or AlarmReceiver, but not both
1072 if ((operation == null && directReceiver == null)
1073 || (operation != null && directReceiver != null)) {
1074 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1075 // NB: previous releases failed silently here, so we are continuing to do the same
1076 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 return;
1078 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001079
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001080 // Sanity check the window length. This will catch people mistakenly
1081 // trying to pass an end-of-window timestamp rather than a duration.
1082 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1083 Slog.w(TAG, "Window length " + windowLength
1084 + "ms suspiciously long; limiting to 1 hour");
1085 windowLength = AlarmManager.INTERVAL_HOUR;
1086 }
1087
Christopher Tate498c6cb2014-11-17 16:09:27 -08001088 // Sanity check the recurrence interval. This will catch people who supply
1089 // seconds when the API expects milliseconds.
Dianne Hackborna750a632015-06-16 17:18:23 -07001090 final long minInterval = mConstants.MIN_INTERVAL;
1091 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001092 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001093 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001094 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001095 interval = minInterval;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001096 }
1097
Christopher Tatee0a22b32013-07-11 14:43:13 -07001098 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1099 throw new IllegalArgumentException("Invalid alarm type " + type);
1100 }
1101
Christopher Tate5f221e82013-07-30 17:13:15 -07001102 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001103 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001104 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001105 + " pid=" + what);
1106 triggerAtTime = 0;
1107 }
1108
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001109 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001110 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1111 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001112 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001113 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1114
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001115 final long maxElapsed;
1116 if (windowLength == AlarmManager.WINDOW_EXACT) {
1117 maxElapsed = triggerElapsed;
1118 } else if (windowLength < 0) {
1119 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001120 // Fix this window in place, so that as time approaches we don't collapse it.
1121 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001122 } else {
1123 maxElapsed = triggerElapsed + windowLength;
1124 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001127 if (DEBUG_BATCH) {
1128 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001129 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001130 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001131 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001132 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001133 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001134 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1135 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001136 }
1137 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138
Christopher Tate3e04b472013-10-21 17:51:31 -07001139 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001140 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1141 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1142 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001143 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001144 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1145 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001146 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001147 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001148 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1149 + " -- package not allowed to start");
1150 return;
1151 }
1152 } catch (RemoteException e) {
1153 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001154 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001155 setImplLocked(a, false, doValidate);
1156 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001157
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001158 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1159 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001160 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001161 // The caller has given the time they want this to happen at, however we need
1162 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001163 // bring us out of idle at an earlier time.
1164 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001165 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001166 }
1167 // Add fuzz to make the alarm go off some time before the actual desired time.
1168 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001169 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001170 if (fuzz > 0) {
1171 if (mRandom == null) {
1172 mRandom = new Random();
1173 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001174 final int delta = mRandom.nextInt(fuzz);
1175 a.whenElapsed -= delta;
1176 if (false) {
1177 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1178 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1179 Slog.d(TAG, "Applied fuzz: " + fuzz);
1180 Slog.d(TAG, "Final delta: " + delta);
1181 Slog.d(TAG, "Final when: " + a.whenElapsed);
1182 }
1183 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001184 }
1185
1186 } else if (mPendingIdleUntil != null) {
1187 // We currently have an idle until alarm scheduled; if the new alarm has
1188 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001189 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1190 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1191 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001192 == 0) {
1193 mPendingWhileIdleAlarms.add(a);
1194 return;
1195 }
1196 }
1197
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001198 if (RECORD_DEVICE_IDLE_ALARMS) {
1199 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1200 IdleDispatchEntry ent = new IdleDispatchEntry();
1201 ent.uid = a.uid;
1202 ent.pkg = a.operation.getCreatorPackage();
1203 ent.tag = a.operation.getTag("");
1204 ent.op = "SET";
1205 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1206 ent.argRealtime = a.whenElapsed;
1207 mAllowWhileIdleDispatches.add(ent);
1208 }
1209 }
1210
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001211 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
1212 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -07001213 if (whichBatch < 0) {
1214 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001215 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216 } else {
Christopher Tate385e4982013-07-23 18:22:29 -07001217 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001218 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001219 // The start time of this batch advanced, so batch ordering may
1220 // have just been broken. Move it to where it now belongs.
1221 mAlarmBatches.remove(whichBatch);
1222 addBatchLocked(mAlarmBatches, batch);
1223 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001224 }
1225
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001226 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001227 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001228 }
1229
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001230 boolean needRebatch = false;
1231
1232 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001233 if (RECORD_DEVICE_IDLE_ALARMS) {
1234 if (mPendingIdleUntil == null) {
1235 IdleDispatchEntry ent = new IdleDispatchEntry();
1236 ent.uid = 0;
1237 ent.pkg = "START IDLE";
1238 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1239 mAllowWhileIdleDispatches.add(ent);
1240 }
1241 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001242 mPendingIdleUntil = a;
Dianne Hackborna750a632015-06-16 17:18:23 -07001243 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001244 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001245 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1246 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1247 mNextWakeFromIdle = a;
1248 // If this wake from idle is earlier than whatever was previously scheduled,
1249 // and we are currently idling, then we need to rebatch alarms in case the idle
1250 // until time needs to be updated.
1251 if (mPendingIdleUntil != null) {
1252 needRebatch = true;
1253 }
1254 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001255 }
1256
1257 if (!rebatching) {
1258 if (DEBUG_VALIDATE) {
1259 if (doValidate && !validateConsistencyLocked()) {
1260 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1261 + " when(hex)=" + Long.toHexString(a.when)
1262 + " whenElapsed=" + a.whenElapsed
1263 + " maxWhenElapsed=" + a.maxWhenElapsed
1264 + " interval=" + a.repeatInterval + " op=" + a.operation
1265 + " flags=0x" + Integer.toHexString(a.flags));
1266 rebatchAllAlarmsLocked(false);
1267 needRebatch = false;
1268 }
1269 }
1270
1271 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001272 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001273 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001274
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001275 rescheduleKernelAlarmsLocked();
1276 updateNextAlarmClockLocked();
1277 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001278 }
1279
Adam Lesinski182f73f2013-12-05 16:48:06 -08001280 private final IBinder mService = new IAlarmManager.Stub() {
1281 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001282 public void set(String callingPackage,
1283 int type, long triggerAtTime, long windowLength, long interval, int flags,
1284 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1285 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001286 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001287
1288 // make sure the caller is not lying about which package should be blamed for
1289 // wakelock time spent in alarm delivery
1290 mAppOps.checkPackage(callingUid, callingPackage);
1291
1292 // Repeating alarms must use PendingIntent, not direct listener
1293 if (interval != 0) {
1294 if (directReceiver != null) {
1295 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1296 }
1297 }
1298
Adam Lesinski182f73f2013-12-05 16:48:06 -08001299 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001300 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001301 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001302 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001303 }
1304
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001305 // No incoming callers can request either WAKE_FROM_IDLE or
1306 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1307 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1308 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1309
1310 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1311 // manager when to come out of idle mode, which is only for DeviceIdleController.
1312 if (callingUid != Process.SYSTEM_UID) {
1313 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1314 }
1315
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001316 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001317 if (windowLength == AlarmManager.WINDOW_EXACT) {
1318 flags |= AlarmManager.FLAG_STANDALONE;
1319 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001320
1321 // If this alarm is for an alarm clock, then it must be standalone and we will
1322 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001323 if (alarmClock != null) {
1324 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001325
1326 // If the caller is a core system component or on the user's whitelist, and not calling
1327 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1328 // This means we will allow these alarms to go off as normal even while idle, with no
1329 // timing restrictions.
1330 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
1331 || Arrays.binarySearch(mDeviceIdleUserWhitelist,
1332 UserHandle.getAppId(callingUid)) >= 0)) {
1333 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1334 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001335 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001336
Christopher Tate14a7bb02015-10-01 10:24:31 -07001337 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1338 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001339 }
Christopher Tate89779822012-08-31 14:40:03 -07001340
Adam Lesinski182f73f2013-12-05 16:48:06 -08001341 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001342 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001343 getContext().enforceCallingOrSelfPermission(
1344 "android.permission.SET_TIME",
1345 "setTime");
1346
Greg Hackmann0cab8962014-02-21 16:35:52 -08001347 if (mNativeData == 0) {
1348 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1349 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001350 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001351
1352 synchronized (mLock) {
1353 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001356
1357 @Override
1358 public void setTimeZone(String tz) {
1359 getContext().enforceCallingOrSelfPermission(
1360 "android.permission.SET_TIME_ZONE",
1361 "setTimeZone");
1362
1363 final long oldId = Binder.clearCallingIdentity();
1364 try {
1365 setTimeZoneImpl(tz);
1366 } finally {
1367 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368 }
1369 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001370
Adam Lesinski182f73f2013-12-05 16:48:06 -08001371 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001372 public void remove(PendingIntent operation, IAlarmListener listener) {
1373 if (operation == null && listener == null) {
1374 Slog.w(TAG, "remove() with no intent or listener");
1375 return;
1376 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001377
Christopher Tate14a7bb02015-10-01 10:24:31 -07001378 synchronized (mLock) {
1379 removeLocked(operation, listener);
1380 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001382
Adam Lesinski182f73f2013-12-05 16:48:06 -08001383 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001384 public long getNextWakeFromIdleTime() {
1385 return getNextWakeFromIdleTimeImpl();
1386 }
1387
1388 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001389 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001390 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1391 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1392 "getNextAlarmClock", null);
1393
1394 return getNextAlarmClockImpl(userId);
1395 }
1396
1397 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001398 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06001399 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001400 dumpImpl(pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001401 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001402 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001403
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001404 public final class LocalService {
1405 public void setDeviceIdleUserWhitelist(int[] appids) {
1406 setDeviceIdleUserWhitelistImpl(appids);
1407 }
1408 }
1409
Adam Lesinski182f73f2013-12-05 16:48:06 -08001410 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 synchronized (mLock) {
1412 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001413 mConstants.dump(pw);
1414 pw.println();
1415
Christopher Tatee0a22b32013-07-11 14:43:13 -07001416 final long nowRTC = System.currentTimeMillis();
1417 final long nowELAPSED = SystemClock.elapsedRealtime();
1418 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1419
Dianne Hackborna750a632015-06-16 17:18:23 -07001420 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001421 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001422 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001423 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001424 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001425 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001426 pw.print(" mLastTimeChangeRealtime=");
Dianne Hackbornc3527222015-05-13 14:03:20 -07001427 TimeUtils.formatDuration(mLastTimeChangeRealtime, pw);
1428 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001429 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001430 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001431 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1432 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001433 pw.print(" Max wakeup delay: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001434 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1435 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001436 pw.print(" Time since last dispatch: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001437 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1438 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001439 pw.print(" Next non-wakeup delivery time: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001440 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1441 pw.println();
1442 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001443
1444 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1445 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001446 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001447 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001448 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001449 pw.print(" Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001450 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001451 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
1452 pw.print(" set at "); TimeUtils.formatDuration(mLastWakeupSet, nowELAPSED, pw);
1453 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001454 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001455 pw.println(" mDeviceIdleUserWhitelist=" + Arrays.toString(mDeviceIdleUserWhitelist));
Christopher Tatee0a22b32013-07-11 14:43:13 -07001456
John Spurlock604a5ee2015-06-01 12:27:22 -04001457 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001458 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001459 final TreeSet<Integer> users = new TreeSet<>();
1460 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1461 users.add(mNextAlarmClockForUser.keyAt(i));
1462 }
1463 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1464 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1465 }
1466 for (int user : users) {
1467 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1468 final long time = next != null ? next.getTriggerTime() : 0;
1469 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001470 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001471 pw.print(" pendingSend:"); pw.print(pendingSend);
1472 pw.print(" time:"); pw.print(time);
1473 if (time > 0) {
1474 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1475 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1476 }
1477 pw.println();
1478 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001479 if (mAlarmBatches.size() > 0) {
1480 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001481 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001482 pw.println(mAlarmBatches.size());
1483 for (Batch b : mAlarmBatches) {
1484 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001485 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001486 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001488 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001489 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001490 pw.println(" Idle mode state:");
1491 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001492 if (mPendingIdleUntil != null) {
1493 pw.println(mPendingIdleUntil);
Dianne Hackbornf3831292015-10-15 14:51:06 -07001494 mPendingIdleUntil.dump(pw, " ", nowRTC, nowELAPSED, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001495 } else {
1496 pw.println("null");
1497 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001498 pw.println(" Pending alarms:");
1499 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001500 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001501 if (mNextWakeFromIdle != null) {
1502 pw.println();
1503 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
1504 mNextWakeFromIdle.dump(pw, " ", nowRTC, nowELAPSED, sdf);
1505 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001506
1507 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001508 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001509 if (mPendingNonWakeupAlarms.size() > 0) {
1510 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001511 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001512 } else {
1513 pw.println("(none)");
1514 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001515 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001516 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1517 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001518 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001519 pw.print(", max non-interactive time: ");
1520 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1521 pw.println();
1522
1523 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001524 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001525 pw.println();
1526
Christopher Tate7f2a0352015-12-08 10:24:33 -08001527 if (mInFlight.size() > 0) {
1528 pw.println("Outstanding deliveries:");
1529 for (int i = 0; i < mInFlight.size(); i++) {
1530 pw.print(" #"); pw.print(i); pw.print(": ");
1531 pw.println(mInFlight.get(i));
1532 }
1533 pw.println();
1534 }
1535
Dianne Hackborna750a632015-06-16 17:18:23 -07001536 pw.print(" mAllowWhileIdleMinTime=");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001537 TimeUtils.formatDuration(mAllowWhileIdleMinTime, pw);
1538 pw.println();
1539 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001540 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001541 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
1542 pw.print(" UID ");
1543 UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
1544 pw.print(": ");
1545 TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i),
1546 nowELAPSED, pw);
1547 pw.println();
1548 }
1549 }
1550 pw.println();
1551
Dianne Hackborn81038902012-11-26 17:04:09 -08001552 if (mLog.dump(pw, " Recent problems", " ")) {
1553 pw.println();
1554 }
1555
1556 final FilterStats[] topFilters = new FilterStats[10];
1557 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1558 @Override
1559 public int compare(FilterStats lhs, FilterStats rhs) {
1560 if (lhs.aggregateTime < rhs.aggregateTime) {
1561 return 1;
1562 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1563 return -1;
1564 }
1565 return 0;
1566 }
1567 };
1568 int len = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001569 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1570 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1571 for (int ip=0; ip<uidStats.size(); ip++) {
1572 BroadcastStats bs = uidStats.valueAt(ip);
1573 for (int is=0; is<bs.filterStats.size(); is++) {
1574 FilterStats fs = bs.filterStats.valueAt(is);
1575 int pos = len > 0
1576 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1577 if (pos < 0) {
1578 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001579 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001580 if (pos < topFilters.length) {
1581 int copylen = topFilters.length - pos - 1;
1582 if (copylen > 0) {
1583 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1584 }
1585 topFilters[pos] = fs;
1586 if (len < topFilters.length) {
1587 len++;
1588 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001589 }
1590 }
1591 }
1592 }
1593 if (len > 0) {
1594 pw.println(" Top Alarms:");
1595 for (int i=0; i<len; i++) {
1596 FilterStats fs = topFilters[i];
1597 pw.print(" ");
1598 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1599 TimeUtils.formatDuration(fs.aggregateTime, pw);
1600 pw.print(" running, "); pw.print(fs.numWakeup);
1601 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001602 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1603 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001604 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001605 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001606 pw.println();
1607 }
1608 }
1609
1610 pw.println(" ");
1611 pw.println(" Alarm Stats:");
1612 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001613 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1614 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1615 for (int ip=0; ip<uidStats.size(); ip++) {
1616 BroadcastStats bs = uidStats.valueAt(ip);
1617 pw.print(" ");
1618 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1619 UserHandle.formatUid(pw, bs.mUid);
1620 pw.print(":");
1621 pw.print(bs.mPackageName);
1622 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1623 pw.print(" running, "); pw.print(bs.numWakeup);
1624 pw.println(" wakeups:");
1625 tmpFilters.clear();
1626 for (int is=0; is<bs.filterStats.size(); is++) {
1627 tmpFilters.add(bs.filterStats.valueAt(is));
1628 }
1629 Collections.sort(tmpFilters, comparator);
1630 for (int i=0; i<tmpFilters.size(); i++) {
1631 FilterStats fs = tmpFilters.get(i);
1632 pw.print(" ");
1633 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1634 TimeUtils.formatDuration(fs.aggregateTime, pw);
1635 pw.print(" "); pw.print(fs.numWakeup);
1636 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001637 pw.print(" alarms, last ");
1638 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1639 pw.println(":");
1640 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001641 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001642 pw.println();
1643 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 }
1645 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001646
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001647 if (RECORD_DEVICE_IDLE_ALARMS) {
1648 pw.println();
1649 pw.println(" Allow while idle dispatches:");
1650 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
1651 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
1652 pw.print(" ");
1653 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
1654 pw.print(": ");
1655 UserHandle.formatUid(pw, ent.uid);
1656 pw.print(":");
1657 pw.println(ent.pkg);
1658 if (ent.op != null) {
1659 pw.print(" ");
1660 pw.print(ent.op);
1661 pw.print(" / ");
1662 pw.print(ent.tag);
1663 if (ent.argRealtime != 0) {
1664 pw.print(" (");
1665 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
1666 pw.print(")");
1667 }
1668 pw.println();
1669 }
1670 }
1671 }
1672
Christopher Tate18a75f12013-07-01 18:18:59 -07001673 if (WAKEUP_STATS) {
1674 pw.println();
1675 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001676 long last = -1;
1677 for (WakeupEvent event : mRecentWakeups) {
1678 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1679 pw.print('|');
1680 if (last < 0) {
1681 pw.print('0');
1682 } else {
1683 pw.print(event.when - last);
1684 }
1685 last = event.when;
1686 pw.print('|'); pw.print(event.uid);
1687 pw.print('|'); pw.print(event.action);
1688 pw.println();
1689 }
1690 pw.println();
1691 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 }
1693 }
1694
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001695 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001696 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
1697 PrintWriter pw = new PrintWriter(bs);
1698 final long nowRTC = System.currentTimeMillis();
1699 final long nowELAPSED = SystemClock.elapsedRealtime();
1700 final int NZ = mAlarmBatches.size();
1701 for (int iz = 0; iz < NZ; iz++) {
1702 Batch bz = mAlarmBatches.get(iz);
1703 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001704 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001705 pw.flush();
1706 Slog.v(TAG, bs.toString());
1707 bs.reset();
1708 }
1709 }
1710
1711 private boolean validateConsistencyLocked() {
1712 if (DEBUG_VALIDATE) {
1713 long lastTime = Long.MIN_VALUE;
1714 final int N = mAlarmBatches.size();
1715 for (int i = 0; i < N; i++) {
1716 Batch b = mAlarmBatches.get(i);
1717 if (b.start >= lastTime) {
1718 // duplicate start times are okay because of standalone batches
1719 lastTime = b.start;
1720 } else {
1721 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001722 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1723 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001724 return false;
1725 }
1726 }
1727 }
1728 return true;
1729 }
1730
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001731 private Batch findFirstWakeupBatchLocked() {
1732 final int N = mAlarmBatches.size();
1733 for (int i = 0; i < N; i++) {
1734 Batch b = mAlarmBatches.get(i);
1735 if (b.hasWakeups()) {
1736 return b;
1737 }
1738 }
1739 return null;
1740 }
1741
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001742 long getNextWakeFromIdleTimeImpl() {
1743 synchronized (mLock) {
1744 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
1745 }
1746 }
1747
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001748 void setDeviceIdleUserWhitelistImpl(int[] appids) {
1749 synchronized (mLock) {
1750 mDeviceIdleUserWhitelist = appids;
1751 }
1752 }
1753
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001754 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001755 synchronized (mLock) {
1756 return mNextAlarmClockForUser.get(userId);
1757 }
1758 }
1759
1760 /**
1761 * Recomputes the next alarm clock for all users.
1762 */
1763 private void updateNextAlarmClockLocked() {
1764 if (!mNextAlarmClockMayChange) {
1765 return;
1766 }
1767 mNextAlarmClockMayChange = false;
1768
Jose Lima235510e2014-08-13 12:50:01 -07001769 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001770 nextForUser.clear();
1771
1772 final int N = mAlarmBatches.size();
1773 for (int i = 0; i < N; i++) {
1774 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
1775 final int M = alarms.size();
1776
1777 for (int j = 0; j < M; j++) {
1778 Alarm a = alarms.get(j);
1779 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001780 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07001781 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001782
1783 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07001784 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001785 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02001786 " for user " + userId);
1787 }
1788
1789 // Alarms and batches are sorted by time, no need to compare times here.
1790 if (nextForUser.get(userId) == null) {
1791 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07001792 } else if (a.alarmClock.equals(current)
1793 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
1794 // same/earlier time and it's the one we cited before, so stick with it
1795 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001796 }
1797 }
1798 }
1799 }
1800
1801 // Update mNextAlarmForUser with new values.
1802 final int NN = nextForUser.size();
1803 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07001804 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001805 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001806 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001807 if (!newAlarm.equals(currentAlarm)) {
1808 updateNextAlarmInfoForUserLocked(userId, newAlarm);
1809 }
1810 }
1811
1812 // Remove users without any alarm clocks scheduled.
1813 final int NNN = mNextAlarmClockForUser.size();
1814 for (int i = NNN - 1; i >= 0; i--) {
1815 int userId = mNextAlarmClockForUser.keyAt(i);
1816 if (nextForUser.get(userId) == null) {
1817 updateNextAlarmInfoForUserLocked(userId, null);
1818 }
1819 }
1820 }
1821
Jose Lima235510e2014-08-13 12:50:01 -07001822 private void updateNextAlarmInfoForUserLocked(int userId,
1823 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001824 if (alarmClock != null) {
1825 if (DEBUG_ALARM_CLOCK) {
1826 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001827 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02001828 }
1829 mNextAlarmClockForUser.put(userId, alarmClock);
1830 } else {
1831 if (DEBUG_ALARM_CLOCK) {
1832 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
1833 }
1834 mNextAlarmClockForUser.remove(userId);
1835 }
1836
1837 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
1838 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1839 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1840 }
1841
1842 /**
1843 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
1844 * for which alarm clocks have changed since the last call to this.
1845 *
1846 * Do not call with a lock held. Only call from mHandler's thread.
1847 *
1848 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
1849 */
1850 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07001851 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001852 pendingUsers.clear();
1853
1854 synchronized (mLock) {
1855 final int N = mPendingSendNextAlarmClockChangedForUser.size();
1856 for (int i = 0; i < N; i++) {
1857 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
1858 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
1859 }
1860 mPendingSendNextAlarmClockChangedForUser.clear();
1861 }
1862
1863 final int N = pendingUsers.size();
1864 for (int i = 0; i < N; i++) {
1865 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001866 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001867 Settings.System.putStringForUser(getContext().getContentResolver(),
1868 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01001869 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02001870 userId);
1871
1872 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
1873 new UserHandle(userId));
1874 }
1875 }
1876
1877 /**
1878 * Formats an alarm like platform/packages/apps/DeskClock used to.
1879 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01001880 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
1881 int userId) {
1882 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02001883 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
1884 return (info == null) ? "" :
1885 DateFormat.format(pattern, info.getTriggerTime()).toString();
1886 }
1887
Adam Lesinski182f73f2013-12-05 16:48:06 -08001888 void rescheduleKernelAlarmsLocked() {
1889 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
1890 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001891 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001892 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001893 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001894 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07001895 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001896 mNextWakeup = firstWakeup.start;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001897 mLastWakeupSet = SystemClock.elapsedRealtime();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001898 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001899 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001900 if (firstBatch != firstWakeup) {
1901 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001902 }
1903 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001904 if (mPendingNonWakeupAlarms.size() > 0) {
1905 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
1906 nextNonWakeup = mNextNonWakeupDeliveryTime;
1907 }
1908 }
Prashant Malani753e9e02015-06-10 17:43:49 -07001909 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001910 mNextNonWakeup = nextNonWakeup;
1911 setLocked(ELAPSED_REALTIME, nextNonWakeup);
1912 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001913 }
1914
Christopher Tate14a7bb02015-10-01 10:24:31 -07001915 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001916 boolean didRemove = false;
1917 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1918 Batch b = mAlarmBatches.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -07001919 didRemove |= b.remove(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001920 if (b.size() == 0) {
1921 mAlarmBatches.remove(i);
1922 }
1923 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001924 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001925 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001926 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1927 mPendingWhileIdleAlarms.remove(i);
1928 }
1929 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001930
1931 if (didRemove) {
1932 if (DEBUG_BATCH) {
1933 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
1934 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001935 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001936 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001937 mPendingIdleUntil = null;
1938 restorePending = true;
1939 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001940 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001941 mNextWakeFromIdle = null;
1942 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001943 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001944 if (restorePending) {
1945 restorePendingWhileIdleAlarmsLocked();
1946 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001947 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001948 }
1949 }
1950
1951 void removeLocked(String packageName) {
1952 boolean didRemove = false;
1953 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1954 Batch b = mAlarmBatches.get(i);
1955 didRemove |= b.remove(packageName);
1956 if (b.size() == 0) {
1957 mAlarmBatches.remove(i);
1958 }
1959 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001960 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001961 final Alarm a = mPendingWhileIdleAlarms.get(i);
1962 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001963 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1964 mPendingWhileIdleAlarms.remove(i);
1965 }
1966 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001967
1968 if (didRemove) {
1969 if (DEBUG_BATCH) {
1970 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1971 }
1972 rebatchAllAlarmsLocked(true);
1973 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001974 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001975 }
1976 }
1977
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001978 void removeForStoppedLocked(int uid) {
1979 boolean didRemove = false;
1980 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1981 Batch b = mAlarmBatches.get(i);
1982 didRemove |= b.removeForStopped(uid);
1983 if (b.size() == 0) {
1984 mAlarmBatches.remove(i);
1985 }
1986 }
1987 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1988 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08001989 if (a.uid == uid) {
1990 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1991 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001992 }
1993 }
1994
1995 if (didRemove) {
1996 if (DEBUG_BATCH) {
1997 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1998 }
1999 rebatchAllAlarmsLocked(true);
2000 rescheduleKernelAlarmsLocked();
2001 updateNextAlarmClockLocked();
2002 }
2003 }
2004
Adam Lesinski182f73f2013-12-05 16:48:06 -08002005 void removeUserLocked(int userHandle) {
2006 boolean didRemove = false;
2007 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2008 Batch b = mAlarmBatches.get(i);
2009 didRemove |= b.remove(userHandle);
2010 if (b.size() == 0) {
2011 mAlarmBatches.remove(i);
2012 }
2013 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002014 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002015 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002016 == userHandle) {
2017 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2018 mPendingWhileIdleAlarms.remove(i);
2019 }
2020 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002021 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
2022 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
2023 mLastAllowWhileIdleDispatch.removeAt(i);
2024 }
2025 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002026
2027 if (didRemove) {
2028 if (DEBUG_BATCH) {
2029 Slog.v(TAG, "remove(user) changed bounds; rebatching");
2030 }
2031 rebatchAllAlarmsLocked(true);
2032 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002033 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002034 }
2035 }
2036
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002037 void interactiveStateChangedLocked(boolean interactive) {
2038 if (mInteractive != interactive) {
2039 mInteractive = interactive;
2040 final long nowELAPSED = SystemClock.elapsedRealtime();
2041 if (interactive) {
2042 if (mPendingNonWakeupAlarms.size() > 0) {
2043 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2044 mTotalDelayTime += thisDelayTime;
2045 if (mMaxDelayTime < thisDelayTime) {
2046 mMaxDelayTime = thisDelayTime;
2047 }
2048 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2049 mPendingNonWakeupAlarms.clear();
2050 }
2051 if (mNonInteractiveStartTime > 0) {
2052 long dur = nowELAPSED - mNonInteractiveStartTime;
2053 if (dur > mNonInteractiveTime) {
2054 mNonInteractiveTime = dur;
2055 }
2056 }
2057 } else {
2058 mNonInteractiveStartTime = nowELAPSED;
2059 }
2060 }
2061 }
2062
Adam Lesinski182f73f2013-12-05 16:48:06 -08002063 boolean lookForPackageLocked(String packageName) {
2064 for (int i = 0; i < mAlarmBatches.size(); i++) {
2065 Batch b = mAlarmBatches.get(i);
2066 if (b.hasPackage(packageName)) {
2067 return true;
2068 }
2069 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002070 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002071 final Alarm a = mPendingWhileIdleAlarms.get(i);
2072 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002073 return true;
2074 }
2075 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002076 return false;
2077 }
2078
2079 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002080 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002081 // The kernel never triggers alarms with negative wakeup times
2082 // so we ensure they are positive.
2083 long alarmSeconds, alarmNanoseconds;
2084 if (when < 0) {
2085 alarmSeconds = 0;
2086 alarmNanoseconds = 0;
2087 } else {
2088 alarmSeconds = when / 1000;
2089 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2090 }
2091
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002092 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002093 } else {
2094 Message msg = Message.obtain();
2095 msg.what = ALARM_EVENT;
2096
2097 mHandler.removeMessages(ALARM_EVENT);
2098 mHandler.sendMessageAtTime(msg, when);
2099 }
2100 }
2101
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002102 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002103 String prefix, String label, long nowRTC, long nowELAPSED, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002104 for (int i=list.size()-1; i>=0; i--) {
2105 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002106 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2107 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002108 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002109 }
2110 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002111
2112 private static final String labelForType(int type) {
2113 switch (type) {
2114 case RTC: return "RTC";
2115 case RTC_WAKEUP : return "RTC_WAKEUP";
2116 case ELAPSED_REALTIME : return "ELAPSED";
2117 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
2118 default:
2119 break;
2120 }
2121 return "--unknown--";
2122 }
2123
2124 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002125 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002126 for (int i=list.size()-1; i>=0; i--) {
2127 Alarm a = list.get(i);
2128 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002129 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2130 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002131 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002132 }
2133 }
2134
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002135 private native long init();
2136 private native void close(long nativeData);
2137 private native void set(long nativeData, int type, long seconds, long nanoseconds);
2138 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08002139 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002140 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002141
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002142 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002143 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002144 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002145 // batches are temporally sorted, so we need only pull from the
2146 // start of the list until we either empty it or hit a batch
2147 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07002148 while (mAlarmBatches.size() > 0) {
2149 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002150 if (batch.start > nowELAPSED) {
2151 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002152 break;
2153 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002154
Christopher Tatee0a22b32013-07-11 14:43:13 -07002155 // We will (re)schedule some alarms now; don't let that interfere
2156 // with delivery of this current batch
2157 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002158
Christopher Tatee0a22b32013-07-11 14:43:13 -07002159 final int N = batch.size();
2160 for (int i = 0; i < N; i++) {
2161 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002162
2163 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
2164 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
2165 // schedule such alarms.
2166 long lastTime = mLastAllowWhileIdleDispatch.get(alarm.uid, 0);
2167 long minTime = lastTime + mAllowWhileIdleMinTime;
2168 if (nowELAPSED < minTime) {
2169 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
2170 // alarm went off for this app. Reschedule the alarm to be in the
2171 // correct time period.
2172 alarm.whenElapsed = minTime;
2173 if (alarm.maxWhenElapsed < minTime) {
2174 alarm.maxWhenElapsed = minTime;
2175 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002176 if (RECORD_DEVICE_IDLE_ALARMS) {
2177 IdleDispatchEntry ent = new IdleDispatchEntry();
2178 ent.uid = alarm.uid;
2179 ent.pkg = alarm.operation.getCreatorPackage();
2180 ent.tag = alarm.operation.getTag("");
2181 ent.op = "RESCHEDULE";
2182 ent.elapsedRealtime = nowELAPSED;
2183 ent.argRealtime = lastTime;
2184 mAllowWhileIdleDispatches.add(ent);
2185 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002186 setImplLocked(alarm, true, false);
2187 continue;
2188 }
2189 }
2190
Christopher Tatee0a22b32013-07-11 14:43:13 -07002191 alarm.count = 1;
2192 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002193 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
2194 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002195 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002196 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002197 if (mPendingIdleUntil == alarm) {
2198 mPendingIdleUntil = null;
2199 rebatchAllAlarmsLocked(false);
2200 restorePendingWhileIdleAlarmsLocked();
2201 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002202 if (mNextWakeFromIdle == alarm) {
2203 mNextWakeFromIdle = null;
2204 rebatchAllAlarmsLocked(false);
2205 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002206
2207 // Recurring alarms may have passed several alarm intervals while the
2208 // phone was asleep or off, so pass a trigger count when sending them.
2209 if (alarm.repeatInterval > 0) {
2210 // this adjustment will be zero if we're late by
2211 // less than one full repeat interval
2212 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
2213
2214 // Also schedule its next recurrence
2215 final long delta = alarm.count * alarm.repeatInterval;
2216 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07002217 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07002218 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07002219 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
2220 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08002221 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002222
Christopher Tate864d42e2014-12-02 11:48:53 -08002223 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002224 hasWakeup = true;
2225 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002226
2227 // We removed an alarm clock. Let the caller recompute the next alarm clock.
2228 if (alarm.alarmClock != null) {
2229 mNextAlarmClockMayChange = true;
2230 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07002231 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002232 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002233
Christopher Tate1590f1e2014-10-02 17:27:57 -07002234 // This is a new alarm delivery set; bump the sequence number to indicate that
2235 // all apps' alarm delivery classes should be recalculated.
2236 mCurrentSeq++;
2237 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002238 Collections.sort(triggerList, mAlarmDispatchComparator);
2239
2240 if (localLOGV) {
2241 for (int i=0; i<triggerList.size(); i++) {
2242 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
2243 }
2244 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002245
2246 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002247 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002249 /**
2250 * This Comparator sorts Alarms into increasing time order.
2251 */
2252 public static class IncreasingTimeOrder implements Comparator<Alarm> {
2253 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09002254 long when1 = a1.whenElapsed;
2255 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002256 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002257 return 1;
2258 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002259 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002260 return -1;
2261 }
2262 return 0;
2263 }
2264 }
2265
2266 private static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002267 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002268 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002269 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002270 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002271 public final IAlarmListener listener;
2272 public final String listenerTag;
2273 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002274 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002275 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002276 public final AlarmManager.AlarmClockInfo alarmClock;
2277 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002278 public final int creatorUid;
2279 public final String packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002280 public int count;
2281 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07002282 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002283 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002284 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002285 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07002286 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002287
Christopher Tate3e04b472013-10-21 17:51:31 -07002288 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002289 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
2290 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
2291 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002292 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002293 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002294 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
2295 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002296 when = _when;
2297 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07002298 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002299 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002300 repeatInterval = _interval;
2301 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002302 listener = _rec;
2303 listenerTag = _listenerTag;
2304 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07002305 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002306 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002307 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002308 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002309 packageName = _pkgName;
2310
2311 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002312 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002313
Christopher Tate14a7bb02015-10-01 10:24:31 -07002314 public static String makeTag(PendingIntent pi, String tag, int type) {
2315 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
2316 ? "*walarm*:" : "*alarm*:";
2317 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
2318 }
2319
2320 public WakeupEvent makeWakeupEvent(long nowRTC) {
2321 return new WakeupEvent(nowRTC, creatorUid,
2322 (operation != null)
2323 ? operation.getIntent().getAction()
2324 : ("<listener>:" + listenerTag));
2325 }
2326
2327 // Returns true if either matches
2328 public boolean matches(PendingIntent pi, IAlarmListener rec) {
2329 return (operation != null)
2330 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09002331 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07002332 }
2333
2334 public boolean matches(String packageName) {
2335 return (operation != null)
2336 ? packageName.equals(operation.getTargetPackage())
2337 : packageName.equals(this.packageName);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002338 }
2339
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002340 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002341 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002342 StringBuilder sb = new StringBuilder(128);
2343 sb.append("Alarm{");
2344 sb.append(Integer.toHexString(System.identityHashCode(this)));
2345 sb.append(" type ");
2346 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002347 sb.append(" when ");
2348 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002349 sb.append(" ");
Christopher Tate14a7bb02015-10-01 10:24:31 -07002350 if (operation != null) {
2351 sb.append(operation.getTargetPackage());
2352 } else {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002353 sb.append(packageName);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002354 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002355 sb.append('}');
2356 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002357 }
2358
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002359 public void dump(PrintWriter pw, String prefix, long nowRTC, long nowELAPSED,
2360 SimpleDateFormat sdf) {
2361 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002362 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002363 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002364 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
2365 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002366 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002367 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002368 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002369 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002370 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002371 }
2372 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002373 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002374 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002375 pw.print(" count="); pw.print(count);
2376 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002377 if (alarmClock != null) {
2378 pw.print(prefix); pw.println("Alarm clock:");
2379 pw.print(prefix); pw.print(" triggerTime=");
2380 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
2381 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
2382 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002383 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002384 if (listener != null) {
2385 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
2386 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002387 }
2388 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002389
Christopher Tatee0a22b32013-07-11 14:43:13 -07002390 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
2391 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002392 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
2393 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002394 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07002395 break;
2396 }
2397
Christopher Tatee0a22b32013-07-11 14:43:13 -07002398 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002399 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
2400 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002401 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07002402 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002403 }
2404 }
2405
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002406 long currentNonWakeupFuzzLocked(long nowELAPSED) {
2407 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
2408 if (timeSinceOn < 5*60*1000) {
2409 // If the screen has been off for 5 minutes, only delay by at most two minutes.
2410 return 2*60*1000;
2411 } else if (timeSinceOn < 30*60*1000) {
2412 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
2413 return 15*60*1000;
2414 } else {
2415 // Otherwise, we will delay by at most an hour.
2416 return 60*60*1000;
2417 }
2418 }
2419
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002420 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002421 if (duration < 15*60*1000) {
2422 // If the duration until the time is less than 15 minutes, the maximum fuzz
2423 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002424 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002425 } else if (duration < 90*60*1000) {
2426 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
2427 return 15*60*1000;
2428 } else {
2429 // Otherwise, we will fuzz by at most half an hour.
2430 return 30*60*1000;
2431 }
2432 }
2433
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002434 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
2435 if (mInteractive) {
2436 return false;
2437 }
2438 if (mLastAlarmDeliveryTime <= 0) {
2439 return false;
2440 }
minho.choo649acab2014-12-12 16:13:55 +09002441 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002442 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
2443 // and the next delivery time is in the past, then just deliver them all. This
2444 // avoids bugs where we get stuck in a loop trying to poll for alarms.
2445 return false;
2446 }
2447 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
2448 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
2449 }
2450
2451 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
2452 mLastAlarmDeliveryTime = nowELAPSED;
2453 for (int i=0; i<triggerList.size(); i++) {
2454 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07002455 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002456 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07002457 if (localLOGV) {
2458 Slog.v(TAG, "sending alarm " + alarm);
2459 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07002460 if (RECORD_ALARMS_IN_HISTORY) {
2461 if (alarm.workSource != null && alarm.workSource.size() > 0) {
2462 for (int wi=0; wi<alarm.workSource.size(); wi++) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002463 ActivityManager.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002464 alarm.operation, alarm.workSource.get(wi), alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002465 }
2466 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002467 ActivityManager.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002468 alarm.operation, alarm.uid, alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002469 }
2470 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002471 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002472 } catch (RuntimeException e) {
2473 Slog.w(TAG, "Failure sending alarm.", e);
2474 }
2475 }
2476 }
2477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002478 private class AlarmThread extends Thread
2479 {
2480 public AlarmThread()
2481 {
2482 super("AlarmManager");
2483 }
2484
2485 public void run()
2486 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002487 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002489 while (true)
2490 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002491 int result = waitForAlarm(mNativeData);
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002492 mLastWakeup = SystemClock.elapsedRealtime();
Dianne Hackborn390517b2013-05-30 15:03:32 -07002493
2494 triggerList.clear();
2495
Dianne Hackbornc3527222015-05-13 14:03:20 -07002496 final long nowRTC = System.currentTimeMillis();
2497 final long nowELAPSED = SystemClock.elapsedRealtime();
2498
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002500 // The kernel can give us spurious time change notifications due to
2501 // small adjustments it makes internally; we want to filter those out.
2502 final long lastTimeChangeClockTime;
2503 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07002504 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002505 lastTimeChangeClockTime = mLastTimeChangeClockTime;
2506 expectedClockTime = lastTimeChangeClockTime
2507 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07002508 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08002509 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
2510 || nowRTC > (expectedClockTime+1000)) {
2511 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07002512 // let's do it!
2513 if (DEBUG_BATCH) {
2514 Slog.v(TAG, "Time changed notification from kernel; rebatching");
2515 }
2516 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07002517 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07002518 rebatchAllAlarms();
2519 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07002520 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07002521 synchronized (mLock) {
2522 mNumTimeChanged++;
2523 mLastTimeChangeClockTime = nowRTC;
2524 mLastTimeChangeRealtime = nowELAPSED;
2525 }
2526 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
2527 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08002528 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07002529 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
2530 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07002531 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
2532
2533 // The world has changed on us, so we need to re-evaluate alarms
2534 // regardless of whether the kernel has told us one went off.
2535 result |= IS_WAKEUP_MASK;
2536 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002538
Dianne Hackbornc3527222015-05-13 14:03:20 -07002539 if (result != TIME_CHANGED_MASK) {
2540 // If this was anything besides just a time change, then figure what if
2541 // anything to do about alarms.
2542 synchronized (mLock) {
2543 if (localLOGV) Slog.v(
2544 TAG, "Checking for alarms... rtc=" + nowRTC
2545 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07002546
Dianne Hackbornc3527222015-05-13 14:03:20 -07002547 if (WAKEUP_STATS) {
2548 if ((result & IS_WAKEUP_MASK) != 0) {
2549 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
2550 int n = 0;
2551 for (WakeupEvent event : mRecentWakeups) {
2552 if (event.when > newEarliest) break;
2553 n++; // number of now-stale entries at the list head
2554 }
2555 for (int i = 0; i < n; i++) {
2556 mRecentWakeups.remove();
2557 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002558
Dianne Hackbornc3527222015-05-13 14:03:20 -07002559 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002560 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002561 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002562
2563 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2564 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
2565 // if there are no wakeup alarms and the screen is off, we can
2566 // delay what we have so far until the future.
2567 if (mPendingNonWakeupAlarms.size() == 0) {
2568 mStartCurrentDelayTime = nowELAPSED;
2569 mNextNonWakeupDeliveryTime = nowELAPSED
2570 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
2571 }
2572 mPendingNonWakeupAlarms.addAll(triggerList);
2573 mNumDelayedAlarms += triggerList.size();
2574 rescheduleKernelAlarmsLocked();
2575 updateNextAlarmClockLocked();
2576 } else {
2577 // now deliver the alarm intents; if there are pending non-wakeup
2578 // alarms, we need to merge them in to the list. note we don't
2579 // just deliver them first because we generally want non-wakeup
2580 // alarms delivered after wakeup alarms.
2581 rescheduleKernelAlarmsLocked();
2582 updateNextAlarmClockLocked();
2583 if (mPendingNonWakeupAlarms.size() > 0) {
2584 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
2585 triggerList.addAll(mPendingNonWakeupAlarms);
2586 Collections.sort(triggerList, mAlarmDispatchComparator);
2587 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2588 mTotalDelayTime += thisDelayTime;
2589 if (mMaxDelayTime < thisDelayTime) {
2590 mMaxDelayTime = thisDelayTime;
2591 }
2592 mPendingNonWakeupAlarms.clear();
2593 }
2594 deliverAlarmsLocked(triggerList, nowELAPSED);
2595 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002596 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002597
2598 } else {
2599 // Just in case -- even though no wakeup flag was set, make sure
2600 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07002601 synchronized (mLock) {
2602 rescheduleKernelAlarmsLocked();
2603 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002604 }
2605 }
2606 }
2607 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002608
David Christieebe51fc2013-07-26 13:23:29 -07002609 /**
2610 * Attribute blame for a WakeLock.
2611 * @param pi PendingIntent to attribute blame to if ws is null.
2612 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002613 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07002614 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002615 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002616 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07002617 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002618 final boolean unimportant = pi == mTimeTickSender;
2619 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002620 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002621 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002622 } else {
2623 mWakeLock.setHistoryTag(null);
2624 }
2625 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07002626 if (ws != null) {
2627 mWakeLock.setWorkSource(ws);
2628 return;
2629 }
2630
Christopher Tate14a7bb02015-10-01 10:24:31 -07002631 final int uid = (knownUid >= 0)
2632 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002633 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07002634 if (uid >= 0) {
2635 mWakeLock.setWorkSource(new WorkSource(uid));
2636 return;
2637 }
2638 } catch (Exception e) {
2639 }
2640
2641 // Something went wrong; fall back to attributing the lock to the OS
2642 mWakeLock.setWorkSource(null);
2643 }
2644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002645 private class AlarmHandler extends Handler {
2646 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002647 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
2648 public static final int LISTENER_TIMEOUT = 3;
2649 public static final int REPORT_ALARMS_ACTIVE = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002650
2651 public AlarmHandler() {
2652 }
2653
2654 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002655 switch (msg.what) {
2656 case ALARM_EVENT: {
2657 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2658 synchronized (mLock) {
2659 final long nowRTC = System.currentTimeMillis();
2660 final long nowELAPSED = SystemClock.elapsedRealtime();
2661 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2662 updateNextAlarmClockLocked();
2663 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002664
Christopher Tate14a7bb02015-10-01 10:24:31 -07002665 // now trigger the alarms without the lock held
2666 for (int i=0; i<triggerList.size(); i++) {
2667 Alarm alarm = triggerList.get(i);
2668 try {
2669 alarm.operation.send();
2670 } catch (PendingIntent.CanceledException e) {
2671 if (alarm.repeatInterval > 0) {
2672 // This IntentSender is no longer valid, but this
2673 // is a repeating alarm, so toss the hoser.
2674 removeImpl(alarm.operation);
2675 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002676 }
2677 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002678 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002679 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002680
2681 case SEND_NEXT_ALARM_CLOCK_CHANGED:
2682 sendNextAlarmClockChanged();
2683 break;
2684
2685 case LISTENER_TIMEOUT:
2686 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
2687 break;
2688
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002689 case REPORT_ALARMS_ACTIVE:
2690 if (mLocalDeviceIdleController != null) {
2691 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
2692 }
2693 break;
2694
Christopher Tate14a7bb02015-10-01 10:24:31 -07002695 default:
2696 // nope, just ignore it
2697 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002698 }
2699 }
2700 }
2701
2702 class ClockReceiver extends BroadcastReceiver {
2703 public ClockReceiver() {
2704 IntentFilter filter = new IntentFilter();
2705 filter.addAction(Intent.ACTION_TIME_TICK);
2706 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002707 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002708 }
2709
2710 @Override
2711 public void onReceive(Context context, Intent intent) {
2712 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07002713 if (DEBUG_BATCH) {
2714 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
2715 }
2716 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002717 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
2718 // Since the kernel does not keep track of DST, we need to
2719 // reset the TZ information at the beginning of each day
2720 // based off of the current Zone gmt offset + userspace tracked
2721 // daylight savings information.
2722 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02002723 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002724 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07002725 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002726 }
2727 }
2728
2729 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07002730 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09002731 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07002732
2733 // Schedule this event for the amount of time that it would take to get to
2734 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09002735 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07002736
David Christieebe51fc2013-07-26 13:23:29 -07002737 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002738 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002739 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
2740 null, Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002741 }
Christopher Tate385e4982013-07-23 18:22:29 -07002742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002743 public void scheduleDateChangedEvent() {
2744 Calendar calendar = Calendar.getInstance();
2745 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07002746 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002747 calendar.set(Calendar.MINUTE, 0);
2748 calendar.set(Calendar.SECOND, 0);
2749 calendar.set(Calendar.MILLISECOND, 0);
2750 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07002751
2752 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002753 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
2754 AlarmManager.FLAG_STANDALONE, workSource, null,
2755 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002756 }
2757 }
2758
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002759 class InteractiveStateReceiver extends BroadcastReceiver {
2760 public InteractiveStateReceiver() {
2761 IntentFilter filter = new IntentFilter();
2762 filter.addAction(Intent.ACTION_SCREEN_OFF);
2763 filter.addAction(Intent.ACTION_SCREEN_ON);
2764 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
2765 getContext().registerReceiver(this, filter);
2766 }
2767
2768 @Override
2769 public void onReceive(Context context, Intent intent) {
2770 synchronized (mLock) {
2771 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
2772 }
2773 }
2774 }
2775
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002776 class UninstallReceiver extends BroadcastReceiver {
2777 public UninstallReceiver() {
2778 IntentFilter filter = new IntentFilter();
2779 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2780 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002781 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002782 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08002783 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002784 // Register for events related to sdcard installation.
2785 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08002786 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002787 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002788 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002789 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002790 }
2791
2792 @Override
2793 public void onReceive(Context context, Intent intent) {
2794 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002795 String action = intent.getAction();
2796 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002797 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
2798 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
2799 for (String packageName : pkgList) {
2800 if (lookForPackageLocked(packageName)) {
2801 setResultCode(Activity.RESULT_OK);
2802 return;
2803 }
2804 }
2805 return;
2806 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002807 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002808 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
2809 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
2810 if (userHandle >= 0) {
2811 removeUserLocked(userHandle);
2812 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002813 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
2814 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
2815 if (uid >= 0) {
2816 mLastAllowWhileIdleDispatch.delete(uid);
2817 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002818 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08002819 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
2820 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
2821 // This package is being updated; don't kill its alarms.
2822 return;
2823 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002824 Uri data = intent.getData();
2825 if (data != null) {
2826 String pkg = data.getSchemeSpecificPart();
2827 if (pkg != null) {
2828 pkgList = new String[]{pkg};
2829 }
2830 }
2831 }
2832 if (pkgList != null && (pkgList.length > 0)) {
2833 for (String pkg : pkgList) {
2834 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07002835 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002836 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
2837 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
2838 if (uidStats.remove(pkg) != null) {
2839 if (uidStats.size() <= 0) {
2840 mBroadcastStats.removeAt(i);
2841 }
2842 }
2843 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002844 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002845 }
2846 }
2847 }
2848 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002849
2850 final class UidObserver extends IUidObserver.Stub {
Sudheer Shanka80255802017-03-04 14:48:53 -08002851 @Override public void onUidStateChanged(int uid, int procState,
2852 long procStateSeq) throws RemoteException {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002853 }
2854
Dianne Hackborne07641d2016-11-09 15:07:23 -08002855 @Override public void onUidGone(int uid, boolean disabled) throws RemoteException {
2856 if (disabled) {
2857 synchronized (mLock) {
2858 removeForStoppedLocked(uid);
2859 }
2860 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002861 }
2862
2863 @Override public void onUidActive(int uid) throws RemoteException {
2864 }
2865
Dianne Hackborne07641d2016-11-09 15:07:23 -08002866 @Override public void onUidIdle(int uid, boolean disabled) throws RemoteException {
2867 if (disabled) {
2868 synchronized (mLock) {
2869 removeForStoppedLocked(uid);
2870 }
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08002871 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002872 }
2873 };
2874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002875 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002876 String pkg = pi.getCreatorPackage();
2877 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002878 return getStatsLocked(uid, pkg);
2879 }
2880
2881 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002882 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
2883 if (uidStats == null) {
2884 uidStats = new ArrayMap<String, BroadcastStats>();
2885 mBroadcastStats.put(uid, uidStats);
2886 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002887 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002889 bs = new BroadcastStats(uid, pkgName);
2890 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002891 }
2892 return bs;
2893 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002894
Christopher Tate14a7bb02015-10-01 10:24:31 -07002895 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
2896 private InFlight removeLocked(PendingIntent pi, Intent intent) {
2897 for (int i = 0; i < mInFlight.size(); i++) {
2898 if (mInFlight.get(i).mPendingIntent == pi) {
2899 return mInFlight.remove(i);
2900 }
2901 }
2902 mLog.w("No in-flight alarm for " + pi + " " + intent);
2903 return null;
2904 }
2905
2906 private InFlight removeLocked(IBinder listener) {
2907 for (int i = 0; i < mInFlight.size(); i++) {
2908 if (mInFlight.get(i).mListener == listener) {
2909 return mInFlight.remove(i);
2910 }
2911 }
2912 mLog.w("No in-flight alarm for listener " + listener);
2913 return null;
2914 }
2915
2916 private void updateStatsLocked(InFlight inflight) {
2917 final long nowELAPSED = SystemClock.elapsedRealtime();
2918 BroadcastStats bs = inflight.mBroadcastStats;
2919 bs.nesting--;
2920 if (bs.nesting <= 0) {
2921 bs.nesting = 0;
2922 bs.aggregateTime += nowELAPSED - bs.startTime;
2923 }
2924 FilterStats fs = inflight.mFilterStats;
2925 fs.nesting--;
2926 if (fs.nesting <= 0) {
2927 fs.nesting = 0;
2928 fs.aggregateTime += nowELAPSED - fs.startTime;
2929 }
2930 if (RECORD_ALARMS_IN_HISTORY) {
2931 if (inflight.mWorkSource != null && inflight.mWorkSource.size() > 0) {
2932 for (int wi=0; wi<inflight.mWorkSource.size(); wi++) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002933 ActivityManager.noteAlarmFinish(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002934 inflight.mPendingIntent, inflight.mWorkSource.get(wi), inflight.mTag);
2935 }
2936 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002937 ActivityManager.noteAlarmFinish(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002938 inflight.mPendingIntent, inflight.mUid, inflight.mTag);
2939 }
2940 }
2941 }
2942
2943 private void updateTrackingLocked(InFlight inflight) {
2944 if (inflight != null) {
2945 updateStatsLocked(inflight);
2946 }
2947 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08002948 if (DEBUG_WAKELOCK) {
2949 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
2950 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002951 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002952 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002953 mWakeLock.release();
2954 if (mInFlight.size() > 0) {
2955 mLog.w("Finished all dispatches with " + mInFlight.size()
2956 + " remaining inflights");
2957 for (int i=0; i<mInFlight.size(); i++) {
2958 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
2959 }
2960 mInFlight.clear();
2961 }
2962 } else {
2963 // the next of our alarms is now in flight. reattribute the wakelock.
2964 if (mInFlight.size() > 0) {
2965 InFlight inFlight = mInFlight.get(0);
2966 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
2967 inFlight.mAlarmType, inFlight.mTag, -1, false);
2968 } else {
2969 // should never happen
2970 mLog.w("Alarm wakelock still held but sent queue empty");
2971 mWakeLock.setWorkSource(null);
2972 }
2973 }
2974 }
2975
2976 /**
2977 * Callback that arrives when a direct-call alarm reports that delivery has finished
2978 */
2979 @Override
2980 public void alarmComplete(IBinder who) {
2981 if (who == null) {
2982 Slog.w(TAG, "Invalid alarmComplete: uid=" + Binder.getCallingUid()
2983 + " pid=" + Binder.getCallingPid());
2984 return;
2985 }
2986
2987 final long ident = Binder.clearCallingIdentity();
2988 try {
2989 synchronized (mLock) {
2990 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
2991 InFlight inflight = removeLocked(who);
2992 if (inflight != null) {
2993 if (DEBUG_LISTENER_CALLBACK) {
2994 Slog.i(TAG, "alarmComplete() from " + who);
2995 }
2996 updateTrackingLocked(inflight);
2997 } else {
2998 // Delivery timed out, and the timeout handling already took care of
2999 // updating our tracking here, so we needn't do anything further.
3000 if (DEBUG_LISTENER_CALLBACK) {
3001 Slog.i(TAG, "Late alarmComplete() from " + who);
3002 }
3003 }
3004 }
3005 } finally {
3006 Binder.restoreCallingIdentity(ident);
3007 }
3008 }
3009
3010 /**
3011 * Callback that arrives when a PendingIntent alarm has finished delivery
3012 */
3013 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003014 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
3015 String resultData, Bundle resultExtras) {
3016 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003017 updateTrackingLocked(removeLocked(pi, intent));
3018 }
3019 }
3020
3021 /**
3022 * Timeout of a direct-call alarm delivery
3023 */
3024 public void alarmTimedOut(IBinder who) {
3025 synchronized (mLock) {
3026 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08003027 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003028 // TODO: implement ANR policy for the target
3029 if (DEBUG_LISTENER_CALLBACK) {
3030 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003031 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003032 updateTrackingLocked(inflight);
Dianne Hackborn81038902012-11-26 17:04:09 -08003033 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003034 if (DEBUG_LISTENER_CALLBACK) {
3035 Slog.i(TAG, "Spurious timeout of listener " + who);
3036 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003037 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003038 }
3039 }
3040
3041 /**
3042 * Deliver an alarm and set up the post-delivery handling appropriately
3043 */
3044 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
3045 if (alarm.operation != null) {
3046 // PendingIntent alarm
3047 try {
3048 alarm.operation.send(getContext(), 0,
3049 mBackgroundIntent.putExtra(
3050 Intent.EXTRA_ALARM_COUNT, alarm.count),
3051 mDeliveryTracker, mHandler, null,
3052 allowWhileIdle ? mIdleOptions : null);
3053 } catch (PendingIntent.CanceledException e) {
3054 if (alarm.repeatInterval > 0) {
3055 // This IntentSender is no longer valid, but this
3056 // is a repeating alarm, so toss it
3057 removeImpl(alarm.operation);
3058 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003059 // No actual delivery was possible, so the delivery tracker's
3060 // 'finished' callback won't be invoked. We also don't need
3061 // to do any wakelock or stats tracking, so we have nothing
3062 // left to do here but go on to the next thing.
3063 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003064 }
3065 } else {
3066 // Direct listener callback alarm
3067 try {
3068 if (DEBUG_LISTENER_CALLBACK) {
3069 Slog.v(TAG, "Alarm to uid=" + alarm.uid
3070 + " listener=" + alarm.listener.asBinder());
3071 }
3072 alarm.listener.doAlarm(this);
3073 mHandler.sendMessageDelayed(
3074 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
3075 alarm.listener.asBinder()),
3076 mConstants.LISTENER_TIMEOUT);
3077 } catch (Exception e) {
3078 if (DEBUG_LISTENER_CALLBACK) {
3079 Slog.i(TAG, "Alarm undeliverable to listener "
3080 + alarm.listener.asBinder(), e);
3081 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003082 // As in the PendingIntent.CanceledException case, delivery of the
3083 // alarm was not possible, so we have no wakelock or timeout or
3084 // stats management to do. It threw before we posted the delayed
3085 // timeout message, so we're done here.
3086 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003087 }
3088 }
3089
3090 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08003091 if (DEBUG_WAKELOCK) {
3092 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
3093 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003094 if (mBroadcastRefCount == 0) {
3095 setWakelockWorkSource(alarm.operation, alarm.workSource,
3096 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
3097 true);
3098 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003099 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003100 }
3101 final InFlight inflight = new InFlight(AlarmManagerService.this,
3102 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
3103 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
3104 mInFlight.add(inflight);
3105 mBroadcastRefCount++;
3106
3107 if (allowWhileIdle) {
3108 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
3109 mLastAllowWhileIdleDispatch.put(alarm.uid, nowELAPSED);
3110 if (RECORD_DEVICE_IDLE_ALARMS) {
3111 IdleDispatchEntry ent = new IdleDispatchEntry();
3112 ent.uid = alarm.uid;
3113 ent.pkg = alarm.packageName;
3114 ent.tag = alarm.statsTag;
3115 ent.op = "DELIVER";
3116 ent.elapsedRealtime = nowELAPSED;
3117 mAllowWhileIdleDispatches.add(ent);
3118 }
3119 }
3120
3121 final BroadcastStats bs = inflight.mBroadcastStats;
3122 bs.count++;
3123 if (bs.nesting == 0) {
3124 bs.nesting = 1;
3125 bs.startTime = nowELAPSED;
3126 } else {
3127 bs.nesting++;
3128 }
3129 final FilterStats fs = inflight.mFilterStats;
3130 fs.count++;
3131 if (fs.nesting == 0) {
3132 fs.nesting = 1;
3133 fs.startTime = nowELAPSED;
3134 } else {
3135 fs.nesting++;
3136 }
3137 if (alarm.type == ELAPSED_REALTIME_WAKEUP
3138 || alarm.type == RTC_WAKEUP) {
3139 bs.numWakeup++;
3140 fs.numWakeup++;
3141 if (alarm.workSource != null && alarm.workSource.size() > 0) {
3142 for (int wi=0; wi<alarm.workSource.size(); wi++) {
Christopher Tate0029f572016-06-14 10:16:28 -07003143 final String wsName = alarm.workSource.getName(wi);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003144 ActivityManager.noteWakeupAlarm(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003145 alarm.operation, alarm.workSource.get(wi),
Christopher Tate0029f572016-06-14 10:16:28 -07003146 (wsName != null) ? wsName : alarm.packageName,
3147 alarm.statsTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08003148 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003149 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003150 ActivityManager.noteWakeupAlarm(
Joe Onorato78bcdf92016-05-09 10:10:29 -07003151 alarm.operation, alarm.uid, alarm.packageName, alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003152 }
3153 }
3154 }
3155 }
3156}