blob: 550774a1df580a2adb3c855cfe1ec43eddbdb429 [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
Christopher Tate5cdf9f82017-05-03 18:10:39 -07001052 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
Chad Brubaker291df4f2017-03-14 10:23:02 -07001053 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001054 intent.putExtra("time-zone", zone.getID());
1055 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1056 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001058
Adam Lesinski182f73f2013-12-05 16:48:06 -08001059 void removeImpl(PendingIntent operation) {
1060 if (operation == null) {
1061 return;
1062 }
1063 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001064 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001065 }
1066 }
1067
1068 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001069 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1070 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1071 int callingUid, String callingPackage) {
1072 // must be *either* PendingIntent or AlarmReceiver, but not both
1073 if ((operation == null && directReceiver == null)
1074 || (operation != null && directReceiver != null)) {
1075 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1076 // NB: previous releases failed silently here, so we are continuing to do the same
1077 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 return;
1079 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001080
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001081 // Sanity check the window length. This will catch people mistakenly
1082 // trying to pass an end-of-window timestamp rather than a duration.
1083 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1084 Slog.w(TAG, "Window length " + windowLength
1085 + "ms suspiciously long; limiting to 1 hour");
1086 windowLength = AlarmManager.INTERVAL_HOUR;
1087 }
1088
Christopher Tate498c6cb2014-11-17 16:09:27 -08001089 // Sanity check the recurrence interval. This will catch people who supply
1090 // seconds when the API expects milliseconds.
Dianne Hackborna750a632015-06-16 17:18:23 -07001091 final long minInterval = mConstants.MIN_INTERVAL;
1092 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001093 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001094 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001095 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001096 interval = minInterval;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001097 }
1098
Christopher Tatee0a22b32013-07-11 14:43:13 -07001099 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1100 throw new IllegalArgumentException("Invalid alarm type " + type);
1101 }
1102
Christopher Tate5f221e82013-07-30 17:13:15 -07001103 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001104 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001105 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001106 + " pid=" + what);
1107 triggerAtTime = 0;
1108 }
1109
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001110 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001111 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1112 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001113 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001114 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1115
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001116 final long maxElapsed;
1117 if (windowLength == AlarmManager.WINDOW_EXACT) {
1118 maxElapsed = triggerElapsed;
1119 } else if (windowLength < 0) {
1120 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001121 // Fix this window in place, so that as time approaches we don't collapse it.
1122 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001123 } else {
1124 maxElapsed = triggerElapsed + windowLength;
1125 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001127 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001128 if (DEBUG_BATCH) {
1129 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001130 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001131 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001132 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001134 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001135 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1136 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001137 }
1138 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139
Christopher Tate3e04b472013-10-21 17:51:31 -07001140 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001141 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1142 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1143 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001144 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001145 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1146 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001147 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001148 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001149 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1150 + " -- package not allowed to start");
1151 return;
1152 }
1153 } catch (RemoteException e) {
1154 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001155 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001156 setImplLocked(a, false, doValidate);
1157 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001158
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001159 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1160 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001161 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001162 // The caller has given the time they want this to happen at, however we need
1163 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001164 // bring us out of idle at an earlier time.
1165 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001166 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001167 }
1168 // Add fuzz to make the alarm go off some time before the actual desired time.
1169 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001170 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001171 if (fuzz > 0) {
1172 if (mRandom == null) {
1173 mRandom = new Random();
1174 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001175 final int delta = mRandom.nextInt(fuzz);
1176 a.whenElapsed -= delta;
1177 if (false) {
1178 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1179 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1180 Slog.d(TAG, "Applied fuzz: " + fuzz);
1181 Slog.d(TAG, "Final delta: " + delta);
1182 Slog.d(TAG, "Final when: " + a.whenElapsed);
1183 }
1184 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001185 }
1186
1187 } else if (mPendingIdleUntil != null) {
1188 // We currently have an idle until alarm scheduled; if the new alarm has
1189 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001190 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1191 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1192 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001193 == 0) {
1194 mPendingWhileIdleAlarms.add(a);
1195 return;
1196 }
1197 }
1198
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001199 if (RECORD_DEVICE_IDLE_ALARMS) {
1200 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1201 IdleDispatchEntry ent = new IdleDispatchEntry();
1202 ent.uid = a.uid;
1203 ent.pkg = a.operation.getCreatorPackage();
1204 ent.tag = a.operation.getTag("");
1205 ent.op = "SET";
1206 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1207 ent.argRealtime = a.whenElapsed;
1208 mAllowWhileIdleDispatches.add(ent);
1209 }
1210 }
1211
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001212 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
1213 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -07001214 if (whichBatch < 0) {
1215 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001216 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001217 } else {
Christopher Tate385e4982013-07-23 18:22:29 -07001218 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001219 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001220 // The start time of this batch advanced, so batch ordering may
1221 // have just been broken. Move it to where it now belongs.
1222 mAlarmBatches.remove(whichBatch);
1223 addBatchLocked(mAlarmBatches, batch);
1224 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001225 }
1226
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001227 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001228 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001229 }
1230
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001231 boolean needRebatch = false;
1232
1233 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001234 if (RECORD_DEVICE_IDLE_ALARMS) {
1235 if (mPendingIdleUntil == null) {
1236 IdleDispatchEntry ent = new IdleDispatchEntry();
1237 ent.uid = 0;
1238 ent.pkg = "START IDLE";
1239 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1240 mAllowWhileIdleDispatches.add(ent);
1241 }
1242 }
Makoto Onuki4274a6d2017-04-21 12:21:25 -07001243 if ((mPendingIdleUntil != a) && (mPendingIdleUntil != null)) {
1244 Slog.wtfStack(TAG, "setImplLocked: idle until changed from " + mPendingIdleUntil
1245 + " to " + a);
1246 }
1247
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001248 mPendingIdleUntil = a;
Dianne Hackborna750a632015-06-16 17:18:23 -07001249 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001250 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001251 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1252 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1253 mNextWakeFromIdle = a;
1254 // If this wake from idle is earlier than whatever was previously scheduled,
1255 // and we are currently idling, then we need to rebatch alarms in case the idle
1256 // until time needs to be updated.
1257 if (mPendingIdleUntil != null) {
1258 needRebatch = true;
1259 }
1260 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001261 }
1262
1263 if (!rebatching) {
1264 if (DEBUG_VALIDATE) {
1265 if (doValidate && !validateConsistencyLocked()) {
1266 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1267 + " when(hex)=" + Long.toHexString(a.when)
1268 + " whenElapsed=" + a.whenElapsed
1269 + " maxWhenElapsed=" + a.maxWhenElapsed
1270 + " interval=" + a.repeatInterval + " op=" + a.operation
1271 + " flags=0x" + Integer.toHexString(a.flags));
1272 rebatchAllAlarmsLocked(false);
1273 needRebatch = false;
1274 }
1275 }
1276
1277 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001278 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001279 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001280
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001281 rescheduleKernelAlarmsLocked();
1282 updateNextAlarmClockLocked();
1283 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001284 }
1285
Adam Lesinski182f73f2013-12-05 16:48:06 -08001286 private final IBinder mService = new IAlarmManager.Stub() {
1287 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001288 public void set(String callingPackage,
1289 int type, long triggerAtTime, long windowLength, long interval, int flags,
1290 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1291 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001292 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001293
1294 // make sure the caller is not lying about which package should be blamed for
1295 // wakelock time spent in alarm delivery
1296 mAppOps.checkPackage(callingUid, callingPackage);
1297
1298 // Repeating alarms must use PendingIntent, not direct listener
1299 if (interval != 0) {
1300 if (directReceiver != null) {
1301 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1302 }
1303 }
1304
Adam Lesinski182f73f2013-12-05 16:48:06 -08001305 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001306 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001307 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001308 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001309 }
1310
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001311 // No incoming callers can request either WAKE_FROM_IDLE or
1312 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1313 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1314 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1315
1316 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1317 // manager when to come out of idle mode, which is only for DeviceIdleController.
1318 if (callingUid != Process.SYSTEM_UID) {
1319 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1320 }
1321
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001322 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001323 if (windowLength == AlarmManager.WINDOW_EXACT) {
1324 flags |= AlarmManager.FLAG_STANDALONE;
1325 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001326
1327 // If this alarm is for an alarm clock, then it must be standalone and we will
1328 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001329 if (alarmClock != null) {
1330 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001331
1332 // If the caller is a core system component or on the user's whitelist, and not calling
1333 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1334 // This means we will allow these alarms to go off as normal even while idle, with no
1335 // timing restrictions.
1336 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
1337 || Arrays.binarySearch(mDeviceIdleUserWhitelist,
1338 UserHandle.getAppId(callingUid)) >= 0)) {
1339 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1340 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001341 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001342
Christopher Tate14a7bb02015-10-01 10:24:31 -07001343 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1344 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001345 }
Christopher Tate89779822012-08-31 14:40:03 -07001346
Adam Lesinski182f73f2013-12-05 16:48:06 -08001347 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001348 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001349 getContext().enforceCallingOrSelfPermission(
1350 "android.permission.SET_TIME",
1351 "setTime");
1352
Greg Hackmann0cab8962014-02-21 16:35:52 -08001353 if (mNativeData == 0) {
1354 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1355 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001356 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001357
1358 synchronized (mLock) {
1359 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001362
1363 @Override
1364 public void setTimeZone(String tz) {
1365 getContext().enforceCallingOrSelfPermission(
1366 "android.permission.SET_TIME_ZONE",
1367 "setTimeZone");
1368
1369 final long oldId = Binder.clearCallingIdentity();
1370 try {
1371 setTimeZoneImpl(tz);
1372 } finally {
1373 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 }
1375 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001376
Adam Lesinski182f73f2013-12-05 16:48:06 -08001377 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001378 public void remove(PendingIntent operation, IAlarmListener listener) {
1379 if (operation == null && listener == null) {
1380 Slog.w(TAG, "remove() with no intent or listener");
1381 return;
1382 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001383
Christopher Tate14a7bb02015-10-01 10:24:31 -07001384 synchronized (mLock) {
1385 removeLocked(operation, listener);
1386 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001388
Adam Lesinski182f73f2013-12-05 16:48:06 -08001389 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001390 public long getNextWakeFromIdleTime() {
1391 return getNextWakeFromIdleTimeImpl();
1392 }
1393
1394 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001395 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001396 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1397 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1398 "getNextAlarmClock", null);
1399
1400 return getNextAlarmClockImpl(userId);
1401 }
1402
1403 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001404 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06001405 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001406 dumpImpl(pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001407 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001408 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001409
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001410 public final class LocalService {
1411 public void setDeviceIdleUserWhitelist(int[] appids) {
1412 setDeviceIdleUserWhitelistImpl(appids);
1413 }
1414 }
1415
Adam Lesinski182f73f2013-12-05 16:48:06 -08001416 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 synchronized (mLock) {
1418 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001419 mConstants.dump(pw);
1420 pw.println();
1421
Christopher Tatee0a22b32013-07-11 14:43:13 -07001422 final long nowRTC = System.currentTimeMillis();
1423 final long nowELAPSED = SystemClock.elapsedRealtime();
1424 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1425
Dianne Hackborna750a632015-06-16 17:18:23 -07001426 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001427 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001428 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001429 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001430 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001431 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001432 pw.print(" mLastTimeChangeRealtime=");
Dianne Hackbornc3527222015-05-13 14:03:20 -07001433 TimeUtils.formatDuration(mLastTimeChangeRealtime, pw);
1434 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001435 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001436 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001437 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1438 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001439 pw.print(" Max wakeup delay: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001440 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1441 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001442 pw.print(" Time since last dispatch: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001443 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1444 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001445 pw.print(" Next non-wakeup delivery time: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001446 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1447 pw.println();
1448 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001449
1450 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1451 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001452 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001453 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001454 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001455 pw.print(" Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001456 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001457 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
1458 pw.print(" set at "); TimeUtils.formatDuration(mLastWakeupSet, nowELAPSED, pw);
1459 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001460 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001461 pw.println(" mDeviceIdleUserWhitelist=" + Arrays.toString(mDeviceIdleUserWhitelist));
Christopher Tatee0a22b32013-07-11 14:43:13 -07001462
John Spurlock604a5ee2015-06-01 12:27:22 -04001463 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001464 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001465 final TreeSet<Integer> users = new TreeSet<>();
1466 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1467 users.add(mNextAlarmClockForUser.keyAt(i));
1468 }
1469 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1470 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1471 }
1472 for (int user : users) {
1473 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1474 final long time = next != null ? next.getTriggerTime() : 0;
1475 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001476 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001477 pw.print(" pendingSend:"); pw.print(pendingSend);
1478 pw.print(" time:"); pw.print(time);
1479 if (time > 0) {
1480 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1481 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1482 }
1483 pw.println();
1484 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001485 if (mAlarmBatches.size() > 0) {
1486 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001487 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001488 pw.println(mAlarmBatches.size());
1489 for (Batch b : mAlarmBatches) {
1490 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001491 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001492 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001494 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001495 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001496 pw.println(" Idle mode state:");
1497 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001498 if (mPendingIdleUntil != null) {
1499 pw.println(mPendingIdleUntil);
Dianne Hackbornf3831292015-10-15 14:51:06 -07001500 mPendingIdleUntil.dump(pw, " ", nowRTC, nowELAPSED, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001501 } else {
1502 pw.println("null");
1503 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001504 pw.println(" Pending alarms:");
1505 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001506 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001507 if (mNextWakeFromIdle != null) {
1508 pw.println();
1509 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
1510 mNextWakeFromIdle.dump(pw, " ", nowRTC, nowELAPSED, sdf);
1511 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001512
1513 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001514 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001515 if (mPendingNonWakeupAlarms.size() > 0) {
1516 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001517 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001518 } else {
1519 pw.println("(none)");
1520 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001521 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001522 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1523 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001524 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001525 pw.print(", max non-interactive time: ");
1526 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1527 pw.println();
1528
1529 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001530 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001531 pw.println();
1532
Christopher Tate7f2a0352015-12-08 10:24:33 -08001533 if (mInFlight.size() > 0) {
1534 pw.println("Outstanding deliveries:");
1535 for (int i = 0; i < mInFlight.size(); i++) {
1536 pw.print(" #"); pw.print(i); pw.print(": ");
1537 pw.println(mInFlight.get(i));
1538 }
1539 pw.println();
1540 }
1541
Dianne Hackborna750a632015-06-16 17:18:23 -07001542 pw.print(" mAllowWhileIdleMinTime=");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001543 TimeUtils.formatDuration(mAllowWhileIdleMinTime, pw);
1544 pw.println();
1545 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001546 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001547 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
1548 pw.print(" UID ");
1549 UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
1550 pw.print(": ");
1551 TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i),
1552 nowELAPSED, pw);
1553 pw.println();
1554 }
1555 }
1556 pw.println();
1557
Dianne Hackborn81038902012-11-26 17:04:09 -08001558 if (mLog.dump(pw, " Recent problems", " ")) {
1559 pw.println();
1560 }
1561
1562 final FilterStats[] topFilters = new FilterStats[10];
1563 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1564 @Override
1565 public int compare(FilterStats lhs, FilterStats rhs) {
1566 if (lhs.aggregateTime < rhs.aggregateTime) {
1567 return 1;
1568 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1569 return -1;
1570 }
1571 return 0;
1572 }
1573 };
1574 int len = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001575 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1576 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1577 for (int ip=0; ip<uidStats.size(); ip++) {
1578 BroadcastStats bs = uidStats.valueAt(ip);
1579 for (int is=0; is<bs.filterStats.size(); is++) {
1580 FilterStats fs = bs.filterStats.valueAt(is);
1581 int pos = len > 0
1582 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1583 if (pos < 0) {
1584 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001585 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001586 if (pos < topFilters.length) {
1587 int copylen = topFilters.length - pos - 1;
1588 if (copylen > 0) {
1589 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1590 }
1591 topFilters[pos] = fs;
1592 if (len < topFilters.length) {
1593 len++;
1594 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001595 }
1596 }
1597 }
1598 }
1599 if (len > 0) {
1600 pw.println(" Top Alarms:");
1601 for (int i=0; i<len; i++) {
1602 FilterStats fs = topFilters[i];
1603 pw.print(" ");
1604 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1605 TimeUtils.formatDuration(fs.aggregateTime, pw);
1606 pw.print(" running, "); pw.print(fs.numWakeup);
1607 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001608 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1609 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001610 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001611 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001612 pw.println();
1613 }
1614 }
1615
1616 pw.println(" ");
1617 pw.println(" Alarm Stats:");
1618 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001619 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1620 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1621 for (int ip=0; ip<uidStats.size(); ip++) {
1622 BroadcastStats bs = uidStats.valueAt(ip);
1623 pw.print(" ");
1624 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1625 UserHandle.formatUid(pw, bs.mUid);
1626 pw.print(":");
1627 pw.print(bs.mPackageName);
1628 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1629 pw.print(" running, "); pw.print(bs.numWakeup);
1630 pw.println(" wakeups:");
1631 tmpFilters.clear();
1632 for (int is=0; is<bs.filterStats.size(); is++) {
1633 tmpFilters.add(bs.filterStats.valueAt(is));
1634 }
1635 Collections.sort(tmpFilters, comparator);
1636 for (int i=0; i<tmpFilters.size(); i++) {
1637 FilterStats fs = tmpFilters.get(i);
1638 pw.print(" ");
1639 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1640 TimeUtils.formatDuration(fs.aggregateTime, pw);
1641 pw.print(" "); pw.print(fs.numWakeup);
1642 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001643 pw.print(" alarms, last ");
1644 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1645 pw.println(":");
1646 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001647 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001648 pw.println();
1649 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 }
1651 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001652
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001653 if (RECORD_DEVICE_IDLE_ALARMS) {
1654 pw.println();
1655 pw.println(" Allow while idle dispatches:");
1656 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
1657 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
1658 pw.print(" ");
1659 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
1660 pw.print(": ");
1661 UserHandle.formatUid(pw, ent.uid);
1662 pw.print(":");
1663 pw.println(ent.pkg);
1664 if (ent.op != null) {
1665 pw.print(" ");
1666 pw.print(ent.op);
1667 pw.print(" / ");
1668 pw.print(ent.tag);
1669 if (ent.argRealtime != 0) {
1670 pw.print(" (");
1671 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
1672 pw.print(")");
1673 }
1674 pw.println();
1675 }
1676 }
1677 }
1678
Christopher Tate18a75f12013-07-01 18:18:59 -07001679 if (WAKEUP_STATS) {
1680 pw.println();
1681 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001682 long last = -1;
1683 for (WakeupEvent event : mRecentWakeups) {
1684 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1685 pw.print('|');
1686 if (last < 0) {
1687 pw.print('0');
1688 } else {
1689 pw.print(event.when - last);
1690 }
1691 last = event.when;
1692 pw.print('|'); pw.print(event.uid);
1693 pw.print('|'); pw.print(event.action);
1694 pw.println();
1695 }
1696 pw.println();
1697 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 }
1699 }
1700
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001701 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001702 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
1703 PrintWriter pw = new PrintWriter(bs);
1704 final long nowRTC = System.currentTimeMillis();
1705 final long nowELAPSED = SystemClock.elapsedRealtime();
1706 final int NZ = mAlarmBatches.size();
1707 for (int iz = 0; iz < NZ; iz++) {
1708 Batch bz = mAlarmBatches.get(iz);
1709 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001710 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001711 pw.flush();
1712 Slog.v(TAG, bs.toString());
1713 bs.reset();
1714 }
1715 }
1716
1717 private boolean validateConsistencyLocked() {
1718 if (DEBUG_VALIDATE) {
1719 long lastTime = Long.MIN_VALUE;
1720 final int N = mAlarmBatches.size();
1721 for (int i = 0; i < N; i++) {
1722 Batch b = mAlarmBatches.get(i);
1723 if (b.start >= lastTime) {
1724 // duplicate start times are okay because of standalone batches
1725 lastTime = b.start;
1726 } else {
1727 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001728 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1729 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001730 return false;
1731 }
1732 }
1733 }
1734 return true;
1735 }
1736
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001737 private Batch findFirstWakeupBatchLocked() {
1738 final int N = mAlarmBatches.size();
1739 for (int i = 0; i < N; i++) {
1740 Batch b = mAlarmBatches.get(i);
1741 if (b.hasWakeups()) {
1742 return b;
1743 }
1744 }
1745 return null;
1746 }
1747
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001748 long getNextWakeFromIdleTimeImpl() {
1749 synchronized (mLock) {
1750 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
1751 }
1752 }
1753
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001754 void setDeviceIdleUserWhitelistImpl(int[] appids) {
1755 synchronized (mLock) {
1756 mDeviceIdleUserWhitelist = appids;
1757 }
1758 }
1759
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001760 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001761 synchronized (mLock) {
1762 return mNextAlarmClockForUser.get(userId);
1763 }
1764 }
1765
1766 /**
1767 * Recomputes the next alarm clock for all users.
1768 */
1769 private void updateNextAlarmClockLocked() {
1770 if (!mNextAlarmClockMayChange) {
1771 return;
1772 }
1773 mNextAlarmClockMayChange = false;
1774
Jose Lima235510e2014-08-13 12:50:01 -07001775 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001776 nextForUser.clear();
1777
1778 final int N = mAlarmBatches.size();
1779 for (int i = 0; i < N; i++) {
1780 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
1781 final int M = alarms.size();
1782
1783 for (int j = 0; j < M; j++) {
1784 Alarm a = alarms.get(j);
1785 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001786 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07001787 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001788
1789 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07001790 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001791 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02001792 " for user " + userId);
1793 }
1794
1795 // Alarms and batches are sorted by time, no need to compare times here.
1796 if (nextForUser.get(userId) == null) {
1797 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07001798 } else if (a.alarmClock.equals(current)
1799 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
1800 // same/earlier time and it's the one we cited before, so stick with it
1801 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001802 }
1803 }
1804 }
1805 }
1806
1807 // Update mNextAlarmForUser with new values.
1808 final int NN = nextForUser.size();
1809 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07001810 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001811 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001812 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001813 if (!newAlarm.equals(currentAlarm)) {
1814 updateNextAlarmInfoForUserLocked(userId, newAlarm);
1815 }
1816 }
1817
1818 // Remove users without any alarm clocks scheduled.
1819 final int NNN = mNextAlarmClockForUser.size();
1820 for (int i = NNN - 1; i >= 0; i--) {
1821 int userId = mNextAlarmClockForUser.keyAt(i);
1822 if (nextForUser.get(userId) == null) {
1823 updateNextAlarmInfoForUserLocked(userId, null);
1824 }
1825 }
1826 }
1827
Jose Lima235510e2014-08-13 12:50:01 -07001828 private void updateNextAlarmInfoForUserLocked(int userId,
1829 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001830 if (alarmClock != null) {
1831 if (DEBUG_ALARM_CLOCK) {
1832 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001833 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02001834 }
1835 mNextAlarmClockForUser.put(userId, alarmClock);
1836 } else {
1837 if (DEBUG_ALARM_CLOCK) {
1838 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
1839 }
1840 mNextAlarmClockForUser.remove(userId);
1841 }
1842
1843 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
1844 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1845 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1846 }
1847
1848 /**
1849 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
1850 * for which alarm clocks have changed since the last call to this.
1851 *
1852 * Do not call with a lock held. Only call from mHandler's thread.
1853 *
1854 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
1855 */
1856 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07001857 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001858 pendingUsers.clear();
1859
1860 synchronized (mLock) {
1861 final int N = mPendingSendNextAlarmClockChangedForUser.size();
1862 for (int i = 0; i < N; i++) {
1863 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
1864 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
1865 }
1866 mPendingSendNextAlarmClockChangedForUser.clear();
1867 }
1868
1869 final int N = pendingUsers.size();
1870 for (int i = 0; i < N; i++) {
1871 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001872 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001873 Settings.System.putStringForUser(getContext().getContentResolver(),
1874 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01001875 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02001876 userId);
1877
1878 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
1879 new UserHandle(userId));
1880 }
1881 }
1882
1883 /**
1884 * Formats an alarm like platform/packages/apps/DeskClock used to.
1885 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01001886 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
1887 int userId) {
1888 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02001889 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
1890 return (info == null) ? "" :
1891 DateFormat.format(pattern, info.getTriggerTime()).toString();
1892 }
1893
Adam Lesinski182f73f2013-12-05 16:48:06 -08001894 void rescheduleKernelAlarmsLocked() {
1895 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
1896 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001897 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001898 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001899 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001900 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07001901 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001902 mNextWakeup = firstWakeup.start;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001903 mLastWakeupSet = SystemClock.elapsedRealtime();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001904 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001905 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001906 if (firstBatch != firstWakeup) {
1907 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001908 }
1909 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001910 if (mPendingNonWakeupAlarms.size() > 0) {
1911 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
1912 nextNonWakeup = mNextNonWakeupDeliveryTime;
1913 }
1914 }
Prashant Malani753e9e02015-06-10 17:43:49 -07001915 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001916 mNextNonWakeup = nextNonWakeup;
1917 setLocked(ELAPSED_REALTIME, nextNonWakeup);
1918 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001919 }
1920
Christopher Tate14a7bb02015-10-01 10:24:31 -07001921 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001922 boolean didRemove = false;
1923 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1924 Batch b = mAlarmBatches.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -07001925 didRemove |= b.remove(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001926 if (b.size() == 0) {
1927 mAlarmBatches.remove(i);
1928 }
1929 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001930 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001931 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001932 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1933 mPendingWhileIdleAlarms.remove(i);
1934 }
1935 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001936
1937 if (didRemove) {
1938 if (DEBUG_BATCH) {
1939 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
1940 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001941 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001942 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001943 mPendingIdleUntil = null;
1944 restorePending = true;
1945 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001946 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001947 mNextWakeFromIdle = null;
1948 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001949 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001950 if (restorePending) {
1951 restorePendingWhileIdleAlarmsLocked();
1952 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001953 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001954 }
1955 }
1956
1957 void removeLocked(String packageName) {
1958 boolean didRemove = false;
1959 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1960 Batch b = mAlarmBatches.get(i);
1961 didRemove |= b.remove(packageName);
1962 if (b.size() == 0) {
1963 mAlarmBatches.remove(i);
1964 }
1965 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001966 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001967 final Alarm a = mPendingWhileIdleAlarms.get(i);
1968 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001969 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1970 mPendingWhileIdleAlarms.remove(i);
1971 }
1972 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001973
1974 if (didRemove) {
1975 if (DEBUG_BATCH) {
1976 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1977 }
1978 rebatchAllAlarmsLocked(true);
1979 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001980 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001981 }
1982 }
1983
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001984 void removeForStoppedLocked(int uid) {
1985 boolean didRemove = false;
1986 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1987 Batch b = mAlarmBatches.get(i);
1988 didRemove |= b.removeForStopped(uid);
1989 if (b.size() == 0) {
1990 mAlarmBatches.remove(i);
1991 }
1992 }
1993 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1994 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08001995 if (a.uid == uid) {
1996 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1997 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001998 }
1999 }
2000
2001 if (didRemove) {
2002 if (DEBUG_BATCH) {
2003 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2004 }
2005 rebatchAllAlarmsLocked(true);
2006 rescheduleKernelAlarmsLocked();
2007 updateNextAlarmClockLocked();
2008 }
2009 }
2010
Adam Lesinski182f73f2013-12-05 16:48:06 -08002011 void removeUserLocked(int userHandle) {
2012 boolean didRemove = false;
2013 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2014 Batch b = mAlarmBatches.get(i);
2015 didRemove |= b.remove(userHandle);
2016 if (b.size() == 0) {
2017 mAlarmBatches.remove(i);
2018 }
2019 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002020 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002021 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002022 == userHandle) {
2023 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2024 mPendingWhileIdleAlarms.remove(i);
2025 }
2026 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002027 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
2028 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
2029 mLastAllowWhileIdleDispatch.removeAt(i);
2030 }
2031 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002032
2033 if (didRemove) {
2034 if (DEBUG_BATCH) {
2035 Slog.v(TAG, "remove(user) changed bounds; rebatching");
2036 }
2037 rebatchAllAlarmsLocked(true);
2038 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002039 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002040 }
2041 }
2042
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002043 void interactiveStateChangedLocked(boolean interactive) {
2044 if (mInteractive != interactive) {
2045 mInteractive = interactive;
2046 final long nowELAPSED = SystemClock.elapsedRealtime();
2047 if (interactive) {
2048 if (mPendingNonWakeupAlarms.size() > 0) {
2049 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2050 mTotalDelayTime += thisDelayTime;
2051 if (mMaxDelayTime < thisDelayTime) {
2052 mMaxDelayTime = thisDelayTime;
2053 }
2054 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2055 mPendingNonWakeupAlarms.clear();
2056 }
2057 if (mNonInteractiveStartTime > 0) {
2058 long dur = nowELAPSED - mNonInteractiveStartTime;
2059 if (dur > mNonInteractiveTime) {
2060 mNonInteractiveTime = dur;
2061 }
2062 }
2063 } else {
2064 mNonInteractiveStartTime = nowELAPSED;
2065 }
2066 }
2067 }
2068
Adam Lesinski182f73f2013-12-05 16:48:06 -08002069 boolean lookForPackageLocked(String packageName) {
2070 for (int i = 0; i < mAlarmBatches.size(); i++) {
2071 Batch b = mAlarmBatches.get(i);
2072 if (b.hasPackage(packageName)) {
2073 return true;
2074 }
2075 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002076 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002077 final Alarm a = mPendingWhileIdleAlarms.get(i);
2078 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002079 return true;
2080 }
2081 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002082 return false;
2083 }
2084
2085 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002086 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002087 // The kernel never triggers alarms with negative wakeup times
2088 // so we ensure they are positive.
2089 long alarmSeconds, alarmNanoseconds;
2090 if (when < 0) {
2091 alarmSeconds = 0;
2092 alarmNanoseconds = 0;
2093 } else {
2094 alarmSeconds = when / 1000;
2095 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2096 }
2097
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002098 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002099 } else {
2100 Message msg = Message.obtain();
2101 msg.what = ALARM_EVENT;
2102
2103 mHandler.removeMessages(ALARM_EVENT);
2104 mHandler.sendMessageAtTime(msg, when);
2105 }
2106 }
2107
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002108 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002109 String prefix, String label, long nowRTC, long nowELAPSED, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002110 for (int i=list.size()-1; i>=0; i--) {
2111 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002112 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2113 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002114 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002115 }
2116 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002117
2118 private static final String labelForType(int type) {
2119 switch (type) {
2120 case RTC: return "RTC";
2121 case RTC_WAKEUP : return "RTC_WAKEUP";
2122 case ELAPSED_REALTIME : return "ELAPSED";
2123 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
2124 default:
2125 break;
2126 }
2127 return "--unknown--";
2128 }
2129
2130 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002131 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002132 for (int i=list.size()-1; i>=0; i--) {
2133 Alarm a = list.get(i);
2134 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002135 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2136 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002137 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002138 }
2139 }
2140
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002141 private native long init();
2142 private native void close(long nativeData);
2143 private native void set(long nativeData, int type, long seconds, long nanoseconds);
2144 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08002145 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002146 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002147
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002148 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002149 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002150 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002151 // batches are temporally sorted, so we need only pull from the
2152 // start of the list until we either empty it or hit a batch
2153 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07002154 while (mAlarmBatches.size() > 0) {
2155 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002156 if (batch.start > nowELAPSED) {
2157 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002158 break;
2159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002160
Christopher Tatee0a22b32013-07-11 14:43:13 -07002161 // We will (re)schedule some alarms now; don't let that interfere
2162 // with delivery of this current batch
2163 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002164
Christopher Tatee0a22b32013-07-11 14:43:13 -07002165 final int N = batch.size();
2166 for (int i = 0; i < N; i++) {
2167 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002168
2169 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
2170 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
2171 // schedule such alarms.
2172 long lastTime = mLastAllowWhileIdleDispatch.get(alarm.uid, 0);
2173 long minTime = lastTime + mAllowWhileIdleMinTime;
2174 if (nowELAPSED < minTime) {
2175 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
2176 // alarm went off for this app. Reschedule the alarm to be in the
2177 // correct time period.
2178 alarm.whenElapsed = minTime;
2179 if (alarm.maxWhenElapsed < minTime) {
2180 alarm.maxWhenElapsed = minTime;
2181 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002182 if (RECORD_DEVICE_IDLE_ALARMS) {
2183 IdleDispatchEntry ent = new IdleDispatchEntry();
2184 ent.uid = alarm.uid;
2185 ent.pkg = alarm.operation.getCreatorPackage();
2186 ent.tag = alarm.operation.getTag("");
2187 ent.op = "RESCHEDULE";
2188 ent.elapsedRealtime = nowELAPSED;
2189 ent.argRealtime = lastTime;
2190 mAllowWhileIdleDispatches.add(ent);
2191 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002192 setImplLocked(alarm, true, false);
2193 continue;
2194 }
2195 }
2196
Christopher Tatee0a22b32013-07-11 14:43:13 -07002197 alarm.count = 1;
2198 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002199 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
2200 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002201 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002202 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002203 if (mPendingIdleUntil == alarm) {
2204 mPendingIdleUntil = null;
2205 rebatchAllAlarmsLocked(false);
2206 restorePendingWhileIdleAlarmsLocked();
2207 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002208 if (mNextWakeFromIdle == alarm) {
2209 mNextWakeFromIdle = null;
2210 rebatchAllAlarmsLocked(false);
2211 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002212
2213 // Recurring alarms may have passed several alarm intervals while the
2214 // phone was asleep or off, so pass a trigger count when sending them.
2215 if (alarm.repeatInterval > 0) {
2216 // this adjustment will be zero if we're late by
2217 // less than one full repeat interval
2218 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
2219
2220 // Also schedule its next recurrence
2221 final long delta = alarm.count * alarm.repeatInterval;
2222 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07002223 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07002224 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07002225 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
2226 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08002227 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002228
Christopher Tate864d42e2014-12-02 11:48:53 -08002229 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002230 hasWakeup = true;
2231 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002232
2233 // We removed an alarm clock. Let the caller recompute the next alarm clock.
2234 if (alarm.alarmClock != null) {
2235 mNextAlarmClockMayChange = true;
2236 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07002237 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002238 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002239
Christopher Tate1590f1e2014-10-02 17:27:57 -07002240 // This is a new alarm delivery set; bump the sequence number to indicate that
2241 // all apps' alarm delivery classes should be recalculated.
2242 mCurrentSeq++;
2243 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002244 Collections.sort(triggerList, mAlarmDispatchComparator);
2245
2246 if (localLOGV) {
2247 for (int i=0; i<triggerList.size(); i++) {
2248 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
2249 }
2250 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002251
2252 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002253 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002255 /**
2256 * This Comparator sorts Alarms into increasing time order.
2257 */
2258 public static class IncreasingTimeOrder implements Comparator<Alarm> {
2259 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09002260 long when1 = a1.whenElapsed;
2261 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002262 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002263 return 1;
2264 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002265 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002266 return -1;
2267 }
2268 return 0;
2269 }
2270 }
2271
2272 private static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002273 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002274 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002275 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002276 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002277 public final IAlarmListener listener;
2278 public final String listenerTag;
2279 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002280 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002281 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002282 public final AlarmManager.AlarmClockInfo alarmClock;
2283 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002284 public final int creatorUid;
2285 public final String packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002286 public int count;
2287 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07002288 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002289 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002290 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002291 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07002292 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002293
Christopher Tate3e04b472013-10-21 17:51:31 -07002294 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002295 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
2296 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
2297 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002298 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002299 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002300 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
2301 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002302 when = _when;
2303 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07002304 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002305 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002306 repeatInterval = _interval;
2307 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002308 listener = _rec;
2309 listenerTag = _listenerTag;
2310 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07002311 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002312 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002313 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002314 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002315 packageName = _pkgName;
2316
2317 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002318 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002319
Christopher Tate14a7bb02015-10-01 10:24:31 -07002320 public static String makeTag(PendingIntent pi, String tag, int type) {
2321 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
2322 ? "*walarm*:" : "*alarm*:";
2323 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
2324 }
2325
2326 public WakeupEvent makeWakeupEvent(long nowRTC) {
2327 return new WakeupEvent(nowRTC, creatorUid,
2328 (operation != null)
2329 ? operation.getIntent().getAction()
2330 : ("<listener>:" + listenerTag));
2331 }
2332
2333 // Returns true if either matches
2334 public boolean matches(PendingIntent pi, IAlarmListener rec) {
2335 return (operation != null)
2336 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09002337 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07002338 }
2339
2340 public boolean matches(String packageName) {
2341 return (operation != null)
2342 ? packageName.equals(operation.getTargetPackage())
2343 : packageName.equals(this.packageName);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002344 }
2345
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002346 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002347 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002348 StringBuilder sb = new StringBuilder(128);
2349 sb.append("Alarm{");
2350 sb.append(Integer.toHexString(System.identityHashCode(this)));
2351 sb.append(" type ");
2352 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002353 sb.append(" when ");
2354 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002355 sb.append(" ");
Christopher Tate14a7bb02015-10-01 10:24:31 -07002356 if (operation != null) {
2357 sb.append(operation.getTargetPackage());
2358 } else {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002359 sb.append(packageName);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002360 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002361 sb.append('}');
2362 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002363 }
2364
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002365 public void dump(PrintWriter pw, String prefix, long nowRTC, long nowELAPSED,
2366 SimpleDateFormat sdf) {
2367 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002368 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002369 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002370 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
2371 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002372 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002373 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002374 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002375 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002376 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002377 }
2378 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002379 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002380 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002381 pw.print(" count="); pw.print(count);
2382 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002383 if (alarmClock != null) {
2384 pw.print(prefix); pw.println("Alarm clock:");
2385 pw.print(prefix); pw.print(" triggerTime=");
2386 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
2387 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
2388 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002389 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002390 if (listener != null) {
2391 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
2392 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002393 }
2394 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002395
Christopher Tatee0a22b32013-07-11 14:43:13 -07002396 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
2397 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002398 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
2399 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002400 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07002401 break;
2402 }
2403
Christopher Tatee0a22b32013-07-11 14:43:13 -07002404 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002405 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
2406 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002407 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07002408 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002409 }
2410 }
2411
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002412 long currentNonWakeupFuzzLocked(long nowELAPSED) {
2413 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
2414 if (timeSinceOn < 5*60*1000) {
2415 // If the screen has been off for 5 minutes, only delay by at most two minutes.
2416 return 2*60*1000;
2417 } else if (timeSinceOn < 30*60*1000) {
2418 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
2419 return 15*60*1000;
2420 } else {
2421 // Otherwise, we will delay by at most an hour.
2422 return 60*60*1000;
2423 }
2424 }
2425
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002426 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002427 if (duration < 15*60*1000) {
2428 // If the duration until the time is less than 15 minutes, the maximum fuzz
2429 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002430 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002431 } else if (duration < 90*60*1000) {
2432 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
2433 return 15*60*1000;
2434 } else {
2435 // Otherwise, we will fuzz by at most half an hour.
2436 return 30*60*1000;
2437 }
2438 }
2439
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002440 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
2441 if (mInteractive) {
2442 return false;
2443 }
2444 if (mLastAlarmDeliveryTime <= 0) {
2445 return false;
2446 }
minho.choo649acab2014-12-12 16:13:55 +09002447 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002448 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
2449 // and the next delivery time is in the past, then just deliver them all. This
2450 // avoids bugs where we get stuck in a loop trying to poll for alarms.
2451 return false;
2452 }
2453 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
2454 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
2455 }
2456
2457 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
2458 mLastAlarmDeliveryTime = nowELAPSED;
2459 for (int i=0; i<triggerList.size(); i++) {
2460 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07002461 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002462 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07002463 if (localLOGV) {
2464 Slog.v(TAG, "sending alarm " + alarm);
2465 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07002466 if (RECORD_ALARMS_IN_HISTORY) {
2467 if (alarm.workSource != null && alarm.workSource.size() > 0) {
2468 for (int wi=0; wi<alarm.workSource.size(); wi++) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002469 ActivityManager.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002470 alarm.operation, alarm.workSource.get(wi), alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002471 }
2472 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002473 ActivityManager.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002474 alarm.operation, alarm.uid, alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002475 }
2476 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002477 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002478 } catch (RuntimeException e) {
2479 Slog.w(TAG, "Failure sending alarm.", e);
2480 }
2481 }
2482 }
2483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002484 private class AlarmThread extends Thread
2485 {
2486 public AlarmThread()
2487 {
2488 super("AlarmManager");
2489 }
2490
2491 public void run()
2492 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002493 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 while (true)
2496 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002497 int result = waitForAlarm(mNativeData);
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002498 mLastWakeup = SystemClock.elapsedRealtime();
Dianne Hackborn390517b2013-05-30 15:03:32 -07002499
2500 triggerList.clear();
2501
Dianne Hackbornc3527222015-05-13 14:03:20 -07002502 final long nowRTC = System.currentTimeMillis();
2503 final long nowELAPSED = SystemClock.elapsedRealtime();
2504
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002505 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002506 // The kernel can give us spurious time change notifications due to
2507 // small adjustments it makes internally; we want to filter those out.
2508 final long lastTimeChangeClockTime;
2509 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07002510 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002511 lastTimeChangeClockTime = mLastTimeChangeClockTime;
2512 expectedClockTime = lastTimeChangeClockTime
2513 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07002514 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08002515 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
2516 || nowRTC > (expectedClockTime+1000)) {
2517 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07002518 // let's do it!
2519 if (DEBUG_BATCH) {
2520 Slog.v(TAG, "Time changed notification from kernel; rebatching");
2521 }
2522 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07002523 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07002524 rebatchAllAlarms();
2525 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07002526 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07002527 synchronized (mLock) {
2528 mNumTimeChanged++;
2529 mLastTimeChangeClockTime = nowRTC;
2530 mLastTimeChangeRealtime = nowELAPSED;
2531 }
2532 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
2533 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08002534 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07002535 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
2536 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07002537 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
2538
2539 // The world has changed on us, so we need to re-evaluate alarms
2540 // regardless of whether the kernel has told us one went off.
2541 result |= IS_WAKEUP_MASK;
2542 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002543 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544
Dianne Hackbornc3527222015-05-13 14:03:20 -07002545 if (result != TIME_CHANGED_MASK) {
2546 // If this was anything besides just a time change, then figure what if
2547 // anything to do about alarms.
2548 synchronized (mLock) {
2549 if (localLOGV) Slog.v(
2550 TAG, "Checking for alarms... rtc=" + nowRTC
2551 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07002552
Dianne Hackbornc3527222015-05-13 14:03:20 -07002553 if (WAKEUP_STATS) {
2554 if ((result & IS_WAKEUP_MASK) != 0) {
2555 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
2556 int n = 0;
2557 for (WakeupEvent event : mRecentWakeups) {
2558 if (event.when > newEarliest) break;
2559 n++; // number of now-stale entries at the list head
2560 }
2561 for (int i = 0; i < n; i++) {
2562 mRecentWakeups.remove();
2563 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002564
Dianne Hackbornc3527222015-05-13 14:03:20 -07002565 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002566 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002567 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002568
2569 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2570 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
2571 // if there are no wakeup alarms and the screen is off, we can
2572 // delay what we have so far until the future.
2573 if (mPendingNonWakeupAlarms.size() == 0) {
2574 mStartCurrentDelayTime = nowELAPSED;
2575 mNextNonWakeupDeliveryTime = nowELAPSED
2576 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
2577 }
2578 mPendingNonWakeupAlarms.addAll(triggerList);
2579 mNumDelayedAlarms += triggerList.size();
2580 rescheduleKernelAlarmsLocked();
2581 updateNextAlarmClockLocked();
2582 } else {
2583 // now deliver the alarm intents; if there are pending non-wakeup
2584 // alarms, we need to merge them in to the list. note we don't
2585 // just deliver them first because we generally want non-wakeup
2586 // alarms delivered after wakeup alarms.
2587 rescheduleKernelAlarmsLocked();
2588 updateNextAlarmClockLocked();
2589 if (mPendingNonWakeupAlarms.size() > 0) {
2590 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
2591 triggerList.addAll(mPendingNonWakeupAlarms);
2592 Collections.sort(triggerList, mAlarmDispatchComparator);
2593 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2594 mTotalDelayTime += thisDelayTime;
2595 if (mMaxDelayTime < thisDelayTime) {
2596 mMaxDelayTime = thisDelayTime;
2597 }
2598 mPendingNonWakeupAlarms.clear();
2599 }
2600 deliverAlarmsLocked(triggerList, nowELAPSED);
2601 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002602 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002603
2604 } else {
2605 // Just in case -- even though no wakeup flag was set, make sure
2606 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07002607 synchronized (mLock) {
2608 rescheduleKernelAlarmsLocked();
2609 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002610 }
2611 }
2612 }
2613 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002614
David Christieebe51fc2013-07-26 13:23:29 -07002615 /**
2616 * Attribute blame for a WakeLock.
2617 * @param pi PendingIntent to attribute blame to if ws is null.
2618 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002619 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07002620 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002621 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002622 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07002623 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002624 final boolean unimportant = pi == mTimeTickSender;
2625 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002626 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002627 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002628 } else {
2629 mWakeLock.setHistoryTag(null);
2630 }
2631 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07002632 if (ws != null) {
2633 mWakeLock.setWorkSource(ws);
2634 return;
2635 }
2636
Christopher Tate14a7bb02015-10-01 10:24:31 -07002637 final int uid = (knownUid >= 0)
2638 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002639 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07002640 if (uid >= 0) {
2641 mWakeLock.setWorkSource(new WorkSource(uid));
2642 return;
2643 }
2644 } catch (Exception e) {
2645 }
2646
2647 // Something went wrong; fall back to attributing the lock to the OS
2648 mWakeLock.setWorkSource(null);
2649 }
2650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002651 private class AlarmHandler extends Handler {
2652 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002653 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
2654 public static final int LISTENER_TIMEOUT = 3;
2655 public static final int REPORT_ALARMS_ACTIVE = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002656
2657 public AlarmHandler() {
2658 }
2659
2660 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002661 switch (msg.what) {
2662 case ALARM_EVENT: {
2663 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2664 synchronized (mLock) {
2665 final long nowRTC = System.currentTimeMillis();
2666 final long nowELAPSED = SystemClock.elapsedRealtime();
2667 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2668 updateNextAlarmClockLocked();
2669 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002670
Christopher Tate14a7bb02015-10-01 10:24:31 -07002671 // now trigger the alarms without the lock held
2672 for (int i=0; i<triggerList.size(); i++) {
2673 Alarm alarm = triggerList.get(i);
2674 try {
2675 alarm.operation.send();
2676 } catch (PendingIntent.CanceledException e) {
2677 if (alarm.repeatInterval > 0) {
2678 // This IntentSender is no longer valid, but this
2679 // is a repeating alarm, so toss the hoser.
2680 removeImpl(alarm.operation);
2681 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 }
2683 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002684 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002685 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002686
2687 case SEND_NEXT_ALARM_CLOCK_CHANGED:
2688 sendNextAlarmClockChanged();
2689 break;
2690
2691 case LISTENER_TIMEOUT:
2692 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
2693 break;
2694
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002695 case REPORT_ALARMS_ACTIVE:
2696 if (mLocalDeviceIdleController != null) {
2697 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
2698 }
2699 break;
2700
Christopher Tate14a7bb02015-10-01 10:24:31 -07002701 default:
2702 // nope, just ignore it
2703 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002704 }
2705 }
2706 }
2707
2708 class ClockReceiver extends BroadcastReceiver {
2709 public ClockReceiver() {
2710 IntentFilter filter = new IntentFilter();
2711 filter.addAction(Intent.ACTION_TIME_TICK);
2712 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002713 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002714 }
2715
2716 @Override
2717 public void onReceive(Context context, Intent intent) {
2718 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07002719 if (DEBUG_BATCH) {
2720 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
2721 }
2722 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002723 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
2724 // Since the kernel does not keep track of DST, we need to
2725 // reset the TZ information at the beginning of each day
2726 // based off of the current Zone gmt offset + userspace tracked
2727 // daylight savings information.
2728 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02002729 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002730 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07002731 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002732 }
2733 }
2734
2735 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07002736 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09002737 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07002738
2739 // Schedule this event for the amount of time that it would take to get to
2740 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09002741 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07002742
David Christieebe51fc2013-07-26 13:23:29 -07002743 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002744 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002745 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
2746 null, Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002747 }
Christopher Tate385e4982013-07-23 18:22:29 -07002748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002749 public void scheduleDateChangedEvent() {
2750 Calendar calendar = Calendar.getInstance();
2751 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07002752 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002753 calendar.set(Calendar.MINUTE, 0);
2754 calendar.set(Calendar.SECOND, 0);
2755 calendar.set(Calendar.MILLISECOND, 0);
2756 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07002757
2758 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002759 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
2760 AlarmManager.FLAG_STANDALONE, workSource, null,
2761 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002762 }
2763 }
2764
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002765 class InteractiveStateReceiver extends BroadcastReceiver {
2766 public InteractiveStateReceiver() {
2767 IntentFilter filter = new IntentFilter();
2768 filter.addAction(Intent.ACTION_SCREEN_OFF);
2769 filter.addAction(Intent.ACTION_SCREEN_ON);
2770 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
2771 getContext().registerReceiver(this, filter);
2772 }
2773
2774 @Override
2775 public void onReceive(Context context, Intent intent) {
2776 synchronized (mLock) {
2777 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
2778 }
2779 }
2780 }
2781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002782 class UninstallReceiver extends BroadcastReceiver {
2783 public UninstallReceiver() {
2784 IntentFilter filter = new IntentFilter();
2785 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2786 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002787 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002788 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08002789 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002790 // Register for events related to sdcard installation.
2791 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08002792 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002793 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002794 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002795 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796 }
2797
2798 @Override
2799 public void onReceive(Context context, Intent intent) {
2800 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002801 String action = intent.getAction();
2802 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002803 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
2804 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
2805 for (String packageName : pkgList) {
2806 if (lookForPackageLocked(packageName)) {
2807 setResultCode(Activity.RESULT_OK);
2808 return;
2809 }
2810 }
2811 return;
2812 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002813 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002814 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
2815 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
2816 if (userHandle >= 0) {
2817 removeUserLocked(userHandle);
2818 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002819 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
2820 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
2821 if (uid >= 0) {
2822 mLastAllowWhileIdleDispatch.delete(uid);
2823 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002824 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08002825 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
2826 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
2827 // This package is being updated; don't kill its alarms.
2828 return;
2829 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002830 Uri data = intent.getData();
2831 if (data != null) {
2832 String pkg = data.getSchemeSpecificPart();
2833 if (pkg != null) {
2834 pkgList = new String[]{pkg};
2835 }
2836 }
2837 }
2838 if (pkgList != null && (pkgList.length > 0)) {
2839 for (String pkg : pkgList) {
2840 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07002841 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002842 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
2843 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
2844 if (uidStats.remove(pkg) != null) {
2845 if (uidStats.size() <= 0) {
2846 mBroadcastStats.removeAt(i);
2847 }
2848 }
2849 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002850 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002851 }
2852 }
2853 }
2854 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002855
2856 final class UidObserver extends IUidObserver.Stub {
Sudheer Shanka80255802017-03-04 14:48:53 -08002857 @Override public void onUidStateChanged(int uid, int procState,
2858 long procStateSeq) throws RemoteException {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002859 }
2860
Dianne Hackborne07641d2016-11-09 15:07:23 -08002861 @Override public void onUidGone(int uid, boolean disabled) throws RemoteException {
2862 if (disabled) {
2863 synchronized (mLock) {
2864 removeForStoppedLocked(uid);
2865 }
2866 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002867 }
2868
2869 @Override public void onUidActive(int uid) throws RemoteException {
2870 }
2871
Dianne Hackborne07641d2016-11-09 15:07:23 -08002872 @Override public void onUidIdle(int uid, boolean disabled) throws RemoteException {
2873 if (disabled) {
2874 synchronized (mLock) {
2875 removeForStoppedLocked(uid);
2876 }
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08002877 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002878 }
2879 };
2880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002881 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002882 String pkg = pi.getCreatorPackage();
2883 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002884 return getStatsLocked(uid, pkg);
2885 }
2886
2887 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002888 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
2889 if (uidStats == null) {
2890 uidStats = new ArrayMap<String, BroadcastStats>();
2891 mBroadcastStats.put(uid, uidStats);
2892 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002893 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002894 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002895 bs = new BroadcastStats(uid, pkgName);
2896 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897 }
2898 return bs;
2899 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002900
Christopher Tate14a7bb02015-10-01 10:24:31 -07002901 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
2902 private InFlight removeLocked(PendingIntent pi, Intent intent) {
2903 for (int i = 0; i < mInFlight.size(); i++) {
2904 if (mInFlight.get(i).mPendingIntent == pi) {
2905 return mInFlight.remove(i);
2906 }
2907 }
2908 mLog.w("No in-flight alarm for " + pi + " " + intent);
2909 return null;
2910 }
2911
2912 private InFlight removeLocked(IBinder listener) {
2913 for (int i = 0; i < mInFlight.size(); i++) {
2914 if (mInFlight.get(i).mListener == listener) {
2915 return mInFlight.remove(i);
2916 }
2917 }
2918 mLog.w("No in-flight alarm for listener " + listener);
2919 return null;
2920 }
2921
2922 private void updateStatsLocked(InFlight inflight) {
2923 final long nowELAPSED = SystemClock.elapsedRealtime();
2924 BroadcastStats bs = inflight.mBroadcastStats;
2925 bs.nesting--;
2926 if (bs.nesting <= 0) {
2927 bs.nesting = 0;
2928 bs.aggregateTime += nowELAPSED - bs.startTime;
2929 }
2930 FilterStats fs = inflight.mFilterStats;
2931 fs.nesting--;
2932 if (fs.nesting <= 0) {
2933 fs.nesting = 0;
2934 fs.aggregateTime += nowELAPSED - fs.startTime;
2935 }
2936 if (RECORD_ALARMS_IN_HISTORY) {
2937 if (inflight.mWorkSource != null && inflight.mWorkSource.size() > 0) {
2938 for (int wi=0; wi<inflight.mWorkSource.size(); wi++) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002939 ActivityManager.noteAlarmFinish(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002940 inflight.mPendingIntent, inflight.mWorkSource.get(wi), inflight.mTag);
2941 }
2942 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002943 ActivityManager.noteAlarmFinish(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002944 inflight.mPendingIntent, inflight.mUid, inflight.mTag);
2945 }
2946 }
2947 }
2948
2949 private void updateTrackingLocked(InFlight inflight) {
2950 if (inflight != null) {
2951 updateStatsLocked(inflight);
2952 }
2953 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08002954 if (DEBUG_WAKELOCK) {
2955 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
2956 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002957 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002958 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002959 mWakeLock.release();
2960 if (mInFlight.size() > 0) {
2961 mLog.w("Finished all dispatches with " + mInFlight.size()
2962 + " remaining inflights");
2963 for (int i=0; i<mInFlight.size(); i++) {
2964 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
2965 }
2966 mInFlight.clear();
2967 }
2968 } else {
2969 // the next of our alarms is now in flight. reattribute the wakelock.
2970 if (mInFlight.size() > 0) {
2971 InFlight inFlight = mInFlight.get(0);
2972 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
2973 inFlight.mAlarmType, inFlight.mTag, -1, false);
2974 } else {
2975 // should never happen
2976 mLog.w("Alarm wakelock still held but sent queue empty");
2977 mWakeLock.setWorkSource(null);
2978 }
2979 }
2980 }
2981
2982 /**
2983 * Callback that arrives when a direct-call alarm reports that delivery has finished
2984 */
2985 @Override
2986 public void alarmComplete(IBinder who) {
2987 if (who == null) {
2988 Slog.w(TAG, "Invalid alarmComplete: uid=" + Binder.getCallingUid()
2989 + " pid=" + Binder.getCallingPid());
2990 return;
2991 }
2992
2993 final long ident = Binder.clearCallingIdentity();
2994 try {
2995 synchronized (mLock) {
2996 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
2997 InFlight inflight = removeLocked(who);
2998 if (inflight != null) {
2999 if (DEBUG_LISTENER_CALLBACK) {
3000 Slog.i(TAG, "alarmComplete() from " + who);
3001 }
3002 updateTrackingLocked(inflight);
3003 } else {
3004 // Delivery timed out, and the timeout handling already took care of
3005 // updating our tracking here, so we needn't do anything further.
3006 if (DEBUG_LISTENER_CALLBACK) {
3007 Slog.i(TAG, "Late alarmComplete() from " + who);
3008 }
3009 }
3010 }
3011 } finally {
3012 Binder.restoreCallingIdentity(ident);
3013 }
3014 }
3015
3016 /**
3017 * Callback that arrives when a PendingIntent alarm has finished delivery
3018 */
3019 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003020 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
3021 String resultData, Bundle resultExtras) {
3022 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003023 updateTrackingLocked(removeLocked(pi, intent));
3024 }
3025 }
3026
3027 /**
3028 * Timeout of a direct-call alarm delivery
3029 */
3030 public void alarmTimedOut(IBinder who) {
3031 synchronized (mLock) {
3032 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08003033 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003034 // TODO: implement ANR policy for the target
3035 if (DEBUG_LISTENER_CALLBACK) {
3036 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003037 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003038 updateTrackingLocked(inflight);
Dianne Hackborn81038902012-11-26 17:04:09 -08003039 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003040 if (DEBUG_LISTENER_CALLBACK) {
3041 Slog.i(TAG, "Spurious timeout of listener " + who);
3042 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003043 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003044 }
3045 }
3046
3047 /**
3048 * Deliver an alarm and set up the post-delivery handling appropriately
3049 */
3050 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
3051 if (alarm.operation != null) {
3052 // PendingIntent alarm
3053 try {
3054 alarm.operation.send(getContext(), 0,
3055 mBackgroundIntent.putExtra(
3056 Intent.EXTRA_ALARM_COUNT, alarm.count),
3057 mDeliveryTracker, mHandler, null,
3058 allowWhileIdle ? mIdleOptions : null);
3059 } catch (PendingIntent.CanceledException e) {
3060 if (alarm.repeatInterval > 0) {
3061 // This IntentSender is no longer valid, but this
3062 // is a repeating alarm, so toss it
3063 removeImpl(alarm.operation);
3064 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003065 // No actual delivery was possible, so the delivery tracker's
3066 // 'finished' callback won't be invoked. We also don't need
3067 // to do any wakelock or stats tracking, so we have nothing
3068 // left to do here but go on to the next thing.
3069 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003070 }
3071 } else {
3072 // Direct listener callback alarm
3073 try {
3074 if (DEBUG_LISTENER_CALLBACK) {
3075 Slog.v(TAG, "Alarm to uid=" + alarm.uid
3076 + " listener=" + alarm.listener.asBinder());
3077 }
3078 alarm.listener.doAlarm(this);
3079 mHandler.sendMessageDelayed(
3080 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
3081 alarm.listener.asBinder()),
3082 mConstants.LISTENER_TIMEOUT);
3083 } catch (Exception e) {
3084 if (DEBUG_LISTENER_CALLBACK) {
3085 Slog.i(TAG, "Alarm undeliverable to listener "
3086 + alarm.listener.asBinder(), e);
3087 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003088 // As in the PendingIntent.CanceledException case, delivery of the
3089 // alarm was not possible, so we have no wakelock or timeout or
3090 // stats management to do. It threw before we posted the delayed
3091 // timeout message, so we're done here.
3092 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003093 }
3094 }
3095
3096 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08003097 if (DEBUG_WAKELOCK) {
3098 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
3099 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003100 if (mBroadcastRefCount == 0) {
3101 setWakelockWorkSource(alarm.operation, alarm.workSource,
3102 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
3103 true);
3104 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003105 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003106 }
3107 final InFlight inflight = new InFlight(AlarmManagerService.this,
3108 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
3109 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
3110 mInFlight.add(inflight);
3111 mBroadcastRefCount++;
3112
3113 if (allowWhileIdle) {
3114 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
3115 mLastAllowWhileIdleDispatch.put(alarm.uid, nowELAPSED);
3116 if (RECORD_DEVICE_IDLE_ALARMS) {
3117 IdleDispatchEntry ent = new IdleDispatchEntry();
3118 ent.uid = alarm.uid;
3119 ent.pkg = alarm.packageName;
3120 ent.tag = alarm.statsTag;
3121 ent.op = "DELIVER";
3122 ent.elapsedRealtime = nowELAPSED;
3123 mAllowWhileIdleDispatches.add(ent);
3124 }
3125 }
3126
3127 final BroadcastStats bs = inflight.mBroadcastStats;
3128 bs.count++;
3129 if (bs.nesting == 0) {
3130 bs.nesting = 1;
3131 bs.startTime = nowELAPSED;
3132 } else {
3133 bs.nesting++;
3134 }
3135 final FilterStats fs = inflight.mFilterStats;
3136 fs.count++;
3137 if (fs.nesting == 0) {
3138 fs.nesting = 1;
3139 fs.startTime = nowELAPSED;
3140 } else {
3141 fs.nesting++;
3142 }
3143 if (alarm.type == ELAPSED_REALTIME_WAKEUP
3144 || alarm.type == RTC_WAKEUP) {
3145 bs.numWakeup++;
3146 fs.numWakeup++;
3147 if (alarm.workSource != null && alarm.workSource.size() > 0) {
3148 for (int wi=0; wi<alarm.workSource.size(); wi++) {
Christopher Tate0029f572016-06-14 10:16:28 -07003149 final String wsName = alarm.workSource.getName(wi);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003150 ActivityManager.noteWakeupAlarm(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003151 alarm.operation, alarm.workSource.get(wi),
Christopher Tate0029f572016-06-14 10:16:28 -07003152 (wsName != null) ? wsName : alarm.packageName,
3153 alarm.statsTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08003154 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003155 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003156 ActivityManager.noteWakeupAlarm(
Joe Onorato78bcdf92016-05-09 10:10:29 -07003157 alarm.operation, alarm.uid, alarm.packageName, alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003158 }
3159 }
3160 }
3161 }
3162}