blob: 8b32c16acb42c8894a496f7f9300e11302a2f7f1 [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;
39import android.os.Handler;
Adam Lesinski182f73f2013-12-05 16:48:06 -080040import android.os.IBinder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.os.Message;
42import android.os.PowerManager;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070043import android.os.Process;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070044import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.os.SystemClock;
46import android.os.SystemProperties;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070047import android.os.UserHandle;
Christopher Tatec4a07d12012-04-06 14:19:13 -070048import android.os.WorkSource;
Adrian Roosc42a1e12014-07-07 23:35:53 +020049import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.text.TextUtils;
Adrian Roosc42a1e12014-07-07 23:35:53 +020051import android.text.format.DateFormat;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080052import android.util.ArrayMap;
Dianne Hackborna750a632015-06-16 17:18:23 -070053import android.util.KeyValueListParser;
Adrian Roosc42a1e12014-07-07 23:35:53 +020054import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080055import android.util.Slog;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080056import android.util.SparseArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +020057import android.util.SparseBooleanArray;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -070058import android.util.SparseLongArray;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070059import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060
Christopher Tate4cb338d2013-07-26 13:11:31 -070061import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import java.io.FileDescriptor;
63import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070064import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -080066import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import java.util.Calendar;
68import java.util.Collections;
69import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -050070import java.util.Date;
Christopher Tate1590f1e2014-10-02 17:27:57 -070071import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -070072import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +020073import java.util.Locale;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070074import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import java.util.TimeZone;
John Spurlock604a5ee2015-06-01 12:27:22 -040076import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077
Christopher Tatee0a22b32013-07-11 14:43:13 -070078import static android.app.AlarmManager.RTC_WAKEUP;
79import static android.app.AlarmManager.RTC;
80import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
81import static android.app.AlarmManager.ELAPSED_REALTIME;
82
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060083import com.android.internal.util.DumpUtils;
Dianne Hackborn81038902012-11-26 17:04:09 -080084import com.android.internal.util.LocalLog;
85
Adam Lesinski182f73f2013-12-05 16:48:06 -080086class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -070087 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
88 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -080089 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -070090 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -080091 static final int TIME_CHANGED_MASK = 1 << 16;
92 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -080093
Christopher Tatee0a22b32013-07-11 14:43:13 -070094 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -080095 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -080096
Adam Lesinski182f73f2013-12-05 16:48:06 -080097 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -080098 static final boolean localLOGV = false;
99 static final boolean DEBUG_BATCH = localLOGV || false;
100 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200101 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700102 static final boolean DEBUG_LISTENER_CALLBACK = localLOGV || false;
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800103 static final boolean DEBUG_WAKELOCK = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700104 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700105 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800106 static final int ALARM_EVENT = 1;
107 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200108
Christopher Tate14a7bb02015-10-01 10:24:31 -0700109 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800111 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112
Adam Lesinski182f73f2013-12-05 16:48:06 -0800113 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700114
Christopher Tate24cd46f2016-02-02 14:28:01 -0800115 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT =
116 new Intent(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED)
117 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Adrian Roosc42a1e12014-07-07 23:35:53 +0200118
Adam Lesinski182f73f2013-12-05 16:48:06 -0800119 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800120
Christopher Tate14a7bb02015-10-01 10:24:31 -0700121 AppOpsManager mAppOps;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800122 DeviceIdleController.LocalService mLocalDeviceIdleController;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700123
Adam Lesinski182f73f2013-12-05 16:48:06 -0800124 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800125
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800126 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800127 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700128 private long mNextNonWakeup;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -0700129 private long mLastWakeupSet;
130 private long mLastWakeup;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800131 int mBroadcastRefCount = 0;
132 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700133 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700134 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
135 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800136 final AlarmHandler mHandler = new AlarmHandler();
137 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700138 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700140 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800141 PendingIntent mTimeTickSender;
142 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700143 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700144 boolean mInteractive = true;
145 long mNonInteractiveStartTime;
146 long mNonInteractiveTime;
147 long mLastAlarmDeliveryTime;
148 long mStartCurrentDelayTime;
149 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700150 long mLastTimeChangeClockTime;
151 long mLastTimeChangeRealtime;
Dianne Hackborna750a632015-06-16 17:18:23 -0700152 long mAllowWhileIdleMinTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700153 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800154
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700155 /**
Dianne Hackborn262ae5c2016-02-10 16:28:29 -0800156 * The current set of user whitelisted apps for device idle mode, meaning these are allowed
157 * to freely schedule alarms.
158 */
159 int[] mDeviceIdleUserWhitelist = new int[0];
160
161 /**
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700162 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
163 * used to determine the earliest we can dispatch the next such alarm.
164 */
165 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
166
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700167 final static class IdleDispatchEntry {
168 int uid;
169 String pkg;
170 String tag;
171 String op;
172 long elapsedRealtime;
173 long argRealtime;
174 }
175 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
176
Dianne Hackborna750a632015-06-16 17:18:23 -0700177 /**
178 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
179 */
180 Bundle mIdleOptions;
181
Jose Lima235510e2014-08-13 12:50:01 -0700182 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
183 new SparseArray<>();
184 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
185 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200186 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
187 new SparseBooleanArray();
188 private boolean mNextAlarmClockMayChange;
189
190 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700191 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
192 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200193
Dianne Hackborna750a632015-06-16 17:18:23 -0700194 /**
195 * All times are in milliseconds. These constants are kept synchronized with the system
196 * global Settings. Any access to this class or its fields should be done while
197 * holding the AlarmManagerService.mLock lock.
198 */
199 private final class Constants extends ContentObserver {
200 // Key names stored in the settings value.
201 private static final String KEY_MIN_FUTURITY = "min_futurity";
202 private static final String KEY_MIN_INTERVAL = "min_interval";
203 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
204 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
205 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
206 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700207 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Dianne Hackborna750a632015-06-16 17:18:23 -0700208
209 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
210 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tateaa244da2015-08-27 15:57:57 -0700211 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700212 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700213 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
214
Christopher Tate14a7bb02015-10-01 10:24:31 -0700215 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
216
Dianne Hackborna750a632015-06-16 17:18:23 -0700217 // Minimum futurity of a new alarm
218 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
219
220 // Minimum alarm recurrence interval
221 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
222
223 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
224 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
225
226 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
227 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
228
229 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
230 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
231 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
232
Christopher Tate14a7bb02015-10-01 10:24:31 -0700233 // Direct alarm listener callback timeout
234 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
235
Dianne Hackborna750a632015-06-16 17:18:23 -0700236 private ContentResolver mResolver;
237 private final KeyValueListParser mParser = new KeyValueListParser(',');
238 private long mLastAllowWhileIdleWhitelistDuration = -1;
239
240 public Constants(Handler handler) {
241 super(handler);
242 updateAllowWhileIdleMinTimeLocked();
243 updateAllowWhileIdleWhitelistDurationLocked();
244 }
245
246 public void start(ContentResolver resolver) {
247 mResolver = resolver;
248 mResolver.registerContentObserver(Settings.Global.getUriFor(
249 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
250 updateConstants();
251 }
252
253 public void updateAllowWhileIdleMinTimeLocked() {
254 mAllowWhileIdleMinTime = mPendingIdleUntil != null
255 ? ALLOW_WHILE_IDLE_LONG_TIME : ALLOW_WHILE_IDLE_SHORT_TIME;
256 }
257
258 public void updateAllowWhileIdleWhitelistDurationLocked() {
259 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
260 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
261 BroadcastOptions opts = BroadcastOptions.makeBasic();
262 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
263 mIdleOptions = opts.toBundle();
264 }
265 }
266
267 @Override
268 public void onChange(boolean selfChange, Uri uri) {
269 updateConstants();
270 }
271
272 private void updateConstants() {
273 synchronized (mLock) {
274 try {
275 mParser.setString(Settings.Global.getString(mResolver,
276 Settings.Global.ALARM_MANAGER_CONSTANTS));
277 } catch (IllegalArgumentException e) {
278 // Failed to parse the settings string, log this and move on
279 // with defaults.
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800280 Slog.e(TAG, "Bad alarm manager settings", e);
Dianne Hackborna750a632015-06-16 17:18:23 -0700281 }
282
283 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
284 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
285 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
286 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
287 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
288 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
289 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
290 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
291 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700292 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
293 DEFAULT_LISTENER_TIMEOUT);
Dianne Hackborna750a632015-06-16 17:18:23 -0700294
295 updateAllowWhileIdleMinTimeLocked();
296 updateAllowWhileIdleWhitelistDurationLocked();
297 }
298 }
299
300 void dump(PrintWriter pw) {
301 pw.println(" Settings:");
302
303 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
304 TimeUtils.formatDuration(MIN_FUTURITY, pw);
305 pw.println();
306
307 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
308 TimeUtils.formatDuration(MIN_INTERVAL, pw);
309 pw.println();
310
Christopher Tate14a7bb02015-10-01 10:24:31 -0700311 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
312 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
313 pw.println();
314
Dianne Hackborna750a632015-06-16 17:18:23 -0700315 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
316 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
317 pw.println();
318
319 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
320 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
321 pw.println();
322
323 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
324 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
325 pw.println();
326 }
327 }
328
329 final Constants mConstants;
330
Christopher Tate1590f1e2014-10-02 17:27:57 -0700331 // Alarm delivery ordering bookkeeping
332 static final int PRIO_TICK = 0;
333 static final int PRIO_WAKEUP = 1;
334 static final int PRIO_NORMAL = 2;
335
Dianne Hackborna750a632015-06-16 17:18:23 -0700336 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700337 int seq;
338 int priority;
339
340 PriorityClass() {
341 seq = mCurrentSeq - 1;
342 priority = PRIO_NORMAL;
343 }
344 }
345
Dianne Hackborna750a632015-06-16 17:18:23 -0700346 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700347 int mCurrentSeq = 0;
348
Dianne Hackborna750a632015-06-16 17:18:23 -0700349 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700350 public long when;
351 public int uid;
352 public String action;
353
354 public WakeupEvent(long theTime, int theUid, String theAction) {
355 when = theTime;
356 uid = theUid;
357 action = theAction;
358 }
359 }
360
Adam Lesinski182f73f2013-12-05 16:48:06 -0800361 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
362 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700363
Adrian Roosc42a1e12014-07-07 23:35:53 +0200364 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700365 long start; // These endpoints are always in ELAPSED
366 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700367 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700368
369 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
370
371 Batch() {
372 start = 0;
373 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700374 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700375 }
376
377 Batch(Alarm seed) {
378 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700379 end = seed.maxWhenElapsed;
380 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700381 alarms.add(seed);
382 }
383
384 int size() {
385 return alarms.size();
386 }
387
388 Alarm get(int index) {
389 return alarms.get(index);
390 }
391
392 boolean canHold(long whenElapsed, long maxWhen) {
393 return (end >= whenElapsed) && (start <= maxWhen);
394 }
395
396 boolean add(Alarm alarm) {
397 boolean newStart = false;
398 // narrows the batch if necessary; presumes that canHold(alarm) is true
399 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
400 if (index < 0) {
401 index = 0 - index - 1;
402 }
403 alarms.add(index, alarm);
404 if (DEBUG_BATCH) {
405 Slog.v(TAG, "Adding " + alarm + " to " + this);
406 }
407 if (alarm.whenElapsed > start) {
408 start = alarm.whenElapsed;
409 newStart = true;
410 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700411 if (alarm.maxWhenElapsed < end) {
412 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700413 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700414 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700415
416 if (DEBUG_BATCH) {
417 Slog.v(TAG, " => now " + this);
418 }
419 return newStart;
420 }
421
Christopher Tate14a7bb02015-10-01 10:24:31 -0700422 boolean remove(final PendingIntent operation, final IAlarmListener listener) {
423 if (operation == null && listener == null) {
424 if (localLOGV) {
425 Slog.w(TAG, "requested remove() of null operation",
426 new RuntimeException("here"));
427 }
428 return false;
429 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700430 boolean didRemove = false;
431 long newStart = 0; // recalculate endpoints as we go
432 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700433 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700434 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700435 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700436 if (alarm.matches(operation, listener)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700437 alarms.remove(i);
438 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200439 if (alarm.alarmClock != null) {
440 mNextAlarmClockMayChange = true;
441 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700442 } else {
443 if (alarm.whenElapsed > newStart) {
444 newStart = alarm.whenElapsed;
445 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700446 if (alarm.maxWhenElapsed < newEnd) {
447 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700448 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700449 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700450 i++;
451 }
452 }
453 if (didRemove) {
454 // commit the new batch bounds
455 start = newStart;
456 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700457 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700458 }
459 return didRemove;
460 }
461
462 boolean remove(final String packageName) {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700463 if (packageName == null) {
464 if (localLOGV) {
465 Slog.w(TAG, "requested remove() of null packageName",
466 new RuntimeException("here"));
467 }
468 return false;
469 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700470 boolean didRemove = false;
471 long newStart = 0; // recalculate endpoints as we go
472 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700473 int newFlags = 0;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700474 for (int i = alarms.size()-1; i >= 0; i--) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700475 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700476 if (alarm.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700477 alarms.remove(i);
478 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200479 if (alarm.alarmClock != null) {
480 mNextAlarmClockMayChange = true;
481 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700482 } else {
483 if (alarm.whenElapsed > newStart) {
484 newStart = alarm.whenElapsed;
485 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700486 if (alarm.maxWhenElapsed < newEnd) {
487 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700488 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700489 newFlags |= alarm.flags;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700490 }
491 }
492 if (didRemove) {
493 // commit the new batch bounds
494 start = newStart;
495 end = newEnd;
496 flags = newFlags;
497 }
498 return didRemove;
499 }
500
501 boolean removeForStopped(final int uid) {
502 boolean didRemove = false;
503 long newStart = 0; // recalculate endpoints as we go
504 long newEnd = Long.MAX_VALUE;
505 int newFlags = 0;
506 for (int i = alarms.size()-1; i >= 0; i--) {
507 Alarm alarm = alarms.get(i);
508 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800509 if (alarm.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
510 uid, alarm.packageName)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700511 alarms.remove(i);
512 didRemove = true;
513 if (alarm.alarmClock != null) {
514 mNextAlarmClockMayChange = true;
515 }
516 } else {
517 if (alarm.whenElapsed > newStart) {
518 newStart = alarm.whenElapsed;
519 }
520 if (alarm.maxWhenElapsed < newEnd) {
521 newEnd = alarm.maxWhenElapsed;
522 }
523 newFlags |= alarm.flags;
524 }
525 } catch (RemoteException e) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700526 }
527 }
528 if (didRemove) {
529 // commit the new batch bounds
530 start = newStart;
531 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700532 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700533 }
534 return didRemove;
535 }
536
537 boolean remove(final int userHandle) {
538 boolean didRemove = false;
539 long newStart = 0; // recalculate endpoints as we go
540 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700541 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700542 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700543 if (UserHandle.getUserId(alarm.creatorUid) == userHandle) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700544 alarms.remove(i);
545 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200546 if (alarm.alarmClock != null) {
547 mNextAlarmClockMayChange = true;
548 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700549 } else {
550 if (alarm.whenElapsed > newStart) {
551 newStart = alarm.whenElapsed;
552 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700553 if (alarm.maxWhenElapsed < newEnd) {
554 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700555 }
556 i++;
557 }
558 }
559 if (didRemove) {
560 // commit the new batch bounds
561 start = newStart;
562 end = newEnd;
563 }
564 return didRemove;
565 }
566
567 boolean hasPackage(final String packageName) {
568 final int N = alarms.size();
569 for (int i = 0; i < N; i++) {
570 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700571 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700572 return true;
573 }
574 }
575 return false;
576 }
577
578 boolean hasWakeups() {
579 final int N = alarms.size();
580 for (int i = 0; i < N; i++) {
581 Alarm a = alarms.get(i);
582 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
583 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
584 return true;
585 }
586 }
587 return false;
588 }
589
590 @Override
591 public String toString() {
592 StringBuilder b = new StringBuilder(40);
593 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
594 b.append(" num="); b.append(size());
595 b.append(" start="); b.append(start);
596 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700597 if (flags != 0) {
598 b.append(" flgs=0x");
599 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700600 }
601 b.append('}');
602 return b.toString();
603 }
604 }
605
606 static class BatchTimeOrder implements Comparator<Batch> {
607 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800608 long when1 = b1.start;
609 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800610 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700611 return 1;
612 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800613 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700614 return -1;
615 }
616 return 0;
617 }
618 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800619
620 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
621 @Override
622 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700623 // priority class trumps everything. TICK < WAKEUP < NORMAL
624 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
625 return -1;
626 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
627 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800628 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700629
630 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800631 if (lhs.whenElapsed < rhs.whenElapsed) {
632 return -1;
633 } else if (lhs.whenElapsed > rhs.whenElapsed) {
634 return 1;
635 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700636
637 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800638 return 0;
639 }
640 };
641
Christopher Tate1590f1e2014-10-02 17:27:57 -0700642 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
643 final int N = alarms.size();
644 for (int i = 0; i < N; i++) {
645 Alarm a = alarms.get(i);
646
647 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700648 if (a.operation != null
649 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700650 alarmPrio = PRIO_TICK;
651 } else if (a.wakeup) {
652 alarmPrio = PRIO_WAKEUP;
653 } else {
654 alarmPrio = PRIO_NORMAL;
655 }
656
657 PriorityClass packagePrio = a.priorityClass;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700658 String alarmPackage = (a.operation != null)
659 ? a.operation.getCreatorPackage()
660 : a.packageName;
661 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700662 if (packagePrio == null) {
663 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700664 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700665 }
666 a.priorityClass = packagePrio;
667
668 if (packagePrio.seq != mCurrentSeq) {
669 // first alarm we've seen in the current delivery generation from this package
670 packagePrio.priority = alarmPrio;
671 packagePrio.seq = mCurrentSeq;
672 } else {
673 // Multiple alarms from this package being delivered in this generation;
674 // bump the package's delivery class if it's warranted.
675 // TICK < WAKEUP < NORMAL
676 if (alarmPrio < packagePrio.priority) {
677 packagePrio.priority = alarmPrio;
678 }
679 }
680 }
681 }
682
Christopher Tatee0a22b32013-07-11 14:43:13 -0700683 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800684 static final long MIN_FUZZABLE_INTERVAL = 10000;
685 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700686 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
687
688 // set to null if in idle mode; while in this mode, any alarms we don't want
689 // to run during this time are placed in mPendingWhileIdleAlarms
690 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700691 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700692 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700693
Jeff Brownb880d882014-02-10 19:47:07 -0800694 public AlarmManagerService(Context context) {
695 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700696 mConstants = new Constants(mHandler);
Jeff Brownb880d882014-02-10 19:47:07 -0800697 }
698
Christopher Tatee0a22b32013-07-11 14:43:13 -0700699 static long convertToElapsed(long when, int type) {
700 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
701 if (isRtc) {
702 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
703 }
704 return when;
705 }
706
707 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
708 // calculate the end of our nominal delivery window for the alarm.
709 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
710 // Current heuristic: batchable window is 75% of either the recurrence interval
711 // [for a periodic alarm] or of the time from now to the desired delivery time,
712 // with a minimum delay/interval of 10 seconds, under which we will simply not
713 // defer the alarm.
714 long futurity = (interval == 0)
715 ? (triggerAtTime - now)
716 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700717 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700718 futurity = 0;
719 }
720 return triggerAtTime + (long)(.75 * futurity);
721 }
722
723 // returns true if the batch was added at the head
724 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
725 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
726 if (index < 0) {
727 index = 0 - index - 1;
728 }
729 list.add(index, newBatch);
730 return (index == 0);
731 }
732
Christopher Tate385e4982013-07-23 18:22:29 -0700733 // Return the index of the matching batch, or -1 if none found.
734 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700735 final int N = mAlarmBatches.size();
736 for (int i = 0; i < N; i++) {
737 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700738 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700739 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700740 }
741 }
Christopher Tate385e4982013-07-23 18:22:29 -0700742 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700743 }
744
745 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
746 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700747 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700748 rebatchAllAlarmsLocked(true);
749 }
750 }
751
752 void rebatchAllAlarmsLocked(boolean doValidate) {
753 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
754 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700755 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700756 final long nowElapsed = SystemClock.elapsedRealtime();
757 final int oldBatches = oldSet.size();
758 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
759 Batch batch = oldSet.get(batchNum);
760 final int N = batch.size();
761 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700762 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700763 }
764 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700765 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
766 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
767 + " to " + mPendingIdleUntil);
768 if (mPendingIdleUntil == null) {
769 // Somehow we lost this... we need to restore all of the pending alarms.
770 restorePendingWhileIdleAlarmsLocked();
771 }
772 }
773 rescheduleKernelAlarmsLocked();
774 updateNextAlarmClockLocked();
775 }
776
777 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
778 a.when = a.origWhen;
779 long whenElapsed = convertToElapsed(a.when, a.type);
780 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700781 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700782 // Exact
783 maxElapsed = whenElapsed;
784 } else {
785 // Not exact. Preserve any explicit window, otherwise recalculate
786 // the window based on the alarm's new futurity. Note that this
787 // reflects a policy of preferring timely to deferred delivery.
788 maxElapsed = (a.windowLength > 0)
789 ? (whenElapsed + a.windowLength)
790 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
791 }
792 a.whenElapsed = whenElapsed;
793 a.maxWhenElapsed = maxElapsed;
794 setImplLocked(a, true, doValidate);
795 }
796
797 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700798 if (RECORD_DEVICE_IDLE_ALARMS) {
799 IdleDispatchEntry ent = new IdleDispatchEntry();
800 ent.uid = 0;
801 ent.pkg = "FINISH IDLE";
802 ent.elapsedRealtime = SystemClock.elapsedRealtime();
803 mAllowWhileIdleDispatches.add(ent);
804 }
805
Dianne Hackborn35d54032015-04-23 10:30:43 -0700806 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700807 if (mPendingWhileIdleAlarms.size() > 0) {
808 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
809 mPendingWhileIdleAlarms = new ArrayList<>();
810 final long nowElapsed = SystemClock.elapsedRealtime();
811 for (int i=alarms.size() - 1; i >= 0; i--) {
812 Alarm a = alarms.get(i);
813 reAddAlarmLocked(a, nowElapsed, false);
814 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700815 }
Dianne Hackborn35d54032015-04-23 10:30:43 -0700816
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700817 // Make sure we are using the correct ALLOW_WHILE_IDLE min time.
Dianne Hackborna750a632015-06-16 17:18:23 -0700818 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700819
Dianne Hackborn35d54032015-04-23 10:30:43 -0700820 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700821 rescheduleKernelAlarmsLocked();
822 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -0700823
824 // And send a TIME_TICK right now, since it is important to get the UI updated.
825 try {
826 mTimeTickSender.send();
827 } catch (PendingIntent.CanceledException e) {
828 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700829 }
830
Christopher Tate14a7bb02015-10-01 10:24:31 -0700831 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -0800832 final PendingIntent mPendingIntent;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700833 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -0700834 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700835 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700836 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800837 final BroadcastStats mBroadcastStats;
838 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800839 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800840
Christopher Tate14a7bb02015-10-01 10:24:31 -0700841 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
842 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
843 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800844 mPendingIntent = pendingIntent;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700845 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -0700846 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700847 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700848 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700849 mBroadcastStats = (pendingIntent != null)
850 ? service.getStatsLocked(pendingIntent)
851 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700852 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -0800853 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700854 fs = new FilterStats(mBroadcastStats, mTag);
855 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -0800856 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700857 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -0800858 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800859 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800860 }
Makoto Onuki33955e12017-03-01 18:11:00 -0800861
862 @Override
863 public String toString() {
864 return "InFlight{"
865 + "pendingIntent=" + mPendingIntent
866 + ", workSource=" + mWorkSource
867 + ", uid=" + mUid
868 + ", tag=" + mTag
869 + ", broadcastStats=" + mBroadcastStats
870 + ", filterStats=" + mFilterStats
871 + ", alarmType=" + mAlarmType
872 + "}";
873 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800874 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800875
Adam Lesinski182f73f2013-12-05 16:48:06 -0800876 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -0800877 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700878 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800879
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700880 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800882 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 int numWakeup;
884 long startTime;
885 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -0800886
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700887 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800888 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700889 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800890 }
Makoto Onuki33955e12017-03-01 18:11:00 -0800891
892 @Override
893 public String toString() {
894 return "FilterStats{"
895 + "tag=" + mTag
896 + ", lastTime=" + lastTime
897 + ", aggregateTime=" + aggregateTime
898 + ", count=" + count
899 + ", numWakeup=" + numWakeup
900 + ", startTime=" + startTime
901 + ", nesting=" + nesting
902 + "}";
903 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800904 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700905
Adam Lesinski182f73f2013-12-05 16:48:06 -0800906 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800907 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800908 final String mPackageName;
909
910 long aggregateTime;
911 int count;
912 int numWakeup;
913 long startTime;
914 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700915 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -0800916
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800917 BroadcastStats(int uid, String packageName) {
918 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800919 mPackageName = packageName;
920 }
Makoto Onuki33955e12017-03-01 18:11:00 -0800921
922 @Override
923 public String toString() {
924 return "BroadcastStats{"
925 + "uid=" + mUid
926 + ", packageName=" + mPackageName
927 + ", aggregateTime=" + aggregateTime
928 + ", count=" + count
929 + ", numWakeup=" + numWakeup
930 + ", startTime=" + startTime
931 + ", nesting=" + nesting
932 + "}";
933 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700935
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800936 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
937 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700938
939 int mNumDelayedAlarms = 0;
940 long mTotalDelayTime = 0;
941 long mMaxDelayTime = 0;
942
Adam Lesinski182f73f2013-12-05 16:48:06 -0800943 @Override
944 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800945 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800946 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800947
948 // We have to set current TimeZone info to kernel
949 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -0800950 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800951
Adam Lesinski182f73f2013-12-05 16:48:06 -0800952 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800953 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800954
Adam Lesinski182f73f2013-12-05 16:48:06 -0800955 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700957 Intent.FLAG_RECEIVER_REGISTERED_ONLY
Chad Brubaker291df4f2017-03-14 10:23:02 -0700958 | Intent.FLAG_RECEIVER_FOREGROUND
959 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700960 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800961 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -0700962 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
963 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800964 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700965 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966
967 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -0800968 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 mClockReceiver.scheduleTimeTickEvent();
970 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700971 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 mUninstallReceiver = new UninstallReceiver();
973
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800974 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800975 AlarmThread waitThread = new AlarmThread();
976 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800978 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800980
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700981 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800982 ActivityManager.getService().registerUidObserver(new UidObserver(),
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800983 ActivityManager.UID_OBSERVER_IDLE, ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700984 } catch (RemoteException e) {
985 // ignored; both services live in system_server
986 }
987
Adam Lesinski182f73f2013-12-05 16:48:06 -0800988 publishBinderService(Context.ALARM_SERVICE, mService);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -0800989 publishLocalService(LocalService.class, new LocalService());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800991
992 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -0700993 public void onBootPhase(int phase) {
994 if (phase == PHASE_SYSTEM_SERVICES_READY) {
995 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -0700996 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800997 mLocalDeviceIdleController
998 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackborna750a632015-06-16 17:18:23 -0700999 }
1000 }
1001
1002 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 protected void finalize() throws Throwable {
1004 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001005 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 } finally {
1007 super.finalize();
1008 }
1009 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001010
Adam Lesinski182f73f2013-12-05 16:48:06 -08001011 void setTimeZoneImpl(String tz) {
1012 if (TextUtils.isEmpty(tz)) {
1013 return;
David Christieebe51fc2013-07-26 13:23:29 -07001014 }
1015
Adam Lesinski182f73f2013-12-05 16:48:06 -08001016 TimeZone zone = TimeZone.getTimeZone(tz);
1017 // Prevent reentrant calls from stepping on each other when writing
1018 // the time zone property
1019 boolean timeZoneWasChanged = false;
1020 synchronized (this) {
1021 String current = SystemProperties.get(TIMEZONE_PROPERTY);
1022 if (current == null || !current.equals(zone.getID())) {
1023 if (localLOGV) {
1024 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
1025 }
1026 timeZoneWasChanged = true;
1027 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
1028 }
1029
1030 // Update the kernel timezone information
1031 // Kernel tracks time offsets as 'minutes west of GMT'
1032 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001033 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001034 }
1035
1036 TimeZone.setDefault(null);
1037
1038 if (timeZoneWasChanged) {
1039 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001040 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1041 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001042 intent.putExtra("time-zone", zone.getID());
1043 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1044 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001046
Adam Lesinski182f73f2013-12-05 16:48:06 -08001047 void removeImpl(PendingIntent operation) {
1048 if (operation == null) {
1049 return;
1050 }
1051 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001052 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001053 }
1054 }
1055
1056 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001057 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1058 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1059 int callingUid, String callingPackage) {
1060 // must be *either* PendingIntent or AlarmReceiver, but not both
1061 if ((operation == null && directReceiver == null)
1062 || (operation != null && directReceiver != null)) {
1063 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1064 // NB: previous releases failed silently here, so we are continuing to do the same
1065 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 return;
1067 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001068
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001069 // Sanity check the window length. This will catch people mistakenly
1070 // trying to pass an end-of-window timestamp rather than a duration.
1071 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1072 Slog.w(TAG, "Window length " + windowLength
1073 + "ms suspiciously long; limiting to 1 hour");
1074 windowLength = AlarmManager.INTERVAL_HOUR;
1075 }
1076
Christopher Tate498c6cb2014-11-17 16:09:27 -08001077 // Sanity check the recurrence interval. This will catch people who supply
1078 // seconds when the API expects milliseconds.
Dianne Hackborna750a632015-06-16 17:18:23 -07001079 final long minInterval = mConstants.MIN_INTERVAL;
1080 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001081 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001082 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001083 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001084 interval = minInterval;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001085 }
1086
Christopher Tatee0a22b32013-07-11 14:43:13 -07001087 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1088 throw new IllegalArgumentException("Invalid alarm type " + type);
1089 }
1090
Christopher Tate5f221e82013-07-30 17:13:15 -07001091 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001092 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001093 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001094 + " pid=" + what);
1095 triggerAtTime = 0;
1096 }
1097
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001098 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001099 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1100 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001101 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001102 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1103
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001104 final long maxElapsed;
1105 if (windowLength == AlarmManager.WINDOW_EXACT) {
1106 maxElapsed = triggerElapsed;
1107 } else if (windowLength < 0) {
1108 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001109 // Fix this window in place, so that as time approaches we don't collapse it.
1110 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001111 } else {
1112 maxElapsed = triggerElapsed + windowLength;
1113 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001116 if (DEBUG_BATCH) {
1117 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001118 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001119 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001120 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001122 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001123 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1124 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125 }
1126 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001127
Christopher Tate3e04b472013-10-21 17:51:31 -07001128 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001129 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1130 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1131 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001132 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001133 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1134 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001135 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001136 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001137 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1138 + " -- package not allowed to start");
1139 return;
1140 }
1141 } catch (RemoteException e) {
1142 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001143 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001144 setImplLocked(a, false, doValidate);
1145 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001146
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001147 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1148 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001149 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001150 // The caller has given the time they want this to happen at, however we need
1151 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001152 // bring us out of idle at an earlier time.
1153 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001154 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001155 }
1156 // Add fuzz to make the alarm go off some time before the actual desired time.
1157 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001158 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001159 if (fuzz > 0) {
1160 if (mRandom == null) {
1161 mRandom = new Random();
1162 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001163 final int delta = mRandom.nextInt(fuzz);
1164 a.whenElapsed -= delta;
1165 if (false) {
1166 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1167 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1168 Slog.d(TAG, "Applied fuzz: " + fuzz);
1169 Slog.d(TAG, "Final delta: " + delta);
1170 Slog.d(TAG, "Final when: " + a.whenElapsed);
1171 }
1172 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001173 }
1174
1175 } else if (mPendingIdleUntil != null) {
1176 // We currently have an idle until alarm scheduled; if the new alarm has
1177 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001178 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1179 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1180 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001181 == 0) {
1182 mPendingWhileIdleAlarms.add(a);
1183 return;
1184 }
1185 }
1186
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001187 if (RECORD_DEVICE_IDLE_ALARMS) {
1188 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1189 IdleDispatchEntry ent = new IdleDispatchEntry();
1190 ent.uid = a.uid;
1191 ent.pkg = a.operation.getCreatorPackage();
1192 ent.tag = a.operation.getTag("");
1193 ent.op = "SET";
1194 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1195 ent.argRealtime = a.whenElapsed;
1196 mAllowWhileIdleDispatches.add(ent);
1197 }
1198 }
1199
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001200 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
1201 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -07001202 if (whichBatch < 0) {
1203 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001204 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205 } else {
Christopher Tate385e4982013-07-23 18:22:29 -07001206 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001207 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001208 // The start time of this batch advanced, so batch ordering may
1209 // have just been broken. Move it to where it now belongs.
1210 mAlarmBatches.remove(whichBatch);
1211 addBatchLocked(mAlarmBatches, batch);
1212 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213 }
1214
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001215 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001216 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001217 }
1218
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001219 boolean needRebatch = false;
1220
1221 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001222 if (RECORD_DEVICE_IDLE_ALARMS) {
1223 if (mPendingIdleUntil == null) {
1224 IdleDispatchEntry ent = new IdleDispatchEntry();
1225 ent.uid = 0;
1226 ent.pkg = "START IDLE";
1227 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1228 mAllowWhileIdleDispatches.add(ent);
1229 }
1230 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001231 mPendingIdleUntil = a;
Dianne Hackborna750a632015-06-16 17:18:23 -07001232 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001233 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001234 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1235 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1236 mNextWakeFromIdle = a;
1237 // If this wake from idle is earlier than whatever was previously scheduled,
1238 // and we are currently idling, then we need to rebatch alarms in case the idle
1239 // until time needs to be updated.
1240 if (mPendingIdleUntil != null) {
1241 needRebatch = true;
1242 }
1243 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001244 }
1245
1246 if (!rebatching) {
1247 if (DEBUG_VALIDATE) {
1248 if (doValidate && !validateConsistencyLocked()) {
1249 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1250 + " when(hex)=" + Long.toHexString(a.when)
1251 + " whenElapsed=" + a.whenElapsed
1252 + " maxWhenElapsed=" + a.maxWhenElapsed
1253 + " interval=" + a.repeatInterval + " op=" + a.operation
1254 + " flags=0x" + Integer.toHexString(a.flags));
1255 rebatchAllAlarmsLocked(false);
1256 needRebatch = false;
1257 }
1258 }
1259
1260 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001261 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001262 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001263
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001264 rescheduleKernelAlarmsLocked();
1265 updateNextAlarmClockLocked();
1266 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001267 }
1268
Adam Lesinski182f73f2013-12-05 16:48:06 -08001269 private final IBinder mService = new IAlarmManager.Stub() {
1270 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001271 public void set(String callingPackage,
1272 int type, long triggerAtTime, long windowLength, long interval, int flags,
1273 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1274 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001275 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001276
1277 // make sure the caller is not lying about which package should be blamed for
1278 // wakelock time spent in alarm delivery
1279 mAppOps.checkPackage(callingUid, callingPackage);
1280
1281 // Repeating alarms must use PendingIntent, not direct listener
1282 if (interval != 0) {
1283 if (directReceiver != null) {
1284 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1285 }
1286 }
1287
Adam Lesinski182f73f2013-12-05 16:48:06 -08001288 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001289 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001290 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001291 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001292 }
1293
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001294 // No incoming callers can request either WAKE_FROM_IDLE or
1295 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1296 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1297 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1298
1299 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1300 // manager when to come out of idle mode, which is only for DeviceIdleController.
1301 if (callingUid != Process.SYSTEM_UID) {
1302 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1303 }
1304
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001305 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001306 if (windowLength == AlarmManager.WINDOW_EXACT) {
1307 flags |= AlarmManager.FLAG_STANDALONE;
1308 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001309
1310 // If this alarm is for an alarm clock, then it must be standalone and we will
1311 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001312 if (alarmClock != null) {
1313 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001314
1315 // If the caller is a core system component or on the user's whitelist, and not calling
1316 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1317 // This means we will allow these alarms to go off as normal even while idle, with no
1318 // timing restrictions.
1319 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
1320 || Arrays.binarySearch(mDeviceIdleUserWhitelist,
1321 UserHandle.getAppId(callingUid)) >= 0)) {
1322 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1323 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001324 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001325
Christopher Tate14a7bb02015-10-01 10:24:31 -07001326 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1327 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001328 }
Christopher Tate89779822012-08-31 14:40:03 -07001329
Adam Lesinski182f73f2013-12-05 16:48:06 -08001330 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001331 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001332 getContext().enforceCallingOrSelfPermission(
1333 "android.permission.SET_TIME",
1334 "setTime");
1335
Greg Hackmann0cab8962014-02-21 16:35:52 -08001336 if (mNativeData == 0) {
1337 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1338 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001339 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001340
1341 synchronized (mLock) {
1342 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001345
1346 @Override
1347 public void setTimeZone(String tz) {
1348 getContext().enforceCallingOrSelfPermission(
1349 "android.permission.SET_TIME_ZONE",
1350 "setTimeZone");
1351
1352 final long oldId = Binder.clearCallingIdentity();
1353 try {
1354 setTimeZoneImpl(tz);
1355 } finally {
1356 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357 }
1358 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001359
Adam Lesinski182f73f2013-12-05 16:48:06 -08001360 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001361 public void remove(PendingIntent operation, IAlarmListener listener) {
1362 if (operation == null && listener == null) {
1363 Slog.w(TAG, "remove() with no intent or listener");
1364 return;
1365 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001366
Christopher Tate14a7bb02015-10-01 10:24:31 -07001367 synchronized (mLock) {
1368 removeLocked(operation, listener);
1369 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001371
Adam Lesinski182f73f2013-12-05 16:48:06 -08001372 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001373 public long getNextWakeFromIdleTime() {
1374 return getNextWakeFromIdleTimeImpl();
1375 }
1376
1377 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001378 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001379 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1380 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1381 "getNextAlarmClock", null);
1382
1383 return getNextAlarmClockImpl(userId);
1384 }
1385
1386 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001387 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06001388 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001389 dumpImpl(pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001390 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001391 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001392
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001393 public final class LocalService {
1394 public void setDeviceIdleUserWhitelist(int[] appids) {
1395 setDeviceIdleUserWhitelistImpl(appids);
1396 }
1397 }
1398
Adam Lesinski182f73f2013-12-05 16:48:06 -08001399 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 synchronized (mLock) {
1401 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001402 mConstants.dump(pw);
1403 pw.println();
1404
Christopher Tatee0a22b32013-07-11 14:43:13 -07001405 final long nowRTC = System.currentTimeMillis();
1406 final long nowELAPSED = SystemClock.elapsedRealtime();
1407 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1408
Dianne Hackborna750a632015-06-16 17:18:23 -07001409 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001410 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001411 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001412 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001413 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001414 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001415 pw.print(" mLastTimeChangeRealtime=");
Dianne Hackbornc3527222015-05-13 14:03:20 -07001416 TimeUtils.formatDuration(mLastTimeChangeRealtime, pw);
1417 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001418 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001419 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001420 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1421 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001422 pw.print(" Max wakeup delay: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001423 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1424 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001425 pw.print(" Time since last dispatch: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001426 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1427 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001428 pw.print(" Next non-wakeup delivery time: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001429 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1430 pw.println();
1431 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001432
1433 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1434 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001435 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001436 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001437 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001438 pw.print(" Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001439 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001440 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
1441 pw.print(" set at "); TimeUtils.formatDuration(mLastWakeupSet, nowELAPSED, pw);
1442 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001443 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001444 pw.println(" mDeviceIdleUserWhitelist=" + Arrays.toString(mDeviceIdleUserWhitelist));
Christopher Tatee0a22b32013-07-11 14:43:13 -07001445
John Spurlock604a5ee2015-06-01 12:27:22 -04001446 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001447 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001448 final TreeSet<Integer> users = new TreeSet<>();
1449 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1450 users.add(mNextAlarmClockForUser.keyAt(i));
1451 }
1452 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1453 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1454 }
1455 for (int user : users) {
1456 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1457 final long time = next != null ? next.getTriggerTime() : 0;
1458 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001459 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001460 pw.print(" pendingSend:"); pw.print(pendingSend);
1461 pw.print(" time:"); pw.print(time);
1462 if (time > 0) {
1463 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1464 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1465 }
1466 pw.println();
1467 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001468 if (mAlarmBatches.size() > 0) {
1469 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001470 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001471 pw.println(mAlarmBatches.size());
1472 for (Batch b : mAlarmBatches) {
1473 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001474 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001475 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001477 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001478 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001479 pw.println(" Idle mode state:");
1480 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001481 if (mPendingIdleUntil != null) {
1482 pw.println(mPendingIdleUntil);
Dianne Hackbornf3831292015-10-15 14:51:06 -07001483 mPendingIdleUntil.dump(pw, " ", nowRTC, nowELAPSED, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001484 } else {
1485 pw.println("null");
1486 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001487 pw.println(" Pending alarms:");
1488 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001489 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001490 if (mNextWakeFromIdle != null) {
1491 pw.println();
1492 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
1493 mNextWakeFromIdle.dump(pw, " ", nowRTC, nowELAPSED, sdf);
1494 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001495
1496 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001497 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001498 if (mPendingNonWakeupAlarms.size() > 0) {
1499 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001500 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001501 } else {
1502 pw.println("(none)");
1503 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001504 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001505 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1506 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001507 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001508 pw.print(", max non-interactive time: ");
1509 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1510 pw.println();
1511
1512 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001513 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001514 pw.println();
1515
Christopher Tate7f2a0352015-12-08 10:24:33 -08001516 if (mInFlight.size() > 0) {
1517 pw.println("Outstanding deliveries:");
1518 for (int i = 0; i < mInFlight.size(); i++) {
1519 pw.print(" #"); pw.print(i); pw.print(": ");
1520 pw.println(mInFlight.get(i));
1521 }
1522 pw.println();
1523 }
1524
Dianne Hackborna750a632015-06-16 17:18:23 -07001525 pw.print(" mAllowWhileIdleMinTime=");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001526 TimeUtils.formatDuration(mAllowWhileIdleMinTime, pw);
1527 pw.println();
1528 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001529 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001530 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
1531 pw.print(" UID ");
1532 UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
1533 pw.print(": ");
1534 TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i),
1535 nowELAPSED, pw);
1536 pw.println();
1537 }
1538 }
1539 pw.println();
1540
Dianne Hackborn81038902012-11-26 17:04:09 -08001541 if (mLog.dump(pw, " Recent problems", " ")) {
1542 pw.println();
1543 }
1544
1545 final FilterStats[] topFilters = new FilterStats[10];
1546 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1547 @Override
1548 public int compare(FilterStats lhs, FilterStats rhs) {
1549 if (lhs.aggregateTime < rhs.aggregateTime) {
1550 return 1;
1551 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1552 return -1;
1553 }
1554 return 0;
1555 }
1556 };
1557 int len = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001558 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1559 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1560 for (int ip=0; ip<uidStats.size(); ip++) {
1561 BroadcastStats bs = uidStats.valueAt(ip);
1562 for (int is=0; is<bs.filterStats.size(); is++) {
1563 FilterStats fs = bs.filterStats.valueAt(is);
1564 int pos = len > 0
1565 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1566 if (pos < 0) {
1567 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001568 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001569 if (pos < topFilters.length) {
1570 int copylen = topFilters.length - pos - 1;
1571 if (copylen > 0) {
1572 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1573 }
1574 topFilters[pos] = fs;
1575 if (len < topFilters.length) {
1576 len++;
1577 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001578 }
1579 }
1580 }
1581 }
1582 if (len > 0) {
1583 pw.println(" Top Alarms:");
1584 for (int i=0; i<len; i++) {
1585 FilterStats fs = topFilters[i];
1586 pw.print(" ");
1587 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1588 TimeUtils.formatDuration(fs.aggregateTime, pw);
1589 pw.print(" running, "); pw.print(fs.numWakeup);
1590 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001591 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1592 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001593 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001594 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001595 pw.println();
1596 }
1597 }
1598
1599 pw.println(" ");
1600 pw.println(" Alarm Stats:");
1601 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001602 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1603 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1604 for (int ip=0; ip<uidStats.size(); ip++) {
1605 BroadcastStats bs = uidStats.valueAt(ip);
1606 pw.print(" ");
1607 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1608 UserHandle.formatUid(pw, bs.mUid);
1609 pw.print(":");
1610 pw.print(bs.mPackageName);
1611 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1612 pw.print(" running, "); pw.print(bs.numWakeup);
1613 pw.println(" wakeups:");
1614 tmpFilters.clear();
1615 for (int is=0; is<bs.filterStats.size(); is++) {
1616 tmpFilters.add(bs.filterStats.valueAt(is));
1617 }
1618 Collections.sort(tmpFilters, comparator);
1619 for (int i=0; i<tmpFilters.size(); i++) {
1620 FilterStats fs = tmpFilters.get(i);
1621 pw.print(" ");
1622 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1623 TimeUtils.formatDuration(fs.aggregateTime, pw);
1624 pw.print(" "); pw.print(fs.numWakeup);
1625 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001626 pw.print(" alarms, last ");
1627 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1628 pw.println(":");
1629 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001630 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001631 pw.println();
1632 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 }
1634 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001635
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001636 if (RECORD_DEVICE_IDLE_ALARMS) {
1637 pw.println();
1638 pw.println(" Allow while idle dispatches:");
1639 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
1640 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
1641 pw.print(" ");
1642 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
1643 pw.print(": ");
1644 UserHandle.formatUid(pw, ent.uid);
1645 pw.print(":");
1646 pw.println(ent.pkg);
1647 if (ent.op != null) {
1648 pw.print(" ");
1649 pw.print(ent.op);
1650 pw.print(" / ");
1651 pw.print(ent.tag);
1652 if (ent.argRealtime != 0) {
1653 pw.print(" (");
1654 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
1655 pw.print(")");
1656 }
1657 pw.println();
1658 }
1659 }
1660 }
1661
Christopher Tate18a75f12013-07-01 18:18:59 -07001662 if (WAKEUP_STATS) {
1663 pw.println();
1664 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001665 long last = -1;
1666 for (WakeupEvent event : mRecentWakeups) {
1667 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1668 pw.print('|');
1669 if (last < 0) {
1670 pw.print('0');
1671 } else {
1672 pw.print(event.when - last);
1673 }
1674 last = event.when;
1675 pw.print('|'); pw.print(event.uid);
1676 pw.print('|'); pw.print(event.action);
1677 pw.println();
1678 }
1679 pw.println();
1680 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 }
1682 }
1683
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001684 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001685 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
1686 PrintWriter pw = new PrintWriter(bs);
1687 final long nowRTC = System.currentTimeMillis();
1688 final long nowELAPSED = SystemClock.elapsedRealtime();
1689 final int NZ = mAlarmBatches.size();
1690 for (int iz = 0; iz < NZ; iz++) {
1691 Batch bz = mAlarmBatches.get(iz);
1692 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001693 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001694 pw.flush();
1695 Slog.v(TAG, bs.toString());
1696 bs.reset();
1697 }
1698 }
1699
1700 private boolean validateConsistencyLocked() {
1701 if (DEBUG_VALIDATE) {
1702 long lastTime = Long.MIN_VALUE;
1703 final int N = mAlarmBatches.size();
1704 for (int i = 0; i < N; i++) {
1705 Batch b = mAlarmBatches.get(i);
1706 if (b.start >= lastTime) {
1707 // duplicate start times are okay because of standalone batches
1708 lastTime = b.start;
1709 } else {
1710 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001711 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1712 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001713 return false;
1714 }
1715 }
1716 }
1717 return true;
1718 }
1719
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001720 private Batch findFirstWakeupBatchLocked() {
1721 final int N = mAlarmBatches.size();
1722 for (int i = 0; i < N; i++) {
1723 Batch b = mAlarmBatches.get(i);
1724 if (b.hasWakeups()) {
1725 return b;
1726 }
1727 }
1728 return null;
1729 }
1730
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001731 long getNextWakeFromIdleTimeImpl() {
1732 synchronized (mLock) {
1733 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
1734 }
1735 }
1736
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001737 void setDeviceIdleUserWhitelistImpl(int[] appids) {
1738 synchronized (mLock) {
1739 mDeviceIdleUserWhitelist = appids;
1740 }
1741 }
1742
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001743 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001744 synchronized (mLock) {
1745 return mNextAlarmClockForUser.get(userId);
1746 }
1747 }
1748
1749 /**
1750 * Recomputes the next alarm clock for all users.
1751 */
1752 private void updateNextAlarmClockLocked() {
1753 if (!mNextAlarmClockMayChange) {
1754 return;
1755 }
1756 mNextAlarmClockMayChange = false;
1757
Jose Lima235510e2014-08-13 12:50:01 -07001758 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001759 nextForUser.clear();
1760
1761 final int N = mAlarmBatches.size();
1762 for (int i = 0; i < N; i++) {
1763 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
1764 final int M = alarms.size();
1765
1766 for (int j = 0; j < M; j++) {
1767 Alarm a = alarms.get(j);
1768 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001769 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07001770 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001771
1772 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07001773 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001774 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02001775 " for user " + userId);
1776 }
1777
1778 // Alarms and batches are sorted by time, no need to compare times here.
1779 if (nextForUser.get(userId) == null) {
1780 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07001781 } else if (a.alarmClock.equals(current)
1782 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
1783 // same/earlier time and it's the one we cited before, so stick with it
1784 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001785 }
1786 }
1787 }
1788 }
1789
1790 // Update mNextAlarmForUser with new values.
1791 final int NN = nextForUser.size();
1792 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07001793 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001794 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001795 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001796 if (!newAlarm.equals(currentAlarm)) {
1797 updateNextAlarmInfoForUserLocked(userId, newAlarm);
1798 }
1799 }
1800
1801 // Remove users without any alarm clocks scheduled.
1802 final int NNN = mNextAlarmClockForUser.size();
1803 for (int i = NNN - 1; i >= 0; i--) {
1804 int userId = mNextAlarmClockForUser.keyAt(i);
1805 if (nextForUser.get(userId) == null) {
1806 updateNextAlarmInfoForUserLocked(userId, null);
1807 }
1808 }
1809 }
1810
Jose Lima235510e2014-08-13 12:50:01 -07001811 private void updateNextAlarmInfoForUserLocked(int userId,
1812 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001813 if (alarmClock != null) {
1814 if (DEBUG_ALARM_CLOCK) {
1815 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001816 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02001817 }
1818 mNextAlarmClockForUser.put(userId, alarmClock);
1819 } else {
1820 if (DEBUG_ALARM_CLOCK) {
1821 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
1822 }
1823 mNextAlarmClockForUser.remove(userId);
1824 }
1825
1826 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
1827 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1828 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1829 }
1830
1831 /**
1832 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
1833 * for which alarm clocks have changed since the last call to this.
1834 *
1835 * Do not call with a lock held. Only call from mHandler's thread.
1836 *
1837 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
1838 */
1839 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07001840 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001841 pendingUsers.clear();
1842
1843 synchronized (mLock) {
1844 final int N = mPendingSendNextAlarmClockChangedForUser.size();
1845 for (int i = 0; i < N; i++) {
1846 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
1847 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
1848 }
1849 mPendingSendNextAlarmClockChangedForUser.clear();
1850 }
1851
1852 final int N = pendingUsers.size();
1853 for (int i = 0; i < N; i++) {
1854 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001855 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001856 Settings.System.putStringForUser(getContext().getContentResolver(),
1857 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01001858 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02001859 userId);
1860
1861 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
1862 new UserHandle(userId));
1863 }
1864 }
1865
1866 /**
1867 * Formats an alarm like platform/packages/apps/DeskClock used to.
1868 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01001869 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
1870 int userId) {
1871 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02001872 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
1873 return (info == null) ? "" :
1874 DateFormat.format(pattern, info.getTriggerTime()).toString();
1875 }
1876
Adam Lesinski182f73f2013-12-05 16:48:06 -08001877 void rescheduleKernelAlarmsLocked() {
1878 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
1879 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001880 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001881 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001882 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001883 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07001884 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001885 mNextWakeup = firstWakeup.start;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001886 mLastWakeupSet = SystemClock.elapsedRealtime();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001887 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001888 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001889 if (firstBatch != firstWakeup) {
1890 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001891 }
1892 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001893 if (mPendingNonWakeupAlarms.size() > 0) {
1894 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
1895 nextNonWakeup = mNextNonWakeupDeliveryTime;
1896 }
1897 }
Prashant Malani753e9e02015-06-10 17:43:49 -07001898 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001899 mNextNonWakeup = nextNonWakeup;
1900 setLocked(ELAPSED_REALTIME, nextNonWakeup);
1901 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001902 }
1903
Christopher Tate14a7bb02015-10-01 10:24:31 -07001904 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001905 boolean didRemove = false;
1906 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1907 Batch b = mAlarmBatches.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -07001908 didRemove |= b.remove(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001909 if (b.size() == 0) {
1910 mAlarmBatches.remove(i);
1911 }
1912 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001913 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001914 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001915 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1916 mPendingWhileIdleAlarms.remove(i);
1917 }
1918 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001919
1920 if (didRemove) {
1921 if (DEBUG_BATCH) {
1922 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
1923 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001924 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001925 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001926 mPendingIdleUntil = null;
1927 restorePending = true;
1928 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001929 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001930 mNextWakeFromIdle = null;
1931 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001932 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001933 if (restorePending) {
1934 restorePendingWhileIdleAlarmsLocked();
1935 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001936 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001937 }
1938 }
1939
1940 void removeLocked(String packageName) {
1941 boolean didRemove = false;
1942 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1943 Batch b = mAlarmBatches.get(i);
1944 didRemove |= b.remove(packageName);
1945 if (b.size() == 0) {
1946 mAlarmBatches.remove(i);
1947 }
1948 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001949 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001950 final Alarm a = mPendingWhileIdleAlarms.get(i);
1951 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001952 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1953 mPendingWhileIdleAlarms.remove(i);
1954 }
1955 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001956
1957 if (didRemove) {
1958 if (DEBUG_BATCH) {
1959 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1960 }
1961 rebatchAllAlarmsLocked(true);
1962 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001963 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001964 }
1965 }
1966
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001967 void removeForStoppedLocked(int uid) {
1968 boolean didRemove = false;
1969 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1970 Batch b = mAlarmBatches.get(i);
1971 didRemove |= b.removeForStopped(uid);
1972 if (b.size() == 0) {
1973 mAlarmBatches.remove(i);
1974 }
1975 }
1976 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1977 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08001978 if (a.uid == uid) {
1979 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1980 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001981 }
1982 }
1983
1984 if (didRemove) {
1985 if (DEBUG_BATCH) {
1986 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1987 }
1988 rebatchAllAlarmsLocked(true);
1989 rescheduleKernelAlarmsLocked();
1990 updateNextAlarmClockLocked();
1991 }
1992 }
1993
Adam Lesinski182f73f2013-12-05 16:48:06 -08001994 void removeUserLocked(int userHandle) {
1995 boolean didRemove = false;
1996 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1997 Batch b = mAlarmBatches.get(i);
1998 didRemove |= b.remove(userHandle);
1999 if (b.size() == 0) {
2000 mAlarmBatches.remove(i);
2001 }
2002 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002003 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002004 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002005 == userHandle) {
2006 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2007 mPendingWhileIdleAlarms.remove(i);
2008 }
2009 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002010 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
2011 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
2012 mLastAllowWhileIdleDispatch.removeAt(i);
2013 }
2014 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002015
2016 if (didRemove) {
2017 if (DEBUG_BATCH) {
2018 Slog.v(TAG, "remove(user) changed bounds; rebatching");
2019 }
2020 rebatchAllAlarmsLocked(true);
2021 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002022 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002023 }
2024 }
2025
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002026 void interactiveStateChangedLocked(boolean interactive) {
2027 if (mInteractive != interactive) {
2028 mInteractive = interactive;
2029 final long nowELAPSED = SystemClock.elapsedRealtime();
2030 if (interactive) {
2031 if (mPendingNonWakeupAlarms.size() > 0) {
2032 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2033 mTotalDelayTime += thisDelayTime;
2034 if (mMaxDelayTime < thisDelayTime) {
2035 mMaxDelayTime = thisDelayTime;
2036 }
2037 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2038 mPendingNonWakeupAlarms.clear();
2039 }
2040 if (mNonInteractiveStartTime > 0) {
2041 long dur = nowELAPSED - mNonInteractiveStartTime;
2042 if (dur > mNonInteractiveTime) {
2043 mNonInteractiveTime = dur;
2044 }
2045 }
2046 } else {
2047 mNonInteractiveStartTime = nowELAPSED;
2048 }
2049 }
2050 }
2051
Adam Lesinski182f73f2013-12-05 16:48:06 -08002052 boolean lookForPackageLocked(String packageName) {
2053 for (int i = 0; i < mAlarmBatches.size(); i++) {
2054 Batch b = mAlarmBatches.get(i);
2055 if (b.hasPackage(packageName)) {
2056 return true;
2057 }
2058 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002059 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002060 final Alarm a = mPendingWhileIdleAlarms.get(i);
2061 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002062 return true;
2063 }
2064 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002065 return false;
2066 }
2067
2068 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002069 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002070 // The kernel never triggers alarms with negative wakeup times
2071 // so we ensure they are positive.
2072 long alarmSeconds, alarmNanoseconds;
2073 if (when < 0) {
2074 alarmSeconds = 0;
2075 alarmNanoseconds = 0;
2076 } else {
2077 alarmSeconds = when / 1000;
2078 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2079 }
2080
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002081 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002082 } else {
2083 Message msg = Message.obtain();
2084 msg.what = ALARM_EVENT;
2085
2086 mHandler.removeMessages(ALARM_EVENT);
2087 mHandler.sendMessageAtTime(msg, when);
2088 }
2089 }
2090
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002091 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002092 String prefix, String label, long nowRTC, long nowELAPSED, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093 for (int i=list.size()-1; i>=0; i--) {
2094 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002095 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2096 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002097 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002098 }
2099 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002100
2101 private static final String labelForType(int type) {
2102 switch (type) {
2103 case RTC: return "RTC";
2104 case RTC_WAKEUP : return "RTC_WAKEUP";
2105 case ELAPSED_REALTIME : return "ELAPSED";
2106 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
2107 default:
2108 break;
2109 }
2110 return "--unknown--";
2111 }
2112
2113 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002114 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002115 for (int i=list.size()-1; i>=0; i--) {
2116 Alarm a = list.get(i);
2117 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002118 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2119 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002120 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002121 }
2122 }
2123
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002124 private native long init();
2125 private native void close(long nativeData);
2126 private native void set(long nativeData, int type, long seconds, long nanoseconds);
2127 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08002128 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002129 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002131 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002132 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002133 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002134 // batches are temporally sorted, so we need only pull from the
2135 // start of the list until we either empty it or hit a batch
2136 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07002137 while (mAlarmBatches.size() > 0) {
2138 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002139 if (batch.start > nowELAPSED) {
2140 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002141 break;
2142 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002143
Christopher Tatee0a22b32013-07-11 14:43:13 -07002144 // We will (re)schedule some alarms now; don't let that interfere
2145 // with delivery of this current batch
2146 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002147
Christopher Tatee0a22b32013-07-11 14:43:13 -07002148 final int N = batch.size();
2149 for (int i = 0; i < N; i++) {
2150 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002151
2152 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
2153 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
2154 // schedule such alarms.
2155 long lastTime = mLastAllowWhileIdleDispatch.get(alarm.uid, 0);
2156 long minTime = lastTime + mAllowWhileIdleMinTime;
2157 if (nowELAPSED < minTime) {
2158 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
2159 // alarm went off for this app. Reschedule the alarm to be in the
2160 // correct time period.
2161 alarm.whenElapsed = minTime;
2162 if (alarm.maxWhenElapsed < minTime) {
2163 alarm.maxWhenElapsed = minTime;
2164 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002165 if (RECORD_DEVICE_IDLE_ALARMS) {
2166 IdleDispatchEntry ent = new IdleDispatchEntry();
2167 ent.uid = alarm.uid;
2168 ent.pkg = alarm.operation.getCreatorPackage();
2169 ent.tag = alarm.operation.getTag("");
2170 ent.op = "RESCHEDULE";
2171 ent.elapsedRealtime = nowELAPSED;
2172 ent.argRealtime = lastTime;
2173 mAllowWhileIdleDispatches.add(ent);
2174 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002175 setImplLocked(alarm, true, false);
2176 continue;
2177 }
2178 }
2179
Christopher Tatee0a22b32013-07-11 14:43:13 -07002180 alarm.count = 1;
2181 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002182 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
2183 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002184 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002185 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002186 if (mPendingIdleUntil == alarm) {
2187 mPendingIdleUntil = null;
2188 rebatchAllAlarmsLocked(false);
2189 restorePendingWhileIdleAlarmsLocked();
2190 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002191 if (mNextWakeFromIdle == alarm) {
2192 mNextWakeFromIdle = null;
2193 rebatchAllAlarmsLocked(false);
2194 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002195
2196 // Recurring alarms may have passed several alarm intervals while the
2197 // phone was asleep or off, so pass a trigger count when sending them.
2198 if (alarm.repeatInterval > 0) {
2199 // this adjustment will be zero if we're late by
2200 // less than one full repeat interval
2201 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
2202
2203 // Also schedule its next recurrence
2204 final long delta = alarm.count * alarm.repeatInterval;
2205 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07002206 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07002207 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07002208 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
2209 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08002210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002211
Christopher Tate864d42e2014-12-02 11:48:53 -08002212 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002213 hasWakeup = true;
2214 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002215
2216 // We removed an alarm clock. Let the caller recompute the next alarm clock.
2217 if (alarm.alarmClock != null) {
2218 mNextAlarmClockMayChange = true;
2219 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07002220 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002221 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002222
Christopher Tate1590f1e2014-10-02 17:27:57 -07002223 // This is a new alarm delivery set; bump the sequence number to indicate that
2224 // all apps' alarm delivery classes should be recalculated.
2225 mCurrentSeq++;
2226 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002227 Collections.sort(triggerList, mAlarmDispatchComparator);
2228
2229 if (localLOGV) {
2230 for (int i=0; i<triggerList.size(); i++) {
2231 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
2232 }
2233 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002234
2235 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002236 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002238 /**
2239 * This Comparator sorts Alarms into increasing time order.
2240 */
2241 public static class IncreasingTimeOrder implements Comparator<Alarm> {
2242 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09002243 long when1 = a1.whenElapsed;
2244 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002245 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002246 return 1;
2247 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002248 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002249 return -1;
2250 }
2251 return 0;
2252 }
2253 }
2254
2255 private static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002256 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002257 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002258 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002259 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002260 public final IAlarmListener listener;
2261 public final String listenerTag;
2262 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002263 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002264 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002265 public final AlarmManager.AlarmClockInfo alarmClock;
2266 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002267 public final int creatorUid;
2268 public final String packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269 public int count;
2270 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07002271 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002272 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002273 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002274 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07002275 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002276
Christopher Tate3e04b472013-10-21 17:51:31 -07002277 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002278 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
2279 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
2280 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002281 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002282 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002283 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
2284 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002285 when = _when;
2286 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07002287 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002288 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002289 repeatInterval = _interval;
2290 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002291 listener = _rec;
2292 listenerTag = _listenerTag;
2293 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07002294 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002295 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002296 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002297 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002298 packageName = _pkgName;
2299
2300 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002301 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002302
Christopher Tate14a7bb02015-10-01 10:24:31 -07002303 public static String makeTag(PendingIntent pi, String tag, int type) {
2304 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
2305 ? "*walarm*:" : "*alarm*:";
2306 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
2307 }
2308
2309 public WakeupEvent makeWakeupEvent(long nowRTC) {
2310 return new WakeupEvent(nowRTC, creatorUid,
2311 (operation != null)
2312 ? operation.getIntent().getAction()
2313 : ("<listener>:" + listenerTag));
2314 }
2315
2316 // Returns true if either matches
2317 public boolean matches(PendingIntent pi, IAlarmListener rec) {
2318 return (operation != null)
2319 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09002320 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07002321 }
2322
2323 public boolean matches(String packageName) {
2324 return (operation != null)
2325 ? packageName.equals(operation.getTargetPackage())
2326 : packageName.equals(this.packageName);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002327 }
2328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002329 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002330 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002331 StringBuilder sb = new StringBuilder(128);
2332 sb.append("Alarm{");
2333 sb.append(Integer.toHexString(System.identityHashCode(this)));
2334 sb.append(" type ");
2335 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002336 sb.append(" when ");
2337 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002338 sb.append(" ");
Christopher Tate14a7bb02015-10-01 10:24:31 -07002339 if (operation != null) {
2340 sb.append(operation.getTargetPackage());
2341 } else {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002342 sb.append(packageName);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002343 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002344 sb.append('}');
2345 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002346 }
2347
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002348 public void dump(PrintWriter pw, String prefix, long nowRTC, long nowELAPSED,
2349 SimpleDateFormat sdf) {
2350 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002351 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002352 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002353 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
2354 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002355 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002356 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002357 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002358 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002359 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002360 }
2361 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002362 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002363 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002364 pw.print(" count="); pw.print(count);
2365 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002366 if (alarmClock != null) {
2367 pw.print(prefix); pw.println("Alarm clock:");
2368 pw.print(prefix); pw.print(" triggerTime=");
2369 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
2370 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
2371 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002372 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002373 if (listener != null) {
2374 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
2375 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002376 }
2377 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002378
Christopher Tatee0a22b32013-07-11 14:43:13 -07002379 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
2380 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002381 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
2382 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002383 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07002384 break;
2385 }
2386
Christopher Tatee0a22b32013-07-11 14:43:13 -07002387 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002388 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
2389 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002390 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07002391 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002392 }
2393 }
2394
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002395 long currentNonWakeupFuzzLocked(long nowELAPSED) {
2396 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
2397 if (timeSinceOn < 5*60*1000) {
2398 // If the screen has been off for 5 minutes, only delay by at most two minutes.
2399 return 2*60*1000;
2400 } else if (timeSinceOn < 30*60*1000) {
2401 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
2402 return 15*60*1000;
2403 } else {
2404 // Otherwise, we will delay by at most an hour.
2405 return 60*60*1000;
2406 }
2407 }
2408
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002409 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002410 if (duration < 15*60*1000) {
2411 // If the duration until the time is less than 15 minutes, the maximum fuzz
2412 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002413 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002414 } else if (duration < 90*60*1000) {
2415 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
2416 return 15*60*1000;
2417 } else {
2418 // Otherwise, we will fuzz by at most half an hour.
2419 return 30*60*1000;
2420 }
2421 }
2422
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002423 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
2424 if (mInteractive) {
2425 return false;
2426 }
2427 if (mLastAlarmDeliveryTime <= 0) {
2428 return false;
2429 }
minho.choo649acab2014-12-12 16:13:55 +09002430 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002431 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
2432 // and the next delivery time is in the past, then just deliver them all. This
2433 // avoids bugs where we get stuck in a loop trying to poll for alarms.
2434 return false;
2435 }
2436 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
2437 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
2438 }
2439
2440 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
2441 mLastAlarmDeliveryTime = nowELAPSED;
2442 for (int i=0; i<triggerList.size(); i++) {
2443 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07002444 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002445 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07002446 if (localLOGV) {
2447 Slog.v(TAG, "sending alarm " + alarm);
2448 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07002449 if (RECORD_ALARMS_IN_HISTORY) {
2450 if (alarm.workSource != null && alarm.workSource.size() > 0) {
2451 for (int wi=0; wi<alarm.workSource.size(); wi++) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002452 ActivityManager.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002453 alarm.operation, alarm.workSource.get(wi), alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002454 }
2455 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002456 ActivityManager.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002457 alarm.operation, alarm.uid, alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002458 }
2459 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002460 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002461 } catch (RuntimeException e) {
2462 Slog.w(TAG, "Failure sending alarm.", e);
2463 }
2464 }
2465 }
2466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002467 private class AlarmThread extends Thread
2468 {
2469 public AlarmThread()
2470 {
2471 super("AlarmManager");
2472 }
2473
2474 public void run()
2475 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002476 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002478 while (true)
2479 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002480 int result = waitForAlarm(mNativeData);
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002481 mLastWakeup = SystemClock.elapsedRealtime();
Dianne Hackborn390517b2013-05-30 15:03:32 -07002482
2483 triggerList.clear();
2484
Dianne Hackbornc3527222015-05-13 14:03:20 -07002485 final long nowRTC = System.currentTimeMillis();
2486 final long nowELAPSED = SystemClock.elapsedRealtime();
2487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002489 // The kernel can give us spurious time change notifications due to
2490 // small adjustments it makes internally; we want to filter those out.
2491 final long lastTimeChangeClockTime;
2492 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07002493 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002494 lastTimeChangeClockTime = mLastTimeChangeClockTime;
2495 expectedClockTime = lastTimeChangeClockTime
2496 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07002497 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08002498 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
2499 || nowRTC > (expectedClockTime+1000)) {
2500 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07002501 // let's do it!
2502 if (DEBUG_BATCH) {
2503 Slog.v(TAG, "Time changed notification from kernel; rebatching");
2504 }
2505 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07002506 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07002507 rebatchAllAlarms();
2508 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07002509 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07002510 synchronized (mLock) {
2511 mNumTimeChanged++;
2512 mLastTimeChangeClockTime = nowRTC;
2513 mLastTimeChangeRealtime = nowELAPSED;
2514 }
2515 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
2516 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08002517 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07002518 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
2519 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07002520 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
2521
2522 // The world has changed on us, so we need to re-evaluate alarms
2523 // regardless of whether the kernel has told us one went off.
2524 result |= IS_WAKEUP_MASK;
2525 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002526 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527
Dianne Hackbornc3527222015-05-13 14:03:20 -07002528 if (result != TIME_CHANGED_MASK) {
2529 // If this was anything besides just a time change, then figure what if
2530 // anything to do about alarms.
2531 synchronized (mLock) {
2532 if (localLOGV) Slog.v(
2533 TAG, "Checking for alarms... rtc=" + nowRTC
2534 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07002535
Dianne Hackbornc3527222015-05-13 14:03:20 -07002536 if (WAKEUP_STATS) {
2537 if ((result & IS_WAKEUP_MASK) != 0) {
2538 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
2539 int n = 0;
2540 for (WakeupEvent event : mRecentWakeups) {
2541 if (event.when > newEarliest) break;
2542 n++; // number of now-stale entries at the list head
2543 }
2544 for (int i = 0; i < n; i++) {
2545 mRecentWakeups.remove();
2546 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002547
Dianne Hackbornc3527222015-05-13 14:03:20 -07002548 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002549 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002550 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002551
2552 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2553 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
2554 // if there are no wakeup alarms and the screen is off, we can
2555 // delay what we have so far until the future.
2556 if (mPendingNonWakeupAlarms.size() == 0) {
2557 mStartCurrentDelayTime = nowELAPSED;
2558 mNextNonWakeupDeliveryTime = nowELAPSED
2559 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
2560 }
2561 mPendingNonWakeupAlarms.addAll(triggerList);
2562 mNumDelayedAlarms += triggerList.size();
2563 rescheduleKernelAlarmsLocked();
2564 updateNextAlarmClockLocked();
2565 } else {
2566 // now deliver the alarm intents; if there are pending non-wakeup
2567 // alarms, we need to merge them in to the list. note we don't
2568 // just deliver them first because we generally want non-wakeup
2569 // alarms delivered after wakeup alarms.
2570 rescheduleKernelAlarmsLocked();
2571 updateNextAlarmClockLocked();
2572 if (mPendingNonWakeupAlarms.size() > 0) {
2573 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
2574 triggerList.addAll(mPendingNonWakeupAlarms);
2575 Collections.sort(triggerList, mAlarmDispatchComparator);
2576 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2577 mTotalDelayTime += thisDelayTime;
2578 if (mMaxDelayTime < thisDelayTime) {
2579 mMaxDelayTime = thisDelayTime;
2580 }
2581 mPendingNonWakeupAlarms.clear();
2582 }
2583 deliverAlarmsLocked(triggerList, nowELAPSED);
2584 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002585 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002586
2587 } else {
2588 // Just in case -- even though no wakeup flag was set, make sure
2589 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07002590 synchronized (mLock) {
2591 rescheduleKernelAlarmsLocked();
2592 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002593 }
2594 }
2595 }
2596 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002597
David Christieebe51fc2013-07-26 13:23:29 -07002598 /**
2599 * Attribute blame for a WakeLock.
2600 * @param pi PendingIntent to attribute blame to if ws is null.
2601 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002602 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07002603 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002604 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002605 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07002606 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002607 final boolean unimportant = pi == mTimeTickSender;
2608 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002609 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002610 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002611 } else {
2612 mWakeLock.setHistoryTag(null);
2613 }
2614 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07002615 if (ws != null) {
2616 mWakeLock.setWorkSource(ws);
2617 return;
2618 }
2619
Christopher Tate14a7bb02015-10-01 10:24:31 -07002620 final int uid = (knownUid >= 0)
2621 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002622 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07002623 if (uid >= 0) {
2624 mWakeLock.setWorkSource(new WorkSource(uid));
2625 return;
2626 }
2627 } catch (Exception e) {
2628 }
2629
2630 // Something went wrong; fall back to attributing the lock to the OS
2631 mWakeLock.setWorkSource(null);
2632 }
2633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002634 private class AlarmHandler extends Handler {
2635 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002636 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
2637 public static final int LISTENER_TIMEOUT = 3;
2638 public static final int REPORT_ALARMS_ACTIVE = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002639
2640 public AlarmHandler() {
2641 }
2642
2643 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002644 switch (msg.what) {
2645 case ALARM_EVENT: {
2646 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2647 synchronized (mLock) {
2648 final long nowRTC = System.currentTimeMillis();
2649 final long nowELAPSED = SystemClock.elapsedRealtime();
2650 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2651 updateNextAlarmClockLocked();
2652 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002653
Christopher Tate14a7bb02015-10-01 10:24:31 -07002654 // now trigger the alarms without the lock held
2655 for (int i=0; i<triggerList.size(); i++) {
2656 Alarm alarm = triggerList.get(i);
2657 try {
2658 alarm.operation.send();
2659 } catch (PendingIntent.CanceledException e) {
2660 if (alarm.repeatInterval > 0) {
2661 // This IntentSender is no longer valid, but this
2662 // is a repeating alarm, so toss the hoser.
2663 removeImpl(alarm.operation);
2664 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002665 }
2666 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002667 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002668 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002669
2670 case SEND_NEXT_ALARM_CLOCK_CHANGED:
2671 sendNextAlarmClockChanged();
2672 break;
2673
2674 case LISTENER_TIMEOUT:
2675 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
2676 break;
2677
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002678 case REPORT_ALARMS_ACTIVE:
2679 if (mLocalDeviceIdleController != null) {
2680 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
2681 }
2682 break;
2683
Christopher Tate14a7bb02015-10-01 10:24:31 -07002684 default:
2685 // nope, just ignore it
2686 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002687 }
2688 }
2689 }
2690
2691 class ClockReceiver extends BroadcastReceiver {
2692 public ClockReceiver() {
2693 IntentFilter filter = new IntentFilter();
2694 filter.addAction(Intent.ACTION_TIME_TICK);
2695 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002696 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002697 }
2698
2699 @Override
2700 public void onReceive(Context context, Intent intent) {
2701 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07002702 if (DEBUG_BATCH) {
2703 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
2704 }
2705 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002706 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
2707 // Since the kernel does not keep track of DST, we need to
2708 // reset the TZ information at the beginning of each day
2709 // based off of the current Zone gmt offset + userspace tracked
2710 // daylight savings information.
2711 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02002712 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002713 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07002714 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002715 }
2716 }
2717
2718 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07002719 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09002720 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07002721
2722 // Schedule this event for the amount of time that it would take to get to
2723 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09002724 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07002725
David Christieebe51fc2013-07-26 13:23:29 -07002726 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002727 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002728 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
2729 null, Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002730 }
Christopher Tate385e4982013-07-23 18:22:29 -07002731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002732 public void scheduleDateChangedEvent() {
2733 Calendar calendar = Calendar.getInstance();
2734 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07002735 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002736 calendar.set(Calendar.MINUTE, 0);
2737 calendar.set(Calendar.SECOND, 0);
2738 calendar.set(Calendar.MILLISECOND, 0);
2739 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07002740
2741 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002742 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
2743 AlarmManager.FLAG_STANDALONE, workSource, null,
2744 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002745 }
2746 }
2747
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002748 class InteractiveStateReceiver extends BroadcastReceiver {
2749 public InteractiveStateReceiver() {
2750 IntentFilter filter = new IntentFilter();
2751 filter.addAction(Intent.ACTION_SCREEN_OFF);
2752 filter.addAction(Intent.ACTION_SCREEN_ON);
2753 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
2754 getContext().registerReceiver(this, filter);
2755 }
2756
2757 @Override
2758 public void onReceive(Context context, Intent intent) {
2759 synchronized (mLock) {
2760 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
2761 }
2762 }
2763 }
2764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002765 class UninstallReceiver extends BroadcastReceiver {
2766 public UninstallReceiver() {
2767 IntentFilter filter = new IntentFilter();
2768 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2769 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002770 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002771 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08002772 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002773 // Register for events related to sdcard installation.
2774 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08002775 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002776 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002777 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002778 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002779 }
2780
2781 @Override
2782 public void onReceive(Context context, Intent intent) {
2783 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002784 String action = intent.getAction();
2785 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002786 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
2787 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
2788 for (String packageName : pkgList) {
2789 if (lookForPackageLocked(packageName)) {
2790 setResultCode(Activity.RESULT_OK);
2791 return;
2792 }
2793 }
2794 return;
2795 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002796 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002797 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
2798 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
2799 if (userHandle >= 0) {
2800 removeUserLocked(userHandle);
2801 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002802 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
2803 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
2804 if (uid >= 0) {
2805 mLastAllowWhileIdleDispatch.delete(uid);
2806 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002807 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08002808 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
2809 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
2810 // This package is being updated; don't kill its alarms.
2811 return;
2812 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002813 Uri data = intent.getData();
2814 if (data != null) {
2815 String pkg = data.getSchemeSpecificPart();
2816 if (pkg != null) {
2817 pkgList = new String[]{pkg};
2818 }
2819 }
2820 }
2821 if (pkgList != null && (pkgList.length > 0)) {
2822 for (String pkg : pkgList) {
2823 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07002824 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002825 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
2826 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
2827 if (uidStats.remove(pkg) != null) {
2828 if (uidStats.size() <= 0) {
2829 mBroadcastStats.removeAt(i);
2830 }
2831 }
2832 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002833 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002834 }
2835 }
2836 }
2837 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002838
2839 final class UidObserver extends IUidObserver.Stub {
Sudheer Shanka80255802017-03-04 14:48:53 -08002840 @Override public void onUidStateChanged(int uid, int procState,
2841 long procStateSeq) throws RemoteException {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002842 }
2843
Dianne Hackborne07641d2016-11-09 15:07:23 -08002844 @Override public void onUidGone(int uid, boolean disabled) throws RemoteException {
2845 if (disabled) {
2846 synchronized (mLock) {
2847 removeForStoppedLocked(uid);
2848 }
2849 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002850 }
2851
2852 @Override public void onUidActive(int uid) throws RemoteException {
2853 }
2854
Dianne Hackborne07641d2016-11-09 15:07:23 -08002855 @Override public void onUidIdle(int uid, boolean disabled) throws RemoteException {
2856 if (disabled) {
2857 synchronized (mLock) {
2858 removeForStoppedLocked(uid);
2859 }
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08002860 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002861 }
2862 };
2863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002864 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002865 String pkg = pi.getCreatorPackage();
2866 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002867 return getStatsLocked(uid, pkg);
2868 }
2869
2870 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002871 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
2872 if (uidStats == null) {
2873 uidStats = new ArrayMap<String, BroadcastStats>();
2874 mBroadcastStats.put(uid, uidStats);
2875 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002876 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002877 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002878 bs = new BroadcastStats(uid, pkgName);
2879 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002880 }
2881 return bs;
2882 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002883
Christopher Tate14a7bb02015-10-01 10:24:31 -07002884 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
2885 private InFlight removeLocked(PendingIntent pi, Intent intent) {
2886 for (int i = 0; i < mInFlight.size(); i++) {
2887 if (mInFlight.get(i).mPendingIntent == pi) {
2888 return mInFlight.remove(i);
2889 }
2890 }
2891 mLog.w("No in-flight alarm for " + pi + " " + intent);
2892 return null;
2893 }
2894
2895 private InFlight removeLocked(IBinder listener) {
2896 for (int i = 0; i < mInFlight.size(); i++) {
2897 if (mInFlight.get(i).mListener == listener) {
2898 return mInFlight.remove(i);
2899 }
2900 }
2901 mLog.w("No in-flight alarm for listener " + listener);
2902 return null;
2903 }
2904
2905 private void updateStatsLocked(InFlight inflight) {
2906 final long nowELAPSED = SystemClock.elapsedRealtime();
2907 BroadcastStats bs = inflight.mBroadcastStats;
2908 bs.nesting--;
2909 if (bs.nesting <= 0) {
2910 bs.nesting = 0;
2911 bs.aggregateTime += nowELAPSED - bs.startTime;
2912 }
2913 FilterStats fs = inflight.mFilterStats;
2914 fs.nesting--;
2915 if (fs.nesting <= 0) {
2916 fs.nesting = 0;
2917 fs.aggregateTime += nowELAPSED - fs.startTime;
2918 }
2919 if (RECORD_ALARMS_IN_HISTORY) {
2920 if (inflight.mWorkSource != null && inflight.mWorkSource.size() > 0) {
2921 for (int wi=0; wi<inflight.mWorkSource.size(); wi++) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002922 ActivityManager.noteAlarmFinish(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002923 inflight.mPendingIntent, inflight.mWorkSource.get(wi), inflight.mTag);
2924 }
2925 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002926 ActivityManager.noteAlarmFinish(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002927 inflight.mPendingIntent, inflight.mUid, inflight.mTag);
2928 }
2929 }
2930 }
2931
2932 private void updateTrackingLocked(InFlight inflight) {
2933 if (inflight != null) {
2934 updateStatsLocked(inflight);
2935 }
2936 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08002937 if (DEBUG_WAKELOCK) {
2938 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
2939 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002940 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002941 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002942 mWakeLock.release();
2943 if (mInFlight.size() > 0) {
2944 mLog.w("Finished all dispatches with " + mInFlight.size()
2945 + " remaining inflights");
2946 for (int i=0; i<mInFlight.size(); i++) {
2947 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
2948 }
2949 mInFlight.clear();
2950 }
2951 } else {
2952 // the next of our alarms is now in flight. reattribute the wakelock.
2953 if (mInFlight.size() > 0) {
2954 InFlight inFlight = mInFlight.get(0);
2955 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
2956 inFlight.mAlarmType, inFlight.mTag, -1, false);
2957 } else {
2958 // should never happen
2959 mLog.w("Alarm wakelock still held but sent queue empty");
2960 mWakeLock.setWorkSource(null);
2961 }
2962 }
2963 }
2964
2965 /**
2966 * Callback that arrives when a direct-call alarm reports that delivery has finished
2967 */
2968 @Override
2969 public void alarmComplete(IBinder who) {
2970 if (who == null) {
2971 Slog.w(TAG, "Invalid alarmComplete: uid=" + Binder.getCallingUid()
2972 + " pid=" + Binder.getCallingPid());
2973 return;
2974 }
2975
2976 final long ident = Binder.clearCallingIdentity();
2977 try {
2978 synchronized (mLock) {
2979 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
2980 InFlight inflight = removeLocked(who);
2981 if (inflight != null) {
2982 if (DEBUG_LISTENER_CALLBACK) {
2983 Slog.i(TAG, "alarmComplete() from " + who);
2984 }
2985 updateTrackingLocked(inflight);
2986 } else {
2987 // Delivery timed out, and the timeout handling already took care of
2988 // updating our tracking here, so we needn't do anything further.
2989 if (DEBUG_LISTENER_CALLBACK) {
2990 Slog.i(TAG, "Late alarmComplete() from " + who);
2991 }
2992 }
2993 }
2994 } finally {
2995 Binder.restoreCallingIdentity(ident);
2996 }
2997 }
2998
2999 /**
3000 * Callback that arrives when a PendingIntent alarm has finished delivery
3001 */
3002 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003003 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
3004 String resultData, Bundle resultExtras) {
3005 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003006 updateTrackingLocked(removeLocked(pi, intent));
3007 }
3008 }
3009
3010 /**
3011 * Timeout of a direct-call alarm delivery
3012 */
3013 public void alarmTimedOut(IBinder who) {
3014 synchronized (mLock) {
3015 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08003016 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003017 // TODO: implement ANR policy for the target
3018 if (DEBUG_LISTENER_CALLBACK) {
3019 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003020 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003021 updateTrackingLocked(inflight);
Dianne Hackborn81038902012-11-26 17:04:09 -08003022 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003023 if (DEBUG_LISTENER_CALLBACK) {
3024 Slog.i(TAG, "Spurious timeout of listener " + who);
3025 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003026 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003027 }
3028 }
3029
3030 /**
3031 * Deliver an alarm and set up the post-delivery handling appropriately
3032 */
3033 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
3034 if (alarm.operation != null) {
3035 // PendingIntent alarm
3036 try {
3037 alarm.operation.send(getContext(), 0,
3038 mBackgroundIntent.putExtra(
3039 Intent.EXTRA_ALARM_COUNT, alarm.count),
3040 mDeliveryTracker, mHandler, null,
3041 allowWhileIdle ? mIdleOptions : null);
3042 } catch (PendingIntent.CanceledException e) {
3043 if (alarm.repeatInterval > 0) {
3044 // This IntentSender is no longer valid, but this
3045 // is a repeating alarm, so toss it
3046 removeImpl(alarm.operation);
3047 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003048 // No actual delivery was possible, so the delivery tracker's
3049 // 'finished' callback won't be invoked. We also don't need
3050 // to do any wakelock or stats tracking, so we have nothing
3051 // left to do here but go on to the next thing.
3052 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003053 }
3054 } else {
3055 // Direct listener callback alarm
3056 try {
3057 if (DEBUG_LISTENER_CALLBACK) {
3058 Slog.v(TAG, "Alarm to uid=" + alarm.uid
3059 + " listener=" + alarm.listener.asBinder());
3060 }
3061 alarm.listener.doAlarm(this);
3062 mHandler.sendMessageDelayed(
3063 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
3064 alarm.listener.asBinder()),
3065 mConstants.LISTENER_TIMEOUT);
3066 } catch (Exception e) {
3067 if (DEBUG_LISTENER_CALLBACK) {
3068 Slog.i(TAG, "Alarm undeliverable to listener "
3069 + alarm.listener.asBinder(), e);
3070 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003071 // As in the PendingIntent.CanceledException case, delivery of the
3072 // alarm was not possible, so we have no wakelock or timeout or
3073 // stats management to do. It threw before we posted the delayed
3074 // timeout message, so we're done here.
3075 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003076 }
3077 }
3078
3079 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08003080 if (DEBUG_WAKELOCK) {
3081 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
3082 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003083 if (mBroadcastRefCount == 0) {
3084 setWakelockWorkSource(alarm.operation, alarm.workSource,
3085 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
3086 true);
3087 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003088 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003089 }
3090 final InFlight inflight = new InFlight(AlarmManagerService.this,
3091 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
3092 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
3093 mInFlight.add(inflight);
3094 mBroadcastRefCount++;
3095
3096 if (allowWhileIdle) {
3097 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
3098 mLastAllowWhileIdleDispatch.put(alarm.uid, nowELAPSED);
3099 if (RECORD_DEVICE_IDLE_ALARMS) {
3100 IdleDispatchEntry ent = new IdleDispatchEntry();
3101 ent.uid = alarm.uid;
3102 ent.pkg = alarm.packageName;
3103 ent.tag = alarm.statsTag;
3104 ent.op = "DELIVER";
3105 ent.elapsedRealtime = nowELAPSED;
3106 mAllowWhileIdleDispatches.add(ent);
3107 }
3108 }
3109
3110 final BroadcastStats bs = inflight.mBroadcastStats;
3111 bs.count++;
3112 if (bs.nesting == 0) {
3113 bs.nesting = 1;
3114 bs.startTime = nowELAPSED;
3115 } else {
3116 bs.nesting++;
3117 }
3118 final FilterStats fs = inflight.mFilterStats;
3119 fs.count++;
3120 if (fs.nesting == 0) {
3121 fs.nesting = 1;
3122 fs.startTime = nowELAPSED;
3123 } else {
3124 fs.nesting++;
3125 }
3126 if (alarm.type == ELAPSED_REALTIME_WAKEUP
3127 || alarm.type == RTC_WAKEUP) {
3128 bs.numWakeup++;
3129 fs.numWakeup++;
3130 if (alarm.workSource != null && alarm.workSource.size() > 0) {
3131 for (int wi=0; wi<alarm.workSource.size(); wi++) {
Christopher Tate0029f572016-06-14 10:16:28 -07003132 final String wsName = alarm.workSource.getName(wi);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003133 ActivityManager.noteWakeupAlarm(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003134 alarm.operation, alarm.workSource.get(wi),
Christopher Tate0029f572016-06-14 10:16:28 -07003135 (wsName != null) ? wsName : alarm.packageName,
3136 alarm.statsTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08003137 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003138 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003139 ActivityManager.noteWakeupAlarm(
Joe Onorato78bcdf92016-05-09 10:10:29 -07003140 alarm.operation, alarm.uid, alarm.packageName, alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003141 }
3142 }
3143 }
3144 }
3145}