blob: c6af2903453cf7ac28783ead6a51471941650d33 [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
Dianne Hackborn81038902012-11-26 17:04:09 -080083import com.android.internal.util.LocalLog;
84
Adam Lesinski182f73f2013-12-05 16:48:06 -080085class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -070086 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
87 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -080088 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -070089 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -080090 static final int TIME_CHANGED_MASK = 1 << 16;
91 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -080092
Christopher Tatee0a22b32013-07-11 14:43:13 -070093 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -080094 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -080095
Adam Lesinski182f73f2013-12-05 16:48:06 -080096 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -080097 static final boolean localLOGV = false;
98 static final boolean DEBUG_BATCH = localLOGV || false;
99 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200100 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700101 static final boolean DEBUG_LISTENER_CALLBACK = localLOGV || false;
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800102 static final boolean DEBUG_WAKELOCK = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700103 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700104 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800105 static final int ALARM_EVENT = 1;
106 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200107
Christopher Tate14a7bb02015-10-01 10:24:31 -0700108 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800110 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111
Adam Lesinski182f73f2013-12-05 16:48:06 -0800112 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700113
Christopher Tate24cd46f2016-02-02 14:28:01 -0800114 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT =
115 new Intent(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED)
116 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Adrian Roosc42a1e12014-07-07 23:35:53 +0200117
Adam Lesinski182f73f2013-12-05 16:48:06 -0800118 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800119
Christopher Tate14a7bb02015-10-01 10:24:31 -0700120 AppOpsManager mAppOps;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800121 DeviceIdleController.LocalService mLocalDeviceIdleController;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700122
Adam Lesinski182f73f2013-12-05 16:48:06 -0800123 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800124
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800125 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800126 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700127 private long mNextNonWakeup;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -0700128 private long mLastWakeupSet;
129 private long mLastWakeup;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800130 int mBroadcastRefCount = 0;
131 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700132 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700133 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
134 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800135 final AlarmHandler mHandler = new AlarmHandler();
136 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700137 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700139 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800140 PendingIntent mTimeTickSender;
141 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700142 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700143 boolean mInteractive = true;
144 long mNonInteractiveStartTime;
145 long mNonInteractiveTime;
146 long mLastAlarmDeliveryTime;
147 long mStartCurrentDelayTime;
148 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700149 long mLastTimeChangeClockTime;
150 long mLastTimeChangeRealtime;
Dianne Hackborna750a632015-06-16 17:18:23 -0700151 long mAllowWhileIdleMinTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700152 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800153
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700154 /**
Dianne Hackborn262ae5c2016-02-10 16:28:29 -0800155 * The current set of user whitelisted apps for device idle mode, meaning these are allowed
156 * to freely schedule alarms.
157 */
158 int[] mDeviceIdleUserWhitelist = new int[0];
159
160 /**
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700161 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
162 * used to determine the earliest we can dispatch the next such alarm.
163 */
164 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
165
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700166 final static class IdleDispatchEntry {
167 int uid;
168 String pkg;
169 String tag;
170 String op;
171 long elapsedRealtime;
172 long argRealtime;
173 }
174 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
175
Dianne Hackborna750a632015-06-16 17:18:23 -0700176 /**
177 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
178 */
179 Bundle mIdleOptions;
180
Jose Lima235510e2014-08-13 12:50:01 -0700181 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
182 new SparseArray<>();
183 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
184 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200185 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
186 new SparseBooleanArray();
187 private boolean mNextAlarmClockMayChange;
188
189 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700190 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
191 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200192
Dianne Hackborna750a632015-06-16 17:18:23 -0700193 /**
194 * All times are in milliseconds. These constants are kept synchronized with the system
195 * global Settings. Any access to this class or its fields should be done while
196 * holding the AlarmManagerService.mLock lock.
197 */
198 private final class Constants extends ContentObserver {
199 // Key names stored in the settings value.
200 private static final String KEY_MIN_FUTURITY = "min_futurity";
201 private static final String KEY_MIN_INTERVAL = "min_interval";
202 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
203 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
204 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
205 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700206 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Dianne Hackborna750a632015-06-16 17:18:23 -0700207
208 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
209 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tateaa244da2015-08-27 15:57:57 -0700210 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700211 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700212 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
213
Christopher Tate14a7bb02015-10-01 10:24:31 -0700214 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
215
Dianne Hackborna750a632015-06-16 17:18:23 -0700216 // Minimum futurity of a new alarm
217 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
218
219 // Minimum alarm recurrence interval
220 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
221
222 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
223 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
224
225 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
226 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
227
228 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
229 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
230 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
231
Christopher Tate14a7bb02015-10-01 10:24:31 -0700232 // Direct alarm listener callback timeout
233 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
234
Dianne Hackborna750a632015-06-16 17:18:23 -0700235 private ContentResolver mResolver;
236 private final KeyValueListParser mParser = new KeyValueListParser(',');
237 private long mLastAllowWhileIdleWhitelistDuration = -1;
238
239 public Constants(Handler handler) {
240 super(handler);
241 updateAllowWhileIdleMinTimeLocked();
242 updateAllowWhileIdleWhitelistDurationLocked();
243 }
244
245 public void start(ContentResolver resolver) {
246 mResolver = resolver;
247 mResolver.registerContentObserver(Settings.Global.getUriFor(
248 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
249 updateConstants();
250 }
251
252 public void updateAllowWhileIdleMinTimeLocked() {
253 mAllowWhileIdleMinTime = mPendingIdleUntil != null
254 ? ALLOW_WHILE_IDLE_LONG_TIME : ALLOW_WHILE_IDLE_SHORT_TIME;
255 }
256
257 public void updateAllowWhileIdleWhitelistDurationLocked() {
258 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
259 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
260 BroadcastOptions opts = BroadcastOptions.makeBasic();
261 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
262 mIdleOptions = opts.toBundle();
263 }
264 }
265
266 @Override
267 public void onChange(boolean selfChange, Uri uri) {
268 updateConstants();
269 }
270
271 private void updateConstants() {
272 synchronized (mLock) {
273 try {
274 mParser.setString(Settings.Global.getString(mResolver,
275 Settings.Global.ALARM_MANAGER_CONSTANTS));
276 } catch (IllegalArgumentException e) {
277 // Failed to parse the settings string, log this and move on
278 // with defaults.
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800279 Slog.e(TAG, "Bad alarm manager settings", e);
Dianne Hackborna750a632015-06-16 17:18:23 -0700280 }
281
282 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
283 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
284 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
285 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
286 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
287 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
288 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
289 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
290 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700291 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
292 DEFAULT_LISTENER_TIMEOUT);
Dianne Hackborna750a632015-06-16 17:18:23 -0700293
294 updateAllowWhileIdleMinTimeLocked();
295 updateAllowWhileIdleWhitelistDurationLocked();
296 }
297 }
298
299 void dump(PrintWriter pw) {
300 pw.println(" Settings:");
301
302 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
303 TimeUtils.formatDuration(MIN_FUTURITY, pw);
304 pw.println();
305
306 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
307 TimeUtils.formatDuration(MIN_INTERVAL, pw);
308 pw.println();
309
Christopher Tate14a7bb02015-10-01 10:24:31 -0700310 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
311 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
312 pw.println();
313
Dianne Hackborna750a632015-06-16 17:18:23 -0700314 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
315 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
316 pw.println();
317
318 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
319 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
320 pw.println();
321
322 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
323 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
324 pw.println();
325 }
326 }
327
328 final Constants mConstants;
329
Christopher Tate1590f1e2014-10-02 17:27:57 -0700330 // Alarm delivery ordering bookkeeping
331 static final int PRIO_TICK = 0;
332 static final int PRIO_WAKEUP = 1;
333 static final int PRIO_NORMAL = 2;
334
Dianne Hackborna750a632015-06-16 17:18:23 -0700335 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700336 int seq;
337 int priority;
338
339 PriorityClass() {
340 seq = mCurrentSeq - 1;
341 priority = PRIO_NORMAL;
342 }
343 }
344
Dianne Hackborna750a632015-06-16 17:18:23 -0700345 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700346 int mCurrentSeq = 0;
347
Dianne Hackborna750a632015-06-16 17:18:23 -0700348 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700349 public long when;
350 public int uid;
351 public String action;
352
353 public WakeupEvent(long theTime, int theUid, String theAction) {
354 when = theTime;
355 uid = theUid;
356 action = theAction;
357 }
358 }
359
Adam Lesinski182f73f2013-12-05 16:48:06 -0800360 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
361 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700362
Adrian Roosc42a1e12014-07-07 23:35:53 +0200363 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700364 long start; // These endpoints are always in ELAPSED
365 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700366 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700367
368 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
369
370 Batch() {
371 start = 0;
372 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700373 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700374 }
375
376 Batch(Alarm seed) {
377 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700378 end = seed.maxWhenElapsed;
379 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700380 alarms.add(seed);
381 }
382
383 int size() {
384 return alarms.size();
385 }
386
387 Alarm get(int index) {
388 return alarms.get(index);
389 }
390
391 boolean canHold(long whenElapsed, long maxWhen) {
392 return (end >= whenElapsed) && (start <= maxWhen);
393 }
394
395 boolean add(Alarm alarm) {
396 boolean newStart = false;
397 // narrows the batch if necessary; presumes that canHold(alarm) is true
398 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
399 if (index < 0) {
400 index = 0 - index - 1;
401 }
402 alarms.add(index, alarm);
403 if (DEBUG_BATCH) {
404 Slog.v(TAG, "Adding " + alarm + " to " + this);
405 }
406 if (alarm.whenElapsed > start) {
407 start = alarm.whenElapsed;
408 newStart = true;
409 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700410 if (alarm.maxWhenElapsed < end) {
411 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700412 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700413 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700414
415 if (DEBUG_BATCH) {
416 Slog.v(TAG, " => now " + this);
417 }
418 return newStart;
419 }
420
Christopher Tate14a7bb02015-10-01 10:24:31 -0700421 boolean remove(final PendingIntent operation, final IAlarmListener listener) {
422 if (operation == null && listener == null) {
423 if (localLOGV) {
424 Slog.w(TAG, "requested remove() of null operation",
425 new RuntimeException("here"));
426 }
427 return false;
428 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700429 boolean didRemove = false;
430 long newStart = 0; // recalculate endpoints as we go
431 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700432 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700433 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700434 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700435 if (alarm.matches(operation, listener)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700436 alarms.remove(i);
437 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200438 if (alarm.alarmClock != null) {
439 mNextAlarmClockMayChange = true;
440 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700441 } else {
442 if (alarm.whenElapsed > newStart) {
443 newStart = alarm.whenElapsed;
444 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700445 if (alarm.maxWhenElapsed < newEnd) {
446 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700447 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700448 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700449 i++;
450 }
451 }
452 if (didRemove) {
453 // commit the new batch bounds
454 start = newStart;
455 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700456 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700457 }
458 return didRemove;
459 }
460
461 boolean remove(final String packageName) {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700462 if (packageName == null) {
463 if (localLOGV) {
464 Slog.w(TAG, "requested remove() of null packageName",
465 new RuntimeException("here"));
466 }
467 return false;
468 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700469 boolean didRemove = false;
470 long newStart = 0; // recalculate endpoints as we go
471 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700472 int newFlags = 0;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700473 for (int i = alarms.size()-1; i >= 0; i--) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700474 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700475 if (alarm.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700476 alarms.remove(i);
477 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200478 if (alarm.alarmClock != null) {
479 mNextAlarmClockMayChange = true;
480 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700481 } else {
482 if (alarm.whenElapsed > newStart) {
483 newStart = alarm.whenElapsed;
484 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700485 if (alarm.maxWhenElapsed < newEnd) {
486 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700487 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700488 newFlags |= alarm.flags;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700489 }
490 }
491 if (didRemove) {
492 // commit the new batch bounds
493 start = newStart;
494 end = newEnd;
495 flags = newFlags;
496 }
497 return didRemove;
498 }
499
500 boolean removeForStopped(final int uid) {
501 boolean didRemove = false;
502 long newStart = 0; // recalculate endpoints as we go
503 long newEnd = Long.MAX_VALUE;
504 int newFlags = 0;
505 for (int i = alarms.size()-1; i >= 0; i--) {
506 Alarm alarm = alarms.get(i);
507 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800508 if (alarm.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
509 uid, alarm.packageName)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700510 alarms.remove(i);
511 didRemove = true;
512 if (alarm.alarmClock != null) {
513 mNextAlarmClockMayChange = true;
514 }
515 } else {
516 if (alarm.whenElapsed > newStart) {
517 newStart = alarm.whenElapsed;
518 }
519 if (alarm.maxWhenElapsed < newEnd) {
520 newEnd = alarm.maxWhenElapsed;
521 }
522 newFlags |= alarm.flags;
523 }
524 } catch (RemoteException e) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700525 }
526 }
527 if (didRemove) {
528 // commit the new batch bounds
529 start = newStart;
530 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700531 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700532 }
533 return didRemove;
534 }
535
536 boolean remove(final int userHandle) {
537 boolean didRemove = false;
538 long newStart = 0; // recalculate endpoints as we go
539 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700540 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700541 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700542 if (UserHandle.getUserId(alarm.creatorUid) == userHandle) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700543 alarms.remove(i);
544 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200545 if (alarm.alarmClock != null) {
546 mNextAlarmClockMayChange = true;
547 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700548 } else {
549 if (alarm.whenElapsed > newStart) {
550 newStart = alarm.whenElapsed;
551 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700552 if (alarm.maxWhenElapsed < newEnd) {
553 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700554 }
555 i++;
556 }
557 }
558 if (didRemove) {
559 // commit the new batch bounds
560 start = newStart;
561 end = newEnd;
562 }
563 return didRemove;
564 }
565
566 boolean hasPackage(final String packageName) {
567 final int N = alarms.size();
568 for (int i = 0; i < N; i++) {
569 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700570 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700571 return true;
572 }
573 }
574 return false;
575 }
576
577 boolean hasWakeups() {
578 final int N = alarms.size();
579 for (int i = 0; i < N; i++) {
580 Alarm a = alarms.get(i);
581 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
582 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
583 return true;
584 }
585 }
586 return false;
587 }
588
589 @Override
590 public String toString() {
591 StringBuilder b = new StringBuilder(40);
592 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
593 b.append(" num="); b.append(size());
594 b.append(" start="); b.append(start);
595 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700596 if (flags != 0) {
597 b.append(" flgs=0x");
598 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700599 }
600 b.append('}');
601 return b.toString();
602 }
603 }
604
605 static class BatchTimeOrder implements Comparator<Batch> {
606 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800607 long when1 = b1.start;
608 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800609 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700610 return 1;
611 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800612 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700613 return -1;
614 }
615 return 0;
616 }
617 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800618
619 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
620 @Override
621 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700622 // priority class trumps everything. TICK < WAKEUP < NORMAL
623 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
624 return -1;
625 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
626 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800627 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700628
629 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800630 if (lhs.whenElapsed < rhs.whenElapsed) {
631 return -1;
632 } else if (lhs.whenElapsed > rhs.whenElapsed) {
633 return 1;
634 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700635
636 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800637 return 0;
638 }
639 };
640
Christopher Tate1590f1e2014-10-02 17:27:57 -0700641 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
642 final int N = alarms.size();
643 for (int i = 0; i < N; i++) {
644 Alarm a = alarms.get(i);
645
646 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700647 if (a.operation != null
648 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700649 alarmPrio = PRIO_TICK;
650 } else if (a.wakeup) {
651 alarmPrio = PRIO_WAKEUP;
652 } else {
653 alarmPrio = PRIO_NORMAL;
654 }
655
656 PriorityClass packagePrio = a.priorityClass;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700657 String alarmPackage = (a.operation != null)
658 ? a.operation.getCreatorPackage()
659 : a.packageName;
660 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700661 if (packagePrio == null) {
662 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700663 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700664 }
665 a.priorityClass = packagePrio;
666
667 if (packagePrio.seq != mCurrentSeq) {
668 // first alarm we've seen in the current delivery generation from this package
669 packagePrio.priority = alarmPrio;
670 packagePrio.seq = mCurrentSeq;
671 } else {
672 // Multiple alarms from this package being delivered in this generation;
673 // bump the package's delivery class if it's warranted.
674 // TICK < WAKEUP < NORMAL
675 if (alarmPrio < packagePrio.priority) {
676 packagePrio.priority = alarmPrio;
677 }
678 }
679 }
680 }
681
Christopher Tatee0a22b32013-07-11 14:43:13 -0700682 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800683 static final long MIN_FUZZABLE_INTERVAL = 10000;
684 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700685 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
686
687 // set to null if in idle mode; while in this mode, any alarms we don't want
688 // to run during this time are placed in mPendingWhileIdleAlarms
689 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700690 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700691 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700692
Jeff Brownb880d882014-02-10 19:47:07 -0800693 public AlarmManagerService(Context context) {
694 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700695 mConstants = new Constants(mHandler);
Jeff Brownb880d882014-02-10 19:47:07 -0800696 }
697
Christopher Tatee0a22b32013-07-11 14:43:13 -0700698 static long convertToElapsed(long when, int type) {
699 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
700 if (isRtc) {
701 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
702 }
703 return when;
704 }
705
706 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
707 // calculate the end of our nominal delivery window for the alarm.
708 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
709 // Current heuristic: batchable window is 75% of either the recurrence interval
710 // [for a periodic alarm] or of the time from now to the desired delivery time,
711 // with a minimum delay/interval of 10 seconds, under which we will simply not
712 // defer the alarm.
713 long futurity = (interval == 0)
714 ? (triggerAtTime - now)
715 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700716 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700717 futurity = 0;
718 }
719 return triggerAtTime + (long)(.75 * futurity);
720 }
721
722 // returns true if the batch was added at the head
723 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
724 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
725 if (index < 0) {
726 index = 0 - index - 1;
727 }
728 list.add(index, newBatch);
729 return (index == 0);
730 }
731
Christopher Tate385e4982013-07-23 18:22:29 -0700732 // Return the index of the matching batch, or -1 if none found.
733 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700734 final int N = mAlarmBatches.size();
735 for (int i = 0; i < N; i++) {
736 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700737 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700738 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700739 }
740 }
Christopher Tate385e4982013-07-23 18:22:29 -0700741 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700742 }
743
744 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
745 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700746 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700747 rebatchAllAlarmsLocked(true);
748 }
749 }
750
751 void rebatchAllAlarmsLocked(boolean doValidate) {
752 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
753 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700754 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700755 final long nowElapsed = SystemClock.elapsedRealtime();
756 final int oldBatches = oldSet.size();
757 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
758 Batch batch = oldSet.get(batchNum);
759 final int N = batch.size();
760 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700761 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700762 }
763 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700764 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
765 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
766 + " to " + mPendingIdleUntil);
767 if (mPendingIdleUntil == null) {
768 // Somehow we lost this... we need to restore all of the pending alarms.
769 restorePendingWhileIdleAlarmsLocked();
770 }
771 }
772 rescheduleKernelAlarmsLocked();
773 updateNextAlarmClockLocked();
774 }
775
776 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
777 a.when = a.origWhen;
778 long whenElapsed = convertToElapsed(a.when, a.type);
779 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700780 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700781 // Exact
782 maxElapsed = whenElapsed;
783 } else {
784 // Not exact. Preserve any explicit window, otherwise recalculate
785 // the window based on the alarm's new futurity. Note that this
786 // reflects a policy of preferring timely to deferred delivery.
787 maxElapsed = (a.windowLength > 0)
788 ? (whenElapsed + a.windowLength)
789 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
790 }
791 a.whenElapsed = whenElapsed;
792 a.maxWhenElapsed = maxElapsed;
793 setImplLocked(a, true, doValidate);
794 }
795
796 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700797 if (RECORD_DEVICE_IDLE_ALARMS) {
798 IdleDispatchEntry ent = new IdleDispatchEntry();
799 ent.uid = 0;
800 ent.pkg = "FINISH IDLE";
801 ent.elapsedRealtime = SystemClock.elapsedRealtime();
802 mAllowWhileIdleDispatches.add(ent);
803 }
804
Dianne Hackborn35d54032015-04-23 10:30:43 -0700805 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700806 if (mPendingWhileIdleAlarms.size() > 0) {
807 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
808 mPendingWhileIdleAlarms = new ArrayList<>();
809 final long nowElapsed = SystemClock.elapsedRealtime();
810 for (int i=alarms.size() - 1; i >= 0; i--) {
811 Alarm a = alarms.get(i);
812 reAddAlarmLocked(a, nowElapsed, false);
813 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700814 }
Dianne Hackborn35d54032015-04-23 10:30:43 -0700815
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700816 // Make sure we are using the correct ALLOW_WHILE_IDLE min time.
Dianne Hackborna750a632015-06-16 17:18:23 -0700817 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700818
Dianne Hackborn35d54032015-04-23 10:30:43 -0700819 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700820 rescheduleKernelAlarmsLocked();
821 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -0700822
823 // And send a TIME_TICK right now, since it is important to get the UI updated.
824 try {
825 mTimeTickSender.send();
826 } catch (PendingIntent.CanceledException e) {
827 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700828 }
829
Christopher Tate14a7bb02015-10-01 10:24:31 -0700830 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -0800831 final PendingIntent mPendingIntent;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700832 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -0700833 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700834 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700835 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800836 final BroadcastStats mBroadcastStats;
837 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800838 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800839
Christopher Tate14a7bb02015-10-01 10:24:31 -0700840 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
841 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
842 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800843 mPendingIntent = pendingIntent;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700844 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -0700845 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700846 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700847 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700848 mBroadcastStats = (pendingIntent != null)
849 ? service.getStatsLocked(pendingIntent)
850 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700851 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -0800852 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700853 fs = new FilterStats(mBroadcastStats, mTag);
854 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -0800855 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700856 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -0800857 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800858 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800859 }
Makoto Onuki33955e12017-03-01 18:11:00 -0800860
861 @Override
862 public String toString() {
863 return "InFlight{"
864 + "pendingIntent=" + mPendingIntent
865 + ", workSource=" + mWorkSource
866 + ", uid=" + mUid
867 + ", tag=" + mTag
868 + ", broadcastStats=" + mBroadcastStats
869 + ", filterStats=" + mFilterStats
870 + ", alarmType=" + mAlarmType
871 + "}";
872 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800874
Adam Lesinski182f73f2013-12-05 16:48:06 -0800875 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -0800876 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700877 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800878
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700879 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800881 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 int numWakeup;
883 long startTime;
884 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -0800885
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700886 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800887 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700888 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800889 }
Makoto Onuki33955e12017-03-01 18:11:00 -0800890
891 @Override
892 public String toString() {
893 return "FilterStats{"
894 + "tag=" + mTag
895 + ", lastTime=" + lastTime
896 + ", aggregateTime=" + aggregateTime
897 + ", count=" + count
898 + ", numWakeup=" + numWakeup
899 + ", startTime=" + startTime
900 + ", nesting=" + nesting
901 + "}";
902 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800903 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700904
Adam Lesinski182f73f2013-12-05 16:48:06 -0800905 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800906 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800907 final String mPackageName;
908
909 long aggregateTime;
910 int count;
911 int numWakeup;
912 long startTime;
913 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700914 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -0800915
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800916 BroadcastStats(int uid, String packageName) {
917 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800918 mPackageName = packageName;
919 }
Makoto Onuki33955e12017-03-01 18:11:00 -0800920
921 @Override
922 public String toString() {
923 return "BroadcastStats{"
924 + "uid=" + mUid
925 + ", packageName=" + mPackageName
926 + ", aggregateTime=" + aggregateTime
927 + ", count=" + count
928 + ", numWakeup=" + numWakeup
929 + ", startTime=" + startTime
930 + ", nesting=" + nesting
931 + "}";
932 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700934
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800935 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
936 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700937
938 int mNumDelayedAlarms = 0;
939 long mTotalDelayTime = 0;
940 long mMaxDelayTime = 0;
941
Adam Lesinski182f73f2013-12-05 16:48:06 -0800942 @Override
943 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800944 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800945 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800946
947 // We have to set current TimeZone info to kernel
948 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -0800949 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800950
Adam Lesinski182f73f2013-12-05 16:48:06 -0800951 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800952 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800953
Adam Lesinski182f73f2013-12-05 16:48:06 -0800954 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700956 Intent.FLAG_RECEIVER_REGISTERED_ONLY
Chad Brubaker291df4f2017-03-14 10:23:02 -0700957 | Intent.FLAG_RECEIVER_FOREGROUND
958 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700959 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800960 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -0700961 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
962 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800963 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700964 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965
966 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -0800967 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 mClockReceiver.scheduleTimeTickEvent();
969 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700970 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971 mUninstallReceiver = new UninstallReceiver();
972
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800973 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800974 AlarmThread waitThread = new AlarmThread();
975 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800977 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800979
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700980 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800981 ActivityManager.getService().registerUidObserver(new UidObserver(),
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800982 ActivityManager.UID_OBSERVER_IDLE, ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700983 } catch (RemoteException e) {
984 // ignored; both services live in system_server
985 }
986
Adam Lesinski182f73f2013-12-05 16:48:06 -0800987 publishBinderService(Context.ALARM_SERVICE, mService);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -0800988 publishLocalService(LocalService.class, new LocalService());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800990
991 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -0700992 public void onBootPhase(int phase) {
993 if (phase == PHASE_SYSTEM_SERVICES_READY) {
994 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -0700995 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800996 mLocalDeviceIdleController
997 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackborna750a632015-06-16 17:18:23 -0700998 }
999 }
1000
1001 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002 protected void finalize() throws Throwable {
1003 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001004 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 } finally {
1006 super.finalize();
1007 }
1008 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001009
Adam Lesinski182f73f2013-12-05 16:48:06 -08001010 void setTimeZoneImpl(String tz) {
1011 if (TextUtils.isEmpty(tz)) {
1012 return;
David Christieebe51fc2013-07-26 13:23:29 -07001013 }
1014
Adam Lesinski182f73f2013-12-05 16:48:06 -08001015 TimeZone zone = TimeZone.getTimeZone(tz);
1016 // Prevent reentrant calls from stepping on each other when writing
1017 // the time zone property
1018 boolean timeZoneWasChanged = false;
1019 synchronized (this) {
1020 String current = SystemProperties.get(TIMEZONE_PROPERTY);
1021 if (current == null || !current.equals(zone.getID())) {
1022 if (localLOGV) {
1023 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
1024 }
1025 timeZoneWasChanged = true;
1026 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
1027 }
1028
1029 // Update the kernel timezone information
1030 // Kernel tracks time offsets as 'minutes west of GMT'
1031 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001032 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001033 }
1034
1035 TimeZone.setDefault(null);
1036
1037 if (timeZoneWasChanged) {
1038 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001039 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1040 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001041 intent.putExtra("time-zone", zone.getID());
1042 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1043 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001045
Adam Lesinski182f73f2013-12-05 16:48:06 -08001046 void removeImpl(PendingIntent operation) {
1047 if (operation == null) {
1048 return;
1049 }
1050 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001051 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001052 }
1053 }
1054
1055 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001056 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1057 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1058 int callingUid, String callingPackage) {
1059 // must be *either* PendingIntent or AlarmReceiver, but not both
1060 if ((operation == null && directReceiver == null)
1061 || (operation != null && directReceiver != null)) {
1062 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1063 // NB: previous releases failed silently here, so we are continuing to do the same
1064 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 return;
1066 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001067
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001068 // Sanity check the window length. This will catch people mistakenly
1069 // trying to pass an end-of-window timestamp rather than a duration.
1070 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1071 Slog.w(TAG, "Window length " + windowLength
1072 + "ms suspiciously long; limiting to 1 hour");
1073 windowLength = AlarmManager.INTERVAL_HOUR;
1074 }
1075
Christopher Tate498c6cb2014-11-17 16:09:27 -08001076 // Sanity check the recurrence interval. This will catch people who supply
1077 // seconds when the API expects milliseconds.
Dianne Hackborna750a632015-06-16 17:18:23 -07001078 final long minInterval = mConstants.MIN_INTERVAL;
1079 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001080 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001081 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001082 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001083 interval = minInterval;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001084 }
1085
Christopher Tatee0a22b32013-07-11 14:43:13 -07001086 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1087 throw new IllegalArgumentException("Invalid alarm type " + type);
1088 }
1089
Christopher Tate5f221e82013-07-30 17:13:15 -07001090 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001091 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001092 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001093 + " pid=" + what);
1094 triggerAtTime = 0;
1095 }
1096
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001097 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001098 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1099 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001100 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001101 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1102
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001103 final long maxElapsed;
1104 if (windowLength == AlarmManager.WINDOW_EXACT) {
1105 maxElapsed = triggerElapsed;
1106 } else if (windowLength < 0) {
1107 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001108 // Fix this window in place, so that as time approaches we don't collapse it.
1109 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001110 } else {
1111 maxElapsed = triggerElapsed + windowLength;
1112 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001114 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001115 if (DEBUG_BATCH) {
1116 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001117 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001118 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001119 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001121 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001122 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1123 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 }
1125 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126
Christopher Tate3e04b472013-10-21 17:51:31 -07001127 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001128 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1129 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1130 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001131 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001132 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1133 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001134 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001135 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001136 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1137 + " -- package not allowed to start");
1138 return;
1139 }
1140 } catch (RemoteException e) {
1141 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001142 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001143 setImplLocked(a, false, doValidate);
1144 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001145
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001146 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1147 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001148 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001149 // The caller has given the time they want this to happen at, however we need
1150 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001151 // bring us out of idle at an earlier time.
1152 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001153 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001154 }
1155 // Add fuzz to make the alarm go off some time before the actual desired time.
1156 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001157 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001158 if (fuzz > 0) {
1159 if (mRandom == null) {
1160 mRandom = new Random();
1161 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001162 final int delta = mRandom.nextInt(fuzz);
1163 a.whenElapsed -= delta;
1164 if (false) {
1165 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1166 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1167 Slog.d(TAG, "Applied fuzz: " + fuzz);
1168 Slog.d(TAG, "Final delta: " + delta);
1169 Slog.d(TAG, "Final when: " + a.whenElapsed);
1170 }
1171 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001172 }
1173
1174 } else if (mPendingIdleUntil != null) {
1175 // We currently have an idle until alarm scheduled; if the new alarm has
1176 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001177 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1178 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1179 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001180 == 0) {
1181 mPendingWhileIdleAlarms.add(a);
1182 return;
1183 }
1184 }
1185
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001186 if (RECORD_DEVICE_IDLE_ALARMS) {
1187 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1188 IdleDispatchEntry ent = new IdleDispatchEntry();
1189 ent.uid = a.uid;
1190 ent.pkg = a.operation.getCreatorPackage();
1191 ent.tag = a.operation.getTag("");
1192 ent.op = "SET";
1193 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1194 ent.argRealtime = a.whenElapsed;
1195 mAllowWhileIdleDispatches.add(ent);
1196 }
1197 }
1198
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001199 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
1200 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -07001201 if (whichBatch < 0) {
1202 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001203 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204 } else {
Christopher Tate385e4982013-07-23 18:22:29 -07001205 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001206 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001207 // The start time of this batch advanced, so batch ordering may
1208 // have just been broken. Move it to where it now belongs.
1209 mAlarmBatches.remove(whichBatch);
1210 addBatchLocked(mAlarmBatches, batch);
1211 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 }
1213
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001214 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001215 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001216 }
1217
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001218 boolean needRebatch = false;
1219
1220 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001221 if (RECORD_DEVICE_IDLE_ALARMS) {
1222 if (mPendingIdleUntil == null) {
1223 IdleDispatchEntry ent = new IdleDispatchEntry();
1224 ent.uid = 0;
1225 ent.pkg = "START IDLE";
1226 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1227 mAllowWhileIdleDispatches.add(ent);
1228 }
1229 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001230 mPendingIdleUntil = a;
Dianne Hackborna750a632015-06-16 17:18:23 -07001231 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001232 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001233 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1234 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1235 mNextWakeFromIdle = a;
1236 // If this wake from idle is earlier than whatever was previously scheduled,
1237 // and we are currently idling, then we need to rebatch alarms in case the idle
1238 // until time needs to be updated.
1239 if (mPendingIdleUntil != null) {
1240 needRebatch = true;
1241 }
1242 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001243 }
1244
1245 if (!rebatching) {
1246 if (DEBUG_VALIDATE) {
1247 if (doValidate && !validateConsistencyLocked()) {
1248 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1249 + " when(hex)=" + Long.toHexString(a.when)
1250 + " whenElapsed=" + a.whenElapsed
1251 + " maxWhenElapsed=" + a.maxWhenElapsed
1252 + " interval=" + a.repeatInterval + " op=" + a.operation
1253 + " flags=0x" + Integer.toHexString(a.flags));
1254 rebatchAllAlarmsLocked(false);
1255 needRebatch = false;
1256 }
1257 }
1258
1259 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001260 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001261 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001262
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001263 rescheduleKernelAlarmsLocked();
1264 updateNextAlarmClockLocked();
1265 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001266 }
1267
Adam Lesinski182f73f2013-12-05 16:48:06 -08001268 private final IBinder mService = new IAlarmManager.Stub() {
1269 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001270 public void set(String callingPackage,
1271 int type, long triggerAtTime, long windowLength, long interval, int flags,
1272 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1273 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001274 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001275
1276 // make sure the caller is not lying about which package should be blamed for
1277 // wakelock time spent in alarm delivery
1278 mAppOps.checkPackage(callingUid, callingPackage);
1279
1280 // Repeating alarms must use PendingIntent, not direct listener
1281 if (interval != 0) {
1282 if (directReceiver != null) {
1283 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1284 }
1285 }
1286
Adam Lesinski182f73f2013-12-05 16:48:06 -08001287 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001288 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001289 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001290 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001291 }
1292
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001293 // No incoming callers can request either WAKE_FROM_IDLE or
1294 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1295 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1296 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1297
1298 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1299 // manager when to come out of idle mode, which is only for DeviceIdleController.
1300 if (callingUid != Process.SYSTEM_UID) {
1301 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1302 }
1303
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001304 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001305 if (windowLength == AlarmManager.WINDOW_EXACT) {
1306 flags |= AlarmManager.FLAG_STANDALONE;
1307 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001308
1309 // If this alarm is for an alarm clock, then it must be standalone and we will
1310 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001311 if (alarmClock != null) {
1312 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001313
1314 // If the caller is a core system component or on the user's whitelist, and not calling
1315 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1316 // This means we will allow these alarms to go off as normal even while idle, with no
1317 // timing restrictions.
1318 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
1319 || Arrays.binarySearch(mDeviceIdleUserWhitelist,
1320 UserHandle.getAppId(callingUid)) >= 0)) {
1321 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1322 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001323 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001324
Christopher Tate14a7bb02015-10-01 10:24:31 -07001325 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1326 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001327 }
Christopher Tate89779822012-08-31 14:40:03 -07001328
Adam Lesinski182f73f2013-12-05 16:48:06 -08001329 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001330 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001331 getContext().enforceCallingOrSelfPermission(
1332 "android.permission.SET_TIME",
1333 "setTime");
1334
Greg Hackmann0cab8962014-02-21 16:35:52 -08001335 if (mNativeData == 0) {
1336 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1337 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001338 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001339
1340 synchronized (mLock) {
1341 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001342 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001344
1345 @Override
1346 public void setTimeZone(String tz) {
1347 getContext().enforceCallingOrSelfPermission(
1348 "android.permission.SET_TIME_ZONE",
1349 "setTimeZone");
1350
1351 final long oldId = Binder.clearCallingIdentity();
1352 try {
1353 setTimeZoneImpl(tz);
1354 } finally {
1355 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 }
1357 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001358
Adam Lesinski182f73f2013-12-05 16:48:06 -08001359 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001360 public void remove(PendingIntent operation, IAlarmListener listener) {
1361 if (operation == null && listener == null) {
1362 Slog.w(TAG, "remove() with no intent or listener");
1363 return;
1364 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001365
Christopher Tate14a7bb02015-10-01 10:24:31 -07001366 synchronized (mLock) {
1367 removeLocked(operation, listener);
1368 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001370
Adam Lesinski182f73f2013-12-05 16:48:06 -08001371 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001372 public long getNextWakeFromIdleTime() {
1373 return getNextWakeFromIdleTimeImpl();
1374 }
1375
1376 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001377 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001378 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1379 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1380 "getNextAlarmClock", null);
1381
1382 return getNextAlarmClockImpl(userId);
1383 }
1384
1385 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001386 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1387 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1388 != PackageManager.PERMISSION_GRANTED) {
1389 pw.println("Permission Denial: can't dump AlarmManager from from pid="
1390 + Binder.getCallingPid()
1391 + ", uid=" + Binder.getCallingUid());
1392 return;
Christopher Tate4cb338d2013-07-26 13:11:31 -07001393 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001394
Adam Lesinski182f73f2013-12-05 16:48:06 -08001395 dumpImpl(pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001396 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001397 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001398
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001399 public final class LocalService {
1400 public void setDeviceIdleUserWhitelist(int[] appids) {
1401 setDeviceIdleUserWhitelistImpl(appids);
1402 }
1403 }
1404
Adam Lesinski182f73f2013-12-05 16:48:06 -08001405 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406 synchronized (mLock) {
1407 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001408 mConstants.dump(pw);
1409 pw.println();
1410
Christopher Tatee0a22b32013-07-11 14:43:13 -07001411 final long nowRTC = System.currentTimeMillis();
1412 final long nowELAPSED = SystemClock.elapsedRealtime();
1413 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1414
Dianne Hackborna750a632015-06-16 17:18:23 -07001415 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001416 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001417 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001418 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001419 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001420 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001421 pw.print(" mLastTimeChangeRealtime=");
Dianne Hackbornc3527222015-05-13 14:03:20 -07001422 TimeUtils.formatDuration(mLastTimeChangeRealtime, pw);
1423 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001424 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001425 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001426 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1427 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001428 pw.print(" Max wakeup delay: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001429 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1430 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001431 pw.print(" Time since last dispatch: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001432 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1433 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001434 pw.print(" Next non-wakeup delivery time: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001435 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1436 pw.println();
1437 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001438
1439 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1440 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001441 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001442 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001443 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001444 pw.print(" Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001445 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001446 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
1447 pw.print(" set at "); TimeUtils.formatDuration(mLastWakeupSet, nowELAPSED, pw);
1448 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001449 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001450 pw.println(" mDeviceIdleUserWhitelist=" + Arrays.toString(mDeviceIdleUserWhitelist));
Christopher Tatee0a22b32013-07-11 14:43:13 -07001451
John Spurlock604a5ee2015-06-01 12:27:22 -04001452 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001453 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001454 final TreeSet<Integer> users = new TreeSet<>();
1455 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1456 users.add(mNextAlarmClockForUser.keyAt(i));
1457 }
1458 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1459 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1460 }
1461 for (int user : users) {
1462 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1463 final long time = next != null ? next.getTriggerTime() : 0;
1464 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001465 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001466 pw.print(" pendingSend:"); pw.print(pendingSend);
1467 pw.print(" time:"); pw.print(time);
1468 if (time > 0) {
1469 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1470 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1471 }
1472 pw.println();
1473 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001474 if (mAlarmBatches.size() > 0) {
1475 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001476 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001477 pw.println(mAlarmBatches.size());
1478 for (Batch b : mAlarmBatches) {
1479 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001480 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001481 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001483 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001484 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001485 pw.println(" Idle mode state:");
1486 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001487 if (mPendingIdleUntil != null) {
1488 pw.println(mPendingIdleUntil);
Dianne Hackbornf3831292015-10-15 14:51:06 -07001489 mPendingIdleUntil.dump(pw, " ", nowRTC, nowELAPSED, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001490 } else {
1491 pw.println("null");
1492 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001493 pw.println(" Pending alarms:");
1494 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001495 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001496 if (mNextWakeFromIdle != null) {
1497 pw.println();
1498 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
1499 mNextWakeFromIdle.dump(pw, " ", nowRTC, nowELAPSED, sdf);
1500 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001501
1502 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001503 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001504 if (mPendingNonWakeupAlarms.size() > 0) {
1505 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001506 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001507 } else {
1508 pw.println("(none)");
1509 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001510 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001511 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1512 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001513 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001514 pw.print(", max non-interactive time: ");
1515 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1516 pw.println();
1517
1518 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001519 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001520 pw.println();
1521
Christopher Tate7f2a0352015-12-08 10:24:33 -08001522 if (mInFlight.size() > 0) {
1523 pw.println("Outstanding deliveries:");
1524 for (int i = 0; i < mInFlight.size(); i++) {
1525 pw.print(" #"); pw.print(i); pw.print(": ");
1526 pw.println(mInFlight.get(i));
1527 }
1528 pw.println();
1529 }
1530
Dianne Hackborna750a632015-06-16 17:18:23 -07001531 pw.print(" mAllowWhileIdleMinTime=");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001532 TimeUtils.formatDuration(mAllowWhileIdleMinTime, pw);
1533 pw.println();
1534 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001535 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001536 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
1537 pw.print(" UID ");
1538 UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
1539 pw.print(": ");
1540 TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i),
1541 nowELAPSED, pw);
1542 pw.println();
1543 }
1544 }
1545 pw.println();
1546
Dianne Hackborn81038902012-11-26 17:04:09 -08001547 if (mLog.dump(pw, " Recent problems", " ")) {
1548 pw.println();
1549 }
1550
1551 final FilterStats[] topFilters = new FilterStats[10];
1552 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1553 @Override
1554 public int compare(FilterStats lhs, FilterStats rhs) {
1555 if (lhs.aggregateTime < rhs.aggregateTime) {
1556 return 1;
1557 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1558 return -1;
1559 }
1560 return 0;
1561 }
1562 };
1563 int len = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001564 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1565 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1566 for (int ip=0; ip<uidStats.size(); ip++) {
1567 BroadcastStats bs = uidStats.valueAt(ip);
1568 for (int is=0; is<bs.filterStats.size(); is++) {
1569 FilterStats fs = bs.filterStats.valueAt(is);
1570 int pos = len > 0
1571 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1572 if (pos < 0) {
1573 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001574 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001575 if (pos < topFilters.length) {
1576 int copylen = topFilters.length - pos - 1;
1577 if (copylen > 0) {
1578 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1579 }
1580 topFilters[pos] = fs;
1581 if (len < topFilters.length) {
1582 len++;
1583 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001584 }
1585 }
1586 }
1587 }
1588 if (len > 0) {
1589 pw.println(" Top Alarms:");
1590 for (int i=0; i<len; i++) {
1591 FilterStats fs = topFilters[i];
1592 pw.print(" ");
1593 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1594 TimeUtils.formatDuration(fs.aggregateTime, pw);
1595 pw.print(" running, "); pw.print(fs.numWakeup);
1596 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001597 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1598 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001599 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001600 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001601 pw.println();
1602 }
1603 }
1604
1605 pw.println(" ");
1606 pw.println(" Alarm Stats:");
1607 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001608 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1609 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1610 for (int ip=0; ip<uidStats.size(); ip++) {
1611 BroadcastStats bs = uidStats.valueAt(ip);
1612 pw.print(" ");
1613 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1614 UserHandle.formatUid(pw, bs.mUid);
1615 pw.print(":");
1616 pw.print(bs.mPackageName);
1617 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1618 pw.print(" running, "); pw.print(bs.numWakeup);
1619 pw.println(" wakeups:");
1620 tmpFilters.clear();
1621 for (int is=0; is<bs.filterStats.size(); is++) {
1622 tmpFilters.add(bs.filterStats.valueAt(is));
1623 }
1624 Collections.sort(tmpFilters, comparator);
1625 for (int i=0; i<tmpFilters.size(); i++) {
1626 FilterStats fs = tmpFilters.get(i);
1627 pw.print(" ");
1628 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1629 TimeUtils.formatDuration(fs.aggregateTime, pw);
1630 pw.print(" "); pw.print(fs.numWakeup);
1631 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001632 pw.print(" alarms, last ");
1633 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1634 pw.println(":");
1635 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001636 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001637 pw.println();
1638 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 }
1640 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001641
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001642 if (RECORD_DEVICE_IDLE_ALARMS) {
1643 pw.println();
1644 pw.println(" Allow while idle dispatches:");
1645 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
1646 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
1647 pw.print(" ");
1648 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
1649 pw.print(": ");
1650 UserHandle.formatUid(pw, ent.uid);
1651 pw.print(":");
1652 pw.println(ent.pkg);
1653 if (ent.op != null) {
1654 pw.print(" ");
1655 pw.print(ent.op);
1656 pw.print(" / ");
1657 pw.print(ent.tag);
1658 if (ent.argRealtime != 0) {
1659 pw.print(" (");
1660 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
1661 pw.print(")");
1662 }
1663 pw.println();
1664 }
1665 }
1666 }
1667
Christopher Tate18a75f12013-07-01 18:18:59 -07001668 if (WAKEUP_STATS) {
1669 pw.println();
1670 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001671 long last = -1;
1672 for (WakeupEvent event : mRecentWakeups) {
1673 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1674 pw.print('|');
1675 if (last < 0) {
1676 pw.print('0');
1677 } else {
1678 pw.print(event.when - last);
1679 }
1680 last = event.when;
1681 pw.print('|'); pw.print(event.uid);
1682 pw.print('|'); pw.print(event.action);
1683 pw.println();
1684 }
1685 pw.println();
1686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 }
1688 }
1689
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001690 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001691 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
1692 PrintWriter pw = new PrintWriter(bs);
1693 final long nowRTC = System.currentTimeMillis();
1694 final long nowELAPSED = SystemClock.elapsedRealtime();
1695 final int NZ = mAlarmBatches.size();
1696 for (int iz = 0; iz < NZ; iz++) {
1697 Batch bz = mAlarmBatches.get(iz);
1698 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001699 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001700 pw.flush();
1701 Slog.v(TAG, bs.toString());
1702 bs.reset();
1703 }
1704 }
1705
1706 private boolean validateConsistencyLocked() {
1707 if (DEBUG_VALIDATE) {
1708 long lastTime = Long.MIN_VALUE;
1709 final int N = mAlarmBatches.size();
1710 for (int i = 0; i < N; i++) {
1711 Batch b = mAlarmBatches.get(i);
1712 if (b.start >= lastTime) {
1713 // duplicate start times are okay because of standalone batches
1714 lastTime = b.start;
1715 } else {
1716 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001717 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1718 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001719 return false;
1720 }
1721 }
1722 }
1723 return true;
1724 }
1725
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001726 private Batch findFirstWakeupBatchLocked() {
1727 final int N = mAlarmBatches.size();
1728 for (int i = 0; i < N; i++) {
1729 Batch b = mAlarmBatches.get(i);
1730 if (b.hasWakeups()) {
1731 return b;
1732 }
1733 }
1734 return null;
1735 }
1736
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001737 long getNextWakeFromIdleTimeImpl() {
1738 synchronized (mLock) {
1739 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
1740 }
1741 }
1742
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001743 void setDeviceIdleUserWhitelistImpl(int[] appids) {
1744 synchronized (mLock) {
1745 mDeviceIdleUserWhitelist = appids;
1746 }
1747 }
1748
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001749 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001750 synchronized (mLock) {
1751 return mNextAlarmClockForUser.get(userId);
1752 }
1753 }
1754
1755 /**
1756 * Recomputes the next alarm clock for all users.
1757 */
1758 private void updateNextAlarmClockLocked() {
1759 if (!mNextAlarmClockMayChange) {
1760 return;
1761 }
1762 mNextAlarmClockMayChange = false;
1763
Jose Lima235510e2014-08-13 12:50:01 -07001764 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001765 nextForUser.clear();
1766
1767 final int N = mAlarmBatches.size();
1768 for (int i = 0; i < N; i++) {
1769 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
1770 final int M = alarms.size();
1771
1772 for (int j = 0; j < M; j++) {
1773 Alarm a = alarms.get(j);
1774 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001775 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07001776 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001777
1778 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07001779 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001780 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02001781 " for user " + userId);
1782 }
1783
1784 // Alarms and batches are sorted by time, no need to compare times here.
1785 if (nextForUser.get(userId) == null) {
1786 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07001787 } else if (a.alarmClock.equals(current)
1788 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
1789 // same/earlier time and it's the one we cited before, so stick with it
1790 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001791 }
1792 }
1793 }
1794 }
1795
1796 // Update mNextAlarmForUser with new values.
1797 final int NN = nextForUser.size();
1798 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07001799 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001800 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001801 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001802 if (!newAlarm.equals(currentAlarm)) {
1803 updateNextAlarmInfoForUserLocked(userId, newAlarm);
1804 }
1805 }
1806
1807 // Remove users without any alarm clocks scheduled.
1808 final int NNN = mNextAlarmClockForUser.size();
1809 for (int i = NNN - 1; i >= 0; i--) {
1810 int userId = mNextAlarmClockForUser.keyAt(i);
1811 if (nextForUser.get(userId) == null) {
1812 updateNextAlarmInfoForUserLocked(userId, null);
1813 }
1814 }
1815 }
1816
Jose Lima235510e2014-08-13 12:50:01 -07001817 private void updateNextAlarmInfoForUserLocked(int userId,
1818 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001819 if (alarmClock != null) {
1820 if (DEBUG_ALARM_CLOCK) {
1821 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001822 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02001823 }
1824 mNextAlarmClockForUser.put(userId, alarmClock);
1825 } else {
1826 if (DEBUG_ALARM_CLOCK) {
1827 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
1828 }
1829 mNextAlarmClockForUser.remove(userId);
1830 }
1831
1832 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
1833 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1834 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1835 }
1836
1837 /**
1838 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
1839 * for which alarm clocks have changed since the last call to this.
1840 *
1841 * Do not call with a lock held. Only call from mHandler's thread.
1842 *
1843 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
1844 */
1845 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07001846 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001847 pendingUsers.clear();
1848
1849 synchronized (mLock) {
1850 final int N = mPendingSendNextAlarmClockChangedForUser.size();
1851 for (int i = 0; i < N; i++) {
1852 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
1853 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
1854 }
1855 mPendingSendNextAlarmClockChangedForUser.clear();
1856 }
1857
1858 final int N = pendingUsers.size();
1859 for (int i = 0; i < N; i++) {
1860 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001861 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001862 Settings.System.putStringForUser(getContext().getContentResolver(),
1863 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01001864 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02001865 userId);
1866
1867 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
1868 new UserHandle(userId));
1869 }
1870 }
1871
1872 /**
1873 * Formats an alarm like platform/packages/apps/DeskClock used to.
1874 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01001875 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
1876 int userId) {
1877 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02001878 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
1879 return (info == null) ? "" :
1880 DateFormat.format(pattern, info.getTriggerTime()).toString();
1881 }
1882
Adam Lesinski182f73f2013-12-05 16:48:06 -08001883 void rescheduleKernelAlarmsLocked() {
1884 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
1885 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001886 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001887 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001888 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001889 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07001890 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001891 mNextWakeup = firstWakeup.start;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001892 mLastWakeupSet = SystemClock.elapsedRealtime();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001893 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001894 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001895 if (firstBatch != firstWakeup) {
1896 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001897 }
1898 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001899 if (mPendingNonWakeupAlarms.size() > 0) {
1900 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
1901 nextNonWakeup = mNextNonWakeupDeliveryTime;
1902 }
1903 }
Prashant Malani753e9e02015-06-10 17:43:49 -07001904 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001905 mNextNonWakeup = nextNonWakeup;
1906 setLocked(ELAPSED_REALTIME, nextNonWakeup);
1907 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001908 }
1909
Christopher Tate14a7bb02015-10-01 10:24:31 -07001910 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001911 boolean didRemove = false;
1912 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1913 Batch b = mAlarmBatches.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -07001914 didRemove |= b.remove(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001915 if (b.size() == 0) {
1916 mAlarmBatches.remove(i);
1917 }
1918 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001919 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001920 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001921 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1922 mPendingWhileIdleAlarms.remove(i);
1923 }
1924 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001925
1926 if (didRemove) {
1927 if (DEBUG_BATCH) {
1928 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
1929 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001930 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001931 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001932 mPendingIdleUntil = null;
1933 restorePending = true;
1934 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001935 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001936 mNextWakeFromIdle = null;
1937 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001938 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001939 if (restorePending) {
1940 restorePendingWhileIdleAlarmsLocked();
1941 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001942 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001943 }
1944 }
1945
1946 void removeLocked(String packageName) {
1947 boolean didRemove = false;
1948 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1949 Batch b = mAlarmBatches.get(i);
1950 didRemove |= b.remove(packageName);
1951 if (b.size() == 0) {
1952 mAlarmBatches.remove(i);
1953 }
1954 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001955 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001956 final Alarm a = mPendingWhileIdleAlarms.get(i);
1957 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001958 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1959 mPendingWhileIdleAlarms.remove(i);
1960 }
1961 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001962
1963 if (didRemove) {
1964 if (DEBUG_BATCH) {
1965 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1966 }
1967 rebatchAllAlarmsLocked(true);
1968 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001969 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001970 }
1971 }
1972
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001973 void removeForStoppedLocked(int uid) {
1974 boolean didRemove = false;
1975 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1976 Batch b = mAlarmBatches.get(i);
1977 didRemove |= b.removeForStopped(uid);
1978 if (b.size() == 0) {
1979 mAlarmBatches.remove(i);
1980 }
1981 }
1982 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1983 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08001984 if (a.uid == uid) {
1985 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1986 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001987 }
1988 }
1989
1990 if (didRemove) {
1991 if (DEBUG_BATCH) {
1992 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1993 }
1994 rebatchAllAlarmsLocked(true);
1995 rescheduleKernelAlarmsLocked();
1996 updateNextAlarmClockLocked();
1997 }
1998 }
1999
Adam Lesinski182f73f2013-12-05 16:48:06 -08002000 void removeUserLocked(int userHandle) {
2001 boolean didRemove = false;
2002 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2003 Batch b = mAlarmBatches.get(i);
2004 didRemove |= b.remove(userHandle);
2005 if (b.size() == 0) {
2006 mAlarmBatches.remove(i);
2007 }
2008 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002009 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002010 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002011 == userHandle) {
2012 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2013 mPendingWhileIdleAlarms.remove(i);
2014 }
2015 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002016 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
2017 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
2018 mLastAllowWhileIdleDispatch.removeAt(i);
2019 }
2020 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002021
2022 if (didRemove) {
2023 if (DEBUG_BATCH) {
2024 Slog.v(TAG, "remove(user) changed bounds; rebatching");
2025 }
2026 rebatchAllAlarmsLocked(true);
2027 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002028 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002029 }
2030 }
2031
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002032 void interactiveStateChangedLocked(boolean interactive) {
2033 if (mInteractive != interactive) {
2034 mInteractive = interactive;
2035 final long nowELAPSED = SystemClock.elapsedRealtime();
2036 if (interactive) {
2037 if (mPendingNonWakeupAlarms.size() > 0) {
2038 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2039 mTotalDelayTime += thisDelayTime;
2040 if (mMaxDelayTime < thisDelayTime) {
2041 mMaxDelayTime = thisDelayTime;
2042 }
2043 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2044 mPendingNonWakeupAlarms.clear();
2045 }
2046 if (mNonInteractiveStartTime > 0) {
2047 long dur = nowELAPSED - mNonInteractiveStartTime;
2048 if (dur > mNonInteractiveTime) {
2049 mNonInteractiveTime = dur;
2050 }
2051 }
2052 } else {
2053 mNonInteractiveStartTime = nowELAPSED;
2054 }
2055 }
2056 }
2057
Adam Lesinski182f73f2013-12-05 16:48:06 -08002058 boolean lookForPackageLocked(String packageName) {
2059 for (int i = 0; i < mAlarmBatches.size(); i++) {
2060 Batch b = mAlarmBatches.get(i);
2061 if (b.hasPackage(packageName)) {
2062 return true;
2063 }
2064 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002065 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002066 final Alarm a = mPendingWhileIdleAlarms.get(i);
2067 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002068 return true;
2069 }
2070 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002071 return false;
2072 }
2073
2074 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002075 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002076 // The kernel never triggers alarms with negative wakeup times
2077 // so we ensure they are positive.
2078 long alarmSeconds, alarmNanoseconds;
2079 if (when < 0) {
2080 alarmSeconds = 0;
2081 alarmNanoseconds = 0;
2082 } else {
2083 alarmSeconds = when / 1000;
2084 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2085 }
2086
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002087 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002088 } else {
2089 Message msg = Message.obtain();
2090 msg.what = ALARM_EVENT;
2091
2092 mHandler.removeMessages(ALARM_EVENT);
2093 mHandler.sendMessageAtTime(msg, when);
2094 }
2095 }
2096
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002097 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002098 String prefix, String label, long nowRTC, long nowELAPSED, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002099 for (int i=list.size()-1; i>=0; i--) {
2100 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002101 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2102 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002103 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002104 }
2105 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002106
2107 private static final String labelForType(int type) {
2108 switch (type) {
2109 case RTC: return "RTC";
2110 case RTC_WAKEUP : return "RTC_WAKEUP";
2111 case ELAPSED_REALTIME : return "ELAPSED";
2112 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
2113 default:
2114 break;
2115 }
2116 return "--unknown--";
2117 }
2118
2119 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002120 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002121 for (int i=list.size()-1; i>=0; i--) {
2122 Alarm a = list.get(i);
2123 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002124 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2125 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002126 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002127 }
2128 }
2129
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002130 private native long init();
2131 private native void close(long nativeData);
2132 private native void set(long nativeData, int type, long seconds, long nanoseconds);
2133 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08002134 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002135 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002136
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002137 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002138 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002139 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002140 // batches are temporally sorted, so we need only pull from the
2141 // start of the list until we either empty it or hit a batch
2142 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07002143 while (mAlarmBatches.size() > 0) {
2144 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002145 if (batch.start > nowELAPSED) {
2146 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002147 break;
2148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002149
Christopher Tatee0a22b32013-07-11 14:43:13 -07002150 // We will (re)schedule some alarms now; don't let that interfere
2151 // with delivery of this current batch
2152 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002153
Christopher Tatee0a22b32013-07-11 14:43:13 -07002154 final int N = batch.size();
2155 for (int i = 0; i < N; i++) {
2156 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002157
2158 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
2159 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
2160 // schedule such alarms.
2161 long lastTime = mLastAllowWhileIdleDispatch.get(alarm.uid, 0);
2162 long minTime = lastTime + mAllowWhileIdleMinTime;
2163 if (nowELAPSED < minTime) {
2164 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
2165 // alarm went off for this app. Reschedule the alarm to be in the
2166 // correct time period.
2167 alarm.whenElapsed = minTime;
2168 if (alarm.maxWhenElapsed < minTime) {
2169 alarm.maxWhenElapsed = minTime;
2170 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002171 if (RECORD_DEVICE_IDLE_ALARMS) {
2172 IdleDispatchEntry ent = new IdleDispatchEntry();
2173 ent.uid = alarm.uid;
2174 ent.pkg = alarm.operation.getCreatorPackage();
2175 ent.tag = alarm.operation.getTag("");
2176 ent.op = "RESCHEDULE";
2177 ent.elapsedRealtime = nowELAPSED;
2178 ent.argRealtime = lastTime;
2179 mAllowWhileIdleDispatches.add(ent);
2180 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002181 setImplLocked(alarm, true, false);
2182 continue;
2183 }
2184 }
2185
Christopher Tatee0a22b32013-07-11 14:43:13 -07002186 alarm.count = 1;
2187 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002188 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
2189 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002190 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002191 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002192 if (mPendingIdleUntil == alarm) {
2193 mPendingIdleUntil = null;
2194 rebatchAllAlarmsLocked(false);
2195 restorePendingWhileIdleAlarmsLocked();
2196 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002197 if (mNextWakeFromIdle == alarm) {
2198 mNextWakeFromIdle = null;
2199 rebatchAllAlarmsLocked(false);
2200 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002201
2202 // Recurring alarms may have passed several alarm intervals while the
2203 // phone was asleep or off, so pass a trigger count when sending them.
2204 if (alarm.repeatInterval > 0) {
2205 // this adjustment will be zero if we're late by
2206 // less than one full repeat interval
2207 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
2208
2209 // Also schedule its next recurrence
2210 final long delta = alarm.count * alarm.repeatInterval;
2211 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07002212 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07002213 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07002214 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
2215 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08002216 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002217
Christopher Tate864d42e2014-12-02 11:48:53 -08002218 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002219 hasWakeup = true;
2220 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002221
2222 // We removed an alarm clock. Let the caller recompute the next alarm clock.
2223 if (alarm.alarmClock != null) {
2224 mNextAlarmClockMayChange = true;
2225 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07002226 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002227 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002228
Christopher Tate1590f1e2014-10-02 17:27:57 -07002229 // This is a new alarm delivery set; bump the sequence number to indicate that
2230 // all apps' alarm delivery classes should be recalculated.
2231 mCurrentSeq++;
2232 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002233 Collections.sort(triggerList, mAlarmDispatchComparator);
2234
2235 if (localLOGV) {
2236 for (int i=0; i<triggerList.size(); i++) {
2237 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
2238 }
2239 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002240
2241 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002242 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002244 /**
2245 * This Comparator sorts Alarms into increasing time order.
2246 */
2247 public static class IncreasingTimeOrder implements Comparator<Alarm> {
2248 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09002249 long when1 = a1.whenElapsed;
2250 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002251 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002252 return 1;
2253 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002254 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002255 return -1;
2256 }
2257 return 0;
2258 }
2259 }
2260
2261 private static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002262 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002263 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002264 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002265 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002266 public final IAlarmListener listener;
2267 public final String listenerTag;
2268 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002269 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002270 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002271 public final AlarmManager.AlarmClockInfo alarmClock;
2272 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002273 public final int creatorUid;
2274 public final String packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002275 public int count;
2276 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07002277 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002278 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002279 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002280 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07002281 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002282
Christopher Tate3e04b472013-10-21 17:51:31 -07002283 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002284 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
2285 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
2286 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002287 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002288 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002289 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
2290 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002291 when = _when;
2292 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07002293 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002294 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002295 repeatInterval = _interval;
2296 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002297 listener = _rec;
2298 listenerTag = _listenerTag;
2299 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07002300 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002301 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002302 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002303 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002304 packageName = _pkgName;
2305
2306 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002307 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002308
Christopher Tate14a7bb02015-10-01 10:24:31 -07002309 public static String makeTag(PendingIntent pi, String tag, int type) {
2310 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
2311 ? "*walarm*:" : "*alarm*:";
2312 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
2313 }
2314
2315 public WakeupEvent makeWakeupEvent(long nowRTC) {
2316 return new WakeupEvent(nowRTC, creatorUid,
2317 (operation != null)
2318 ? operation.getIntent().getAction()
2319 : ("<listener>:" + listenerTag));
2320 }
2321
2322 // Returns true if either matches
2323 public boolean matches(PendingIntent pi, IAlarmListener rec) {
2324 return (operation != null)
2325 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09002326 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07002327 }
2328
2329 public boolean matches(String packageName) {
2330 return (operation != null)
2331 ? packageName.equals(operation.getTargetPackage())
2332 : packageName.equals(this.packageName);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002333 }
2334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002335 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002336 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002337 StringBuilder sb = new StringBuilder(128);
2338 sb.append("Alarm{");
2339 sb.append(Integer.toHexString(System.identityHashCode(this)));
2340 sb.append(" type ");
2341 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002342 sb.append(" when ");
2343 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002344 sb.append(" ");
Christopher Tate14a7bb02015-10-01 10:24:31 -07002345 if (operation != null) {
2346 sb.append(operation.getTargetPackage());
2347 } else {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002348 sb.append(packageName);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002349 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002350 sb.append('}');
2351 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002352 }
2353
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002354 public void dump(PrintWriter pw, String prefix, long nowRTC, long nowELAPSED,
2355 SimpleDateFormat sdf) {
2356 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002357 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002358 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002359 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
2360 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002361 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002362 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002363 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002364 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002365 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002366 }
2367 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002368 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002369 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002370 pw.print(" count="); pw.print(count);
2371 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002372 if (alarmClock != null) {
2373 pw.print(prefix); pw.println("Alarm clock:");
2374 pw.print(prefix); pw.print(" triggerTime=");
2375 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
2376 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
2377 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002378 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002379 if (listener != null) {
2380 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
2381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002382 }
2383 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002384
Christopher Tatee0a22b32013-07-11 14:43:13 -07002385 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
2386 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002387 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
2388 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002389 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07002390 break;
2391 }
2392
Christopher Tatee0a22b32013-07-11 14:43:13 -07002393 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002394 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
2395 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002396 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07002397 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002398 }
2399 }
2400
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002401 long currentNonWakeupFuzzLocked(long nowELAPSED) {
2402 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
2403 if (timeSinceOn < 5*60*1000) {
2404 // If the screen has been off for 5 minutes, only delay by at most two minutes.
2405 return 2*60*1000;
2406 } else if (timeSinceOn < 30*60*1000) {
2407 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
2408 return 15*60*1000;
2409 } else {
2410 // Otherwise, we will delay by at most an hour.
2411 return 60*60*1000;
2412 }
2413 }
2414
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002415 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002416 if (duration < 15*60*1000) {
2417 // If the duration until the time is less than 15 minutes, the maximum fuzz
2418 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002419 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002420 } else if (duration < 90*60*1000) {
2421 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
2422 return 15*60*1000;
2423 } else {
2424 // Otherwise, we will fuzz by at most half an hour.
2425 return 30*60*1000;
2426 }
2427 }
2428
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002429 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
2430 if (mInteractive) {
2431 return false;
2432 }
2433 if (mLastAlarmDeliveryTime <= 0) {
2434 return false;
2435 }
minho.choo649acab2014-12-12 16:13:55 +09002436 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002437 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
2438 // and the next delivery time is in the past, then just deliver them all. This
2439 // avoids bugs where we get stuck in a loop trying to poll for alarms.
2440 return false;
2441 }
2442 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
2443 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
2444 }
2445
2446 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
2447 mLastAlarmDeliveryTime = nowELAPSED;
2448 for (int i=0; i<triggerList.size(); i++) {
2449 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07002450 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002451 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07002452 if (localLOGV) {
2453 Slog.v(TAG, "sending alarm " + alarm);
2454 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07002455 if (RECORD_ALARMS_IN_HISTORY) {
2456 if (alarm.workSource != null && alarm.workSource.size() > 0) {
2457 for (int wi=0; wi<alarm.workSource.size(); wi++) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002458 ActivityManager.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002459 alarm.operation, alarm.workSource.get(wi), alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002460 }
2461 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002462 ActivityManager.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002463 alarm.operation, alarm.uid, alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002464 }
2465 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002466 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002467 } catch (RuntimeException e) {
2468 Slog.w(TAG, "Failure sending alarm.", e);
2469 }
2470 }
2471 }
2472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002473 private class AlarmThread extends Thread
2474 {
2475 public AlarmThread()
2476 {
2477 super("AlarmManager");
2478 }
2479
2480 public void run()
2481 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002482 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002484 while (true)
2485 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002486 int result = waitForAlarm(mNativeData);
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002487 mLastWakeup = SystemClock.elapsedRealtime();
Dianne Hackborn390517b2013-05-30 15:03:32 -07002488
2489 triggerList.clear();
2490
Dianne Hackbornc3527222015-05-13 14:03:20 -07002491 final long nowRTC = System.currentTimeMillis();
2492 final long nowELAPSED = SystemClock.elapsedRealtime();
2493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002494 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002495 // The kernel can give us spurious time change notifications due to
2496 // small adjustments it makes internally; we want to filter those out.
2497 final long lastTimeChangeClockTime;
2498 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07002499 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002500 lastTimeChangeClockTime = mLastTimeChangeClockTime;
2501 expectedClockTime = lastTimeChangeClockTime
2502 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07002503 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08002504 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
2505 || nowRTC > (expectedClockTime+1000)) {
2506 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07002507 // let's do it!
2508 if (DEBUG_BATCH) {
2509 Slog.v(TAG, "Time changed notification from kernel; rebatching");
2510 }
2511 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07002512 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07002513 rebatchAllAlarms();
2514 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07002515 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07002516 synchronized (mLock) {
2517 mNumTimeChanged++;
2518 mLastTimeChangeClockTime = nowRTC;
2519 mLastTimeChangeRealtime = nowELAPSED;
2520 }
2521 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
2522 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08002523 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07002524 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
2525 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07002526 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
2527
2528 // The world has changed on us, so we need to re-evaluate alarms
2529 // regardless of whether the kernel has told us one went off.
2530 result |= IS_WAKEUP_MASK;
2531 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002532 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002533
Dianne Hackbornc3527222015-05-13 14:03:20 -07002534 if (result != TIME_CHANGED_MASK) {
2535 // If this was anything besides just a time change, then figure what if
2536 // anything to do about alarms.
2537 synchronized (mLock) {
2538 if (localLOGV) Slog.v(
2539 TAG, "Checking for alarms... rtc=" + nowRTC
2540 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07002541
Dianne Hackbornc3527222015-05-13 14:03:20 -07002542 if (WAKEUP_STATS) {
2543 if ((result & IS_WAKEUP_MASK) != 0) {
2544 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
2545 int n = 0;
2546 for (WakeupEvent event : mRecentWakeups) {
2547 if (event.when > newEarliest) break;
2548 n++; // number of now-stale entries at the list head
2549 }
2550 for (int i = 0; i < n; i++) {
2551 mRecentWakeups.remove();
2552 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002553
Dianne Hackbornc3527222015-05-13 14:03:20 -07002554 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002555 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002556 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002557
2558 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2559 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
2560 // if there are no wakeup alarms and the screen is off, we can
2561 // delay what we have so far until the future.
2562 if (mPendingNonWakeupAlarms.size() == 0) {
2563 mStartCurrentDelayTime = nowELAPSED;
2564 mNextNonWakeupDeliveryTime = nowELAPSED
2565 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
2566 }
2567 mPendingNonWakeupAlarms.addAll(triggerList);
2568 mNumDelayedAlarms += triggerList.size();
2569 rescheduleKernelAlarmsLocked();
2570 updateNextAlarmClockLocked();
2571 } else {
2572 // now deliver the alarm intents; if there are pending non-wakeup
2573 // alarms, we need to merge them in to the list. note we don't
2574 // just deliver them first because we generally want non-wakeup
2575 // alarms delivered after wakeup alarms.
2576 rescheduleKernelAlarmsLocked();
2577 updateNextAlarmClockLocked();
2578 if (mPendingNonWakeupAlarms.size() > 0) {
2579 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
2580 triggerList.addAll(mPendingNonWakeupAlarms);
2581 Collections.sort(triggerList, mAlarmDispatchComparator);
2582 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2583 mTotalDelayTime += thisDelayTime;
2584 if (mMaxDelayTime < thisDelayTime) {
2585 mMaxDelayTime = thisDelayTime;
2586 }
2587 mPendingNonWakeupAlarms.clear();
2588 }
2589 deliverAlarmsLocked(triggerList, nowELAPSED);
2590 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002592
2593 } else {
2594 // Just in case -- even though no wakeup flag was set, make sure
2595 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07002596 synchronized (mLock) {
2597 rescheduleKernelAlarmsLocked();
2598 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002599 }
2600 }
2601 }
2602 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002603
David Christieebe51fc2013-07-26 13:23:29 -07002604 /**
2605 * Attribute blame for a WakeLock.
2606 * @param pi PendingIntent to attribute blame to if ws is null.
2607 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002608 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07002609 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002610 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002611 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07002612 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002613 final boolean unimportant = pi == mTimeTickSender;
2614 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002615 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002616 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002617 } else {
2618 mWakeLock.setHistoryTag(null);
2619 }
2620 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07002621 if (ws != null) {
2622 mWakeLock.setWorkSource(ws);
2623 return;
2624 }
2625
Christopher Tate14a7bb02015-10-01 10:24:31 -07002626 final int uid = (knownUid >= 0)
2627 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002628 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07002629 if (uid >= 0) {
2630 mWakeLock.setWorkSource(new WorkSource(uid));
2631 return;
2632 }
2633 } catch (Exception e) {
2634 }
2635
2636 // Something went wrong; fall back to attributing the lock to the OS
2637 mWakeLock.setWorkSource(null);
2638 }
2639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002640 private class AlarmHandler extends Handler {
2641 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002642 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
2643 public static final int LISTENER_TIMEOUT = 3;
2644 public static final int REPORT_ALARMS_ACTIVE = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002645
2646 public AlarmHandler() {
2647 }
2648
2649 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002650 switch (msg.what) {
2651 case ALARM_EVENT: {
2652 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2653 synchronized (mLock) {
2654 final long nowRTC = System.currentTimeMillis();
2655 final long nowELAPSED = SystemClock.elapsedRealtime();
2656 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2657 updateNextAlarmClockLocked();
2658 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002659
Christopher Tate14a7bb02015-10-01 10:24:31 -07002660 // now trigger the alarms without the lock held
2661 for (int i=0; i<triggerList.size(); i++) {
2662 Alarm alarm = triggerList.get(i);
2663 try {
2664 alarm.operation.send();
2665 } catch (PendingIntent.CanceledException e) {
2666 if (alarm.repeatInterval > 0) {
2667 // This IntentSender is no longer valid, but this
2668 // is a repeating alarm, so toss the hoser.
2669 removeImpl(alarm.operation);
2670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002671 }
2672 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002673 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002674 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002675
2676 case SEND_NEXT_ALARM_CLOCK_CHANGED:
2677 sendNextAlarmClockChanged();
2678 break;
2679
2680 case LISTENER_TIMEOUT:
2681 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
2682 break;
2683
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002684 case REPORT_ALARMS_ACTIVE:
2685 if (mLocalDeviceIdleController != null) {
2686 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
2687 }
2688 break;
2689
Christopher Tate14a7bb02015-10-01 10:24:31 -07002690 default:
2691 // nope, just ignore it
2692 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002693 }
2694 }
2695 }
2696
2697 class ClockReceiver extends BroadcastReceiver {
2698 public ClockReceiver() {
2699 IntentFilter filter = new IntentFilter();
2700 filter.addAction(Intent.ACTION_TIME_TICK);
2701 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002702 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002703 }
2704
2705 @Override
2706 public void onReceive(Context context, Intent intent) {
2707 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07002708 if (DEBUG_BATCH) {
2709 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
2710 }
2711 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002712 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
2713 // Since the kernel does not keep track of DST, we need to
2714 // reset the TZ information at the beginning of each day
2715 // based off of the current Zone gmt offset + userspace tracked
2716 // daylight savings information.
2717 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02002718 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002719 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07002720 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002721 }
2722 }
2723
2724 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07002725 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09002726 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07002727
2728 // Schedule this event for the amount of time that it would take to get to
2729 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09002730 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07002731
David Christieebe51fc2013-07-26 13:23:29 -07002732 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002733 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002734 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
2735 null, Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002736 }
Christopher Tate385e4982013-07-23 18:22:29 -07002737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002738 public void scheduleDateChangedEvent() {
2739 Calendar calendar = Calendar.getInstance();
2740 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07002741 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002742 calendar.set(Calendar.MINUTE, 0);
2743 calendar.set(Calendar.SECOND, 0);
2744 calendar.set(Calendar.MILLISECOND, 0);
2745 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07002746
2747 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002748 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
2749 AlarmManager.FLAG_STANDALONE, workSource, null,
2750 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002751 }
2752 }
2753
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002754 class InteractiveStateReceiver extends BroadcastReceiver {
2755 public InteractiveStateReceiver() {
2756 IntentFilter filter = new IntentFilter();
2757 filter.addAction(Intent.ACTION_SCREEN_OFF);
2758 filter.addAction(Intent.ACTION_SCREEN_ON);
2759 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
2760 getContext().registerReceiver(this, filter);
2761 }
2762
2763 @Override
2764 public void onReceive(Context context, Intent intent) {
2765 synchronized (mLock) {
2766 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
2767 }
2768 }
2769 }
2770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002771 class UninstallReceiver extends BroadcastReceiver {
2772 public UninstallReceiver() {
2773 IntentFilter filter = new IntentFilter();
2774 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2775 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002776 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002777 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08002778 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002779 // Register for events related to sdcard installation.
2780 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08002781 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002782 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002783 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002784 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002785 }
2786
2787 @Override
2788 public void onReceive(Context context, Intent intent) {
2789 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002790 String action = intent.getAction();
2791 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002792 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
2793 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
2794 for (String packageName : pkgList) {
2795 if (lookForPackageLocked(packageName)) {
2796 setResultCode(Activity.RESULT_OK);
2797 return;
2798 }
2799 }
2800 return;
2801 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002802 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002803 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
2804 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
2805 if (userHandle >= 0) {
2806 removeUserLocked(userHandle);
2807 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002808 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
2809 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
2810 if (uid >= 0) {
2811 mLastAllowWhileIdleDispatch.delete(uid);
2812 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002813 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08002814 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
2815 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
2816 // This package is being updated; don't kill its alarms.
2817 return;
2818 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002819 Uri data = intent.getData();
2820 if (data != null) {
2821 String pkg = data.getSchemeSpecificPart();
2822 if (pkg != null) {
2823 pkgList = new String[]{pkg};
2824 }
2825 }
2826 }
2827 if (pkgList != null && (pkgList.length > 0)) {
2828 for (String pkg : pkgList) {
2829 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07002830 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002831 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
2832 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
2833 if (uidStats.remove(pkg) != null) {
2834 if (uidStats.size() <= 0) {
2835 mBroadcastStats.removeAt(i);
2836 }
2837 }
2838 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002839 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002840 }
2841 }
2842 }
2843 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002844
2845 final class UidObserver extends IUidObserver.Stub {
Sudheer Shanka80255802017-03-04 14:48:53 -08002846 @Override public void onUidStateChanged(int uid, int procState,
2847 long procStateSeq) throws RemoteException {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002848 }
2849
Dianne Hackborne07641d2016-11-09 15:07:23 -08002850 @Override public void onUidGone(int uid, boolean disabled) throws RemoteException {
2851 if (disabled) {
2852 synchronized (mLock) {
2853 removeForStoppedLocked(uid);
2854 }
2855 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002856 }
2857
2858 @Override public void onUidActive(int uid) throws RemoteException {
2859 }
2860
Dianne Hackborne07641d2016-11-09 15:07:23 -08002861 @Override public void onUidIdle(int uid, boolean disabled) throws RemoteException {
2862 if (disabled) {
2863 synchronized (mLock) {
2864 removeForStoppedLocked(uid);
2865 }
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08002866 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002867 }
2868 };
2869
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002870 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002871 String pkg = pi.getCreatorPackage();
2872 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002873 return getStatsLocked(uid, pkg);
2874 }
2875
2876 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002877 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
2878 if (uidStats == null) {
2879 uidStats = new ArrayMap<String, BroadcastStats>();
2880 mBroadcastStats.put(uid, uidStats);
2881 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002882 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002883 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002884 bs = new BroadcastStats(uid, pkgName);
2885 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002886 }
2887 return bs;
2888 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002889
Christopher Tate14a7bb02015-10-01 10:24:31 -07002890 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
2891 private InFlight removeLocked(PendingIntent pi, Intent intent) {
2892 for (int i = 0; i < mInFlight.size(); i++) {
2893 if (mInFlight.get(i).mPendingIntent == pi) {
2894 return mInFlight.remove(i);
2895 }
2896 }
2897 mLog.w("No in-flight alarm for " + pi + " " + intent);
2898 return null;
2899 }
2900
2901 private InFlight removeLocked(IBinder listener) {
2902 for (int i = 0; i < mInFlight.size(); i++) {
2903 if (mInFlight.get(i).mListener == listener) {
2904 return mInFlight.remove(i);
2905 }
2906 }
2907 mLog.w("No in-flight alarm for listener " + listener);
2908 return null;
2909 }
2910
2911 private void updateStatsLocked(InFlight inflight) {
2912 final long nowELAPSED = SystemClock.elapsedRealtime();
2913 BroadcastStats bs = inflight.mBroadcastStats;
2914 bs.nesting--;
2915 if (bs.nesting <= 0) {
2916 bs.nesting = 0;
2917 bs.aggregateTime += nowELAPSED - bs.startTime;
2918 }
2919 FilterStats fs = inflight.mFilterStats;
2920 fs.nesting--;
2921 if (fs.nesting <= 0) {
2922 fs.nesting = 0;
2923 fs.aggregateTime += nowELAPSED - fs.startTime;
2924 }
2925 if (RECORD_ALARMS_IN_HISTORY) {
2926 if (inflight.mWorkSource != null && inflight.mWorkSource.size() > 0) {
2927 for (int wi=0; wi<inflight.mWorkSource.size(); wi++) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002928 ActivityManager.noteAlarmFinish(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002929 inflight.mPendingIntent, inflight.mWorkSource.get(wi), inflight.mTag);
2930 }
2931 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002932 ActivityManager.noteAlarmFinish(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002933 inflight.mPendingIntent, inflight.mUid, inflight.mTag);
2934 }
2935 }
2936 }
2937
2938 private void updateTrackingLocked(InFlight inflight) {
2939 if (inflight != null) {
2940 updateStatsLocked(inflight);
2941 }
2942 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08002943 if (DEBUG_WAKELOCK) {
2944 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
2945 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002946 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002947 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002948 mWakeLock.release();
2949 if (mInFlight.size() > 0) {
2950 mLog.w("Finished all dispatches with " + mInFlight.size()
2951 + " remaining inflights");
2952 for (int i=0; i<mInFlight.size(); i++) {
2953 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
2954 }
2955 mInFlight.clear();
2956 }
2957 } else {
2958 // the next of our alarms is now in flight. reattribute the wakelock.
2959 if (mInFlight.size() > 0) {
2960 InFlight inFlight = mInFlight.get(0);
2961 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
2962 inFlight.mAlarmType, inFlight.mTag, -1, false);
2963 } else {
2964 // should never happen
2965 mLog.w("Alarm wakelock still held but sent queue empty");
2966 mWakeLock.setWorkSource(null);
2967 }
2968 }
2969 }
2970
2971 /**
2972 * Callback that arrives when a direct-call alarm reports that delivery has finished
2973 */
2974 @Override
2975 public void alarmComplete(IBinder who) {
2976 if (who == null) {
2977 Slog.w(TAG, "Invalid alarmComplete: uid=" + Binder.getCallingUid()
2978 + " pid=" + Binder.getCallingPid());
2979 return;
2980 }
2981
2982 final long ident = Binder.clearCallingIdentity();
2983 try {
2984 synchronized (mLock) {
2985 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
2986 InFlight inflight = removeLocked(who);
2987 if (inflight != null) {
2988 if (DEBUG_LISTENER_CALLBACK) {
2989 Slog.i(TAG, "alarmComplete() from " + who);
2990 }
2991 updateTrackingLocked(inflight);
2992 } else {
2993 // Delivery timed out, and the timeout handling already took care of
2994 // updating our tracking here, so we needn't do anything further.
2995 if (DEBUG_LISTENER_CALLBACK) {
2996 Slog.i(TAG, "Late alarmComplete() from " + who);
2997 }
2998 }
2999 }
3000 } finally {
3001 Binder.restoreCallingIdentity(ident);
3002 }
3003 }
3004
3005 /**
3006 * Callback that arrives when a PendingIntent alarm has finished delivery
3007 */
3008 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003009 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
3010 String resultData, Bundle resultExtras) {
3011 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003012 updateTrackingLocked(removeLocked(pi, intent));
3013 }
3014 }
3015
3016 /**
3017 * Timeout of a direct-call alarm delivery
3018 */
3019 public void alarmTimedOut(IBinder who) {
3020 synchronized (mLock) {
3021 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08003022 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003023 // TODO: implement ANR policy for the target
3024 if (DEBUG_LISTENER_CALLBACK) {
3025 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003026 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003027 updateTrackingLocked(inflight);
Dianne Hackborn81038902012-11-26 17:04:09 -08003028 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003029 if (DEBUG_LISTENER_CALLBACK) {
3030 Slog.i(TAG, "Spurious timeout of listener " + who);
3031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003032 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003033 }
3034 }
3035
3036 /**
3037 * Deliver an alarm and set up the post-delivery handling appropriately
3038 */
3039 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
3040 if (alarm.operation != null) {
3041 // PendingIntent alarm
3042 try {
3043 alarm.operation.send(getContext(), 0,
3044 mBackgroundIntent.putExtra(
3045 Intent.EXTRA_ALARM_COUNT, alarm.count),
3046 mDeliveryTracker, mHandler, null,
3047 allowWhileIdle ? mIdleOptions : null);
3048 } catch (PendingIntent.CanceledException e) {
3049 if (alarm.repeatInterval > 0) {
3050 // This IntentSender is no longer valid, but this
3051 // is a repeating alarm, so toss it
3052 removeImpl(alarm.operation);
3053 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003054 // No actual delivery was possible, so the delivery tracker's
3055 // 'finished' callback won't be invoked. We also don't need
3056 // to do any wakelock or stats tracking, so we have nothing
3057 // left to do here but go on to the next thing.
3058 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003059 }
3060 } else {
3061 // Direct listener callback alarm
3062 try {
3063 if (DEBUG_LISTENER_CALLBACK) {
3064 Slog.v(TAG, "Alarm to uid=" + alarm.uid
3065 + " listener=" + alarm.listener.asBinder());
3066 }
3067 alarm.listener.doAlarm(this);
3068 mHandler.sendMessageDelayed(
3069 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
3070 alarm.listener.asBinder()),
3071 mConstants.LISTENER_TIMEOUT);
3072 } catch (Exception e) {
3073 if (DEBUG_LISTENER_CALLBACK) {
3074 Slog.i(TAG, "Alarm undeliverable to listener "
3075 + alarm.listener.asBinder(), e);
3076 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003077 // As in the PendingIntent.CanceledException case, delivery of the
3078 // alarm was not possible, so we have no wakelock or timeout or
3079 // stats management to do. It threw before we posted the delayed
3080 // timeout message, so we're done here.
3081 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003082 }
3083 }
3084
3085 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08003086 if (DEBUG_WAKELOCK) {
3087 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
3088 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003089 if (mBroadcastRefCount == 0) {
3090 setWakelockWorkSource(alarm.operation, alarm.workSource,
3091 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
3092 true);
3093 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003094 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003095 }
3096 final InFlight inflight = new InFlight(AlarmManagerService.this,
3097 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
3098 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
3099 mInFlight.add(inflight);
3100 mBroadcastRefCount++;
3101
3102 if (allowWhileIdle) {
3103 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
3104 mLastAllowWhileIdleDispatch.put(alarm.uid, nowELAPSED);
3105 if (RECORD_DEVICE_IDLE_ALARMS) {
3106 IdleDispatchEntry ent = new IdleDispatchEntry();
3107 ent.uid = alarm.uid;
3108 ent.pkg = alarm.packageName;
3109 ent.tag = alarm.statsTag;
3110 ent.op = "DELIVER";
3111 ent.elapsedRealtime = nowELAPSED;
3112 mAllowWhileIdleDispatches.add(ent);
3113 }
3114 }
3115
3116 final BroadcastStats bs = inflight.mBroadcastStats;
3117 bs.count++;
3118 if (bs.nesting == 0) {
3119 bs.nesting = 1;
3120 bs.startTime = nowELAPSED;
3121 } else {
3122 bs.nesting++;
3123 }
3124 final FilterStats fs = inflight.mFilterStats;
3125 fs.count++;
3126 if (fs.nesting == 0) {
3127 fs.nesting = 1;
3128 fs.startTime = nowELAPSED;
3129 } else {
3130 fs.nesting++;
3131 }
3132 if (alarm.type == ELAPSED_REALTIME_WAKEUP
3133 || alarm.type == RTC_WAKEUP) {
3134 bs.numWakeup++;
3135 fs.numWakeup++;
3136 if (alarm.workSource != null && alarm.workSource.size() > 0) {
3137 for (int wi=0; wi<alarm.workSource.size(); wi++) {
Christopher Tate0029f572016-06-14 10:16:28 -07003138 final String wsName = alarm.workSource.getName(wi);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003139 ActivityManager.noteWakeupAlarm(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003140 alarm.operation, alarm.workSource.get(wi),
Christopher Tate0029f572016-06-14 10:16:28 -07003141 (wsName != null) ? wsName : alarm.packageName,
3142 alarm.statsTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08003143 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003144 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003145 ActivityManager.noteWakeupAlarm(
Joe Onorato78bcdf92016-05-09 10:10:29 -07003146 alarm.operation, alarm.uid, alarm.packageName, alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003147 }
3148 }
3149 }
3150 }
3151}