blob: 0d438cb0f87ab106d94f153e2aec6397b9e86cfb [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
957 | Intent.FLAG_RECEIVER_FOREGROUND), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700958 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800959 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
960 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800961 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700962 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963
964 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -0800965 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 mClockReceiver.scheduleTimeTickEvent();
967 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700968 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 mUninstallReceiver = new UninstallReceiver();
970
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800971 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800972 AlarmThread waitThread = new AlarmThread();
973 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800975 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800977
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700978 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800979 ActivityManager.getService().registerUidObserver(new UidObserver(),
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800980 ActivityManager.UID_OBSERVER_IDLE, ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700981 } catch (RemoteException e) {
982 // ignored; both services live in system_server
983 }
984
Adam Lesinski182f73f2013-12-05 16:48:06 -0800985 publishBinderService(Context.ALARM_SERVICE, mService);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -0800986 publishLocalService(LocalService.class, new LocalService());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800988
989 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -0700990 public void onBootPhase(int phase) {
991 if (phase == PHASE_SYSTEM_SERVICES_READY) {
992 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -0700993 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800994 mLocalDeviceIdleController
995 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackborna750a632015-06-16 17:18:23 -0700996 }
997 }
998
999 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000 protected void finalize() throws Throwable {
1001 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001002 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 } finally {
1004 super.finalize();
1005 }
1006 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001007
Adam Lesinski182f73f2013-12-05 16:48:06 -08001008 void setTimeZoneImpl(String tz) {
1009 if (TextUtils.isEmpty(tz)) {
1010 return;
David Christieebe51fc2013-07-26 13:23:29 -07001011 }
1012
Adam Lesinski182f73f2013-12-05 16:48:06 -08001013 TimeZone zone = TimeZone.getTimeZone(tz);
1014 // Prevent reentrant calls from stepping on each other when writing
1015 // the time zone property
1016 boolean timeZoneWasChanged = false;
1017 synchronized (this) {
1018 String current = SystemProperties.get(TIMEZONE_PROPERTY);
1019 if (current == null || !current.equals(zone.getID())) {
1020 if (localLOGV) {
1021 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
1022 }
1023 timeZoneWasChanged = true;
1024 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
1025 }
1026
1027 // Update the kernel timezone information
1028 // Kernel tracks time offsets as 'minutes west of GMT'
1029 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001030 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001031 }
1032
1033 TimeZone.setDefault(null);
1034
1035 if (timeZoneWasChanged) {
1036 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
1037 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
1038 intent.putExtra("time-zone", zone.getID());
1039 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1040 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001042
Adam Lesinski182f73f2013-12-05 16:48:06 -08001043 void removeImpl(PendingIntent operation) {
1044 if (operation == null) {
1045 return;
1046 }
1047 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001048 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001049 }
1050 }
1051
1052 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001053 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1054 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1055 int callingUid, String callingPackage) {
1056 // must be *either* PendingIntent or AlarmReceiver, but not both
1057 if ((operation == null && directReceiver == null)
1058 || (operation != null && directReceiver != null)) {
1059 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1060 // NB: previous releases failed silently here, so we are continuing to do the same
1061 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 return;
1063 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001064
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001065 // Sanity check the window length. This will catch people mistakenly
1066 // trying to pass an end-of-window timestamp rather than a duration.
1067 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1068 Slog.w(TAG, "Window length " + windowLength
1069 + "ms suspiciously long; limiting to 1 hour");
1070 windowLength = AlarmManager.INTERVAL_HOUR;
1071 }
1072
Christopher Tate498c6cb2014-11-17 16:09:27 -08001073 // Sanity check the recurrence interval. This will catch people who supply
1074 // seconds when the API expects milliseconds.
Dianne Hackborna750a632015-06-16 17:18:23 -07001075 final long minInterval = mConstants.MIN_INTERVAL;
1076 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001077 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001078 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001079 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001080 interval = minInterval;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001081 }
1082
Christopher Tatee0a22b32013-07-11 14:43:13 -07001083 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1084 throw new IllegalArgumentException("Invalid alarm type " + type);
1085 }
1086
Christopher Tate5f221e82013-07-30 17:13:15 -07001087 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001088 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001089 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001090 + " pid=" + what);
1091 triggerAtTime = 0;
1092 }
1093
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001094 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001095 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1096 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001097 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001098 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1099
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001100 final long maxElapsed;
1101 if (windowLength == AlarmManager.WINDOW_EXACT) {
1102 maxElapsed = triggerElapsed;
1103 } else if (windowLength < 0) {
1104 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001105 // Fix this window in place, so that as time approaches we don't collapse it.
1106 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001107 } else {
1108 maxElapsed = triggerElapsed + windowLength;
1109 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001110
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001112 if (DEBUG_BATCH) {
1113 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001114 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001115 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001116 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001118 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001119 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1120 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 }
1122 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123
Christopher Tate3e04b472013-10-21 17:51:31 -07001124 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001125 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1126 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1127 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001128 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001129 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1130 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001131 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001132 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001133 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1134 + " -- package not allowed to start");
1135 return;
1136 }
1137 } catch (RemoteException e) {
1138 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001139 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001140 setImplLocked(a, false, doValidate);
1141 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001142
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001143 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1144 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001145 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001146 // The caller has given the time they want this to happen at, however we need
1147 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001148 // bring us out of idle at an earlier time.
1149 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001150 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001151 }
1152 // Add fuzz to make the alarm go off some time before the actual desired time.
1153 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001154 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001155 if (fuzz > 0) {
1156 if (mRandom == null) {
1157 mRandom = new Random();
1158 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001159 final int delta = mRandom.nextInt(fuzz);
1160 a.whenElapsed -= delta;
1161 if (false) {
1162 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1163 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1164 Slog.d(TAG, "Applied fuzz: " + fuzz);
1165 Slog.d(TAG, "Final delta: " + delta);
1166 Slog.d(TAG, "Final when: " + a.whenElapsed);
1167 }
1168 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001169 }
1170
1171 } else if (mPendingIdleUntil != null) {
1172 // We currently have an idle until alarm scheduled; if the new alarm has
1173 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001174 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1175 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1176 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001177 == 0) {
1178 mPendingWhileIdleAlarms.add(a);
1179 return;
1180 }
1181 }
1182
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001183 if (RECORD_DEVICE_IDLE_ALARMS) {
1184 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1185 IdleDispatchEntry ent = new IdleDispatchEntry();
1186 ent.uid = a.uid;
1187 ent.pkg = a.operation.getCreatorPackage();
1188 ent.tag = a.operation.getTag("");
1189 ent.op = "SET";
1190 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1191 ent.argRealtime = a.whenElapsed;
1192 mAllowWhileIdleDispatches.add(ent);
1193 }
1194 }
1195
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001196 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
1197 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -07001198 if (whichBatch < 0) {
1199 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001200 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001201 } else {
Christopher Tate385e4982013-07-23 18:22:29 -07001202 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001203 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001204 // The start time of this batch advanced, so batch ordering may
1205 // have just been broken. Move it to where it now belongs.
1206 mAlarmBatches.remove(whichBatch);
1207 addBatchLocked(mAlarmBatches, batch);
1208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 }
1210
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001211 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001212 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001213 }
1214
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001215 boolean needRebatch = false;
1216
1217 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001218 if (RECORD_DEVICE_IDLE_ALARMS) {
1219 if (mPendingIdleUntil == null) {
1220 IdleDispatchEntry ent = new IdleDispatchEntry();
1221 ent.uid = 0;
1222 ent.pkg = "START IDLE";
1223 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1224 mAllowWhileIdleDispatches.add(ent);
1225 }
1226 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001227 mPendingIdleUntil = a;
Dianne Hackborna750a632015-06-16 17:18:23 -07001228 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001229 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001230 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1231 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1232 mNextWakeFromIdle = a;
1233 // If this wake from idle is earlier than whatever was previously scheduled,
1234 // and we are currently idling, then we need to rebatch alarms in case the idle
1235 // until time needs to be updated.
1236 if (mPendingIdleUntil != null) {
1237 needRebatch = true;
1238 }
1239 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001240 }
1241
1242 if (!rebatching) {
1243 if (DEBUG_VALIDATE) {
1244 if (doValidate && !validateConsistencyLocked()) {
1245 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1246 + " when(hex)=" + Long.toHexString(a.when)
1247 + " whenElapsed=" + a.whenElapsed
1248 + " maxWhenElapsed=" + a.maxWhenElapsed
1249 + " interval=" + a.repeatInterval + " op=" + a.operation
1250 + " flags=0x" + Integer.toHexString(a.flags));
1251 rebatchAllAlarmsLocked(false);
1252 needRebatch = false;
1253 }
1254 }
1255
1256 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001257 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001258 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001259
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001260 rescheduleKernelAlarmsLocked();
1261 updateNextAlarmClockLocked();
1262 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001263 }
1264
Adam Lesinski182f73f2013-12-05 16:48:06 -08001265 private final IBinder mService = new IAlarmManager.Stub() {
1266 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001267 public void set(String callingPackage,
1268 int type, long triggerAtTime, long windowLength, long interval, int flags,
1269 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1270 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001271 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001272
1273 // make sure the caller is not lying about which package should be blamed for
1274 // wakelock time spent in alarm delivery
1275 mAppOps.checkPackage(callingUid, callingPackage);
1276
1277 // Repeating alarms must use PendingIntent, not direct listener
1278 if (interval != 0) {
1279 if (directReceiver != null) {
1280 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1281 }
1282 }
1283
Adam Lesinski182f73f2013-12-05 16:48:06 -08001284 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001285 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001286 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001287 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001288 }
1289
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001290 // No incoming callers can request either WAKE_FROM_IDLE or
1291 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1292 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1293 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1294
1295 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1296 // manager when to come out of idle mode, which is only for DeviceIdleController.
1297 if (callingUid != Process.SYSTEM_UID) {
1298 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1299 }
1300
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001301 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001302 if (windowLength == AlarmManager.WINDOW_EXACT) {
1303 flags |= AlarmManager.FLAG_STANDALONE;
1304 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001305
1306 // If this alarm is for an alarm clock, then it must be standalone and we will
1307 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001308 if (alarmClock != null) {
1309 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001310
1311 // If the caller is a core system component or on the user's whitelist, and not calling
1312 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1313 // This means we will allow these alarms to go off as normal even while idle, with no
1314 // timing restrictions.
1315 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
1316 || Arrays.binarySearch(mDeviceIdleUserWhitelist,
1317 UserHandle.getAppId(callingUid)) >= 0)) {
1318 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1319 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001320 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001321
Christopher Tate14a7bb02015-10-01 10:24:31 -07001322 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1323 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001324 }
Christopher Tate89779822012-08-31 14:40:03 -07001325
Adam Lesinski182f73f2013-12-05 16:48:06 -08001326 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001327 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001328 getContext().enforceCallingOrSelfPermission(
1329 "android.permission.SET_TIME",
1330 "setTime");
1331
Greg Hackmann0cab8962014-02-21 16:35:52 -08001332 if (mNativeData == 0) {
1333 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1334 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001335 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001336
1337 synchronized (mLock) {
1338 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001341
1342 @Override
1343 public void setTimeZone(String tz) {
1344 getContext().enforceCallingOrSelfPermission(
1345 "android.permission.SET_TIME_ZONE",
1346 "setTimeZone");
1347
1348 final long oldId = Binder.clearCallingIdentity();
1349 try {
1350 setTimeZoneImpl(tz);
1351 } finally {
1352 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001353 }
1354 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001355
Adam Lesinski182f73f2013-12-05 16:48:06 -08001356 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001357 public void remove(PendingIntent operation, IAlarmListener listener) {
1358 if (operation == null && listener == null) {
1359 Slog.w(TAG, "remove() with no intent or listener");
1360 return;
1361 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001362
Christopher Tate14a7bb02015-10-01 10:24:31 -07001363 synchronized (mLock) {
1364 removeLocked(operation, listener);
1365 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001367
Adam Lesinski182f73f2013-12-05 16:48:06 -08001368 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001369 public long getNextWakeFromIdleTime() {
1370 return getNextWakeFromIdleTimeImpl();
1371 }
1372
1373 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001374 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001375 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1376 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1377 "getNextAlarmClock", null);
1378
1379 return getNextAlarmClockImpl(userId);
1380 }
1381
1382 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001383 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1384 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1385 != PackageManager.PERMISSION_GRANTED) {
1386 pw.println("Permission Denial: can't dump AlarmManager from from pid="
1387 + Binder.getCallingPid()
1388 + ", uid=" + Binder.getCallingUid());
1389 return;
Christopher Tate4cb338d2013-07-26 13:11:31 -07001390 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001391
Adam Lesinski182f73f2013-12-05 16:48:06 -08001392 dumpImpl(pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001393 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001394 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001395
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001396 public final class LocalService {
1397 public void setDeviceIdleUserWhitelist(int[] appids) {
1398 setDeviceIdleUserWhitelistImpl(appids);
1399 }
1400 }
1401
Adam Lesinski182f73f2013-12-05 16:48:06 -08001402 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 synchronized (mLock) {
1404 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001405 mConstants.dump(pw);
1406 pw.println();
1407
Christopher Tatee0a22b32013-07-11 14:43:13 -07001408 final long nowRTC = System.currentTimeMillis();
1409 final long nowELAPSED = SystemClock.elapsedRealtime();
1410 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1411
Dianne Hackborna750a632015-06-16 17:18:23 -07001412 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001413 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001414 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001415 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001416 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001417 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001418 pw.print(" mLastTimeChangeRealtime=");
Dianne Hackbornc3527222015-05-13 14:03:20 -07001419 TimeUtils.formatDuration(mLastTimeChangeRealtime, pw);
1420 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001421 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001422 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001423 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1424 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001425 pw.print(" Max wakeup delay: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001426 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1427 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001428 pw.print(" Time since last dispatch: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001429 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1430 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001431 pw.print(" Next non-wakeup delivery time: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001432 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1433 pw.println();
1434 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001435
1436 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1437 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001438 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001439 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001440 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001441 pw.print(" Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001442 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001443 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
1444 pw.print(" set at "); TimeUtils.formatDuration(mLastWakeupSet, nowELAPSED, pw);
1445 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001446 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001447 pw.println(" mDeviceIdleUserWhitelist=" + Arrays.toString(mDeviceIdleUserWhitelist));
Christopher Tatee0a22b32013-07-11 14:43:13 -07001448
John Spurlock604a5ee2015-06-01 12:27:22 -04001449 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001450 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001451 final TreeSet<Integer> users = new TreeSet<>();
1452 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1453 users.add(mNextAlarmClockForUser.keyAt(i));
1454 }
1455 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1456 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1457 }
1458 for (int user : users) {
1459 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1460 final long time = next != null ? next.getTriggerTime() : 0;
1461 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001462 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001463 pw.print(" pendingSend:"); pw.print(pendingSend);
1464 pw.print(" time:"); pw.print(time);
1465 if (time > 0) {
1466 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1467 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1468 }
1469 pw.println();
1470 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001471 if (mAlarmBatches.size() > 0) {
1472 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001473 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001474 pw.println(mAlarmBatches.size());
1475 for (Batch b : mAlarmBatches) {
1476 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001477 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001478 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001480 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001481 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001482 pw.println(" Idle mode state:");
1483 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001484 if (mPendingIdleUntil != null) {
1485 pw.println(mPendingIdleUntil);
Dianne Hackbornf3831292015-10-15 14:51:06 -07001486 mPendingIdleUntil.dump(pw, " ", nowRTC, nowELAPSED, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001487 } else {
1488 pw.println("null");
1489 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001490 pw.println(" Pending alarms:");
1491 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001492 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001493 if (mNextWakeFromIdle != null) {
1494 pw.println();
1495 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
1496 mNextWakeFromIdle.dump(pw, " ", nowRTC, nowELAPSED, sdf);
1497 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001498
1499 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001500 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001501 if (mPendingNonWakeupAlarms.size() > 0) {
1502 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001503 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001504 } else {
1505 pw.println("(none)");
1506 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001507 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001508 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1509 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001510 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001511 pw.print(", max non-interactive time: ");
1512 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1513 pw.println();
1514
1515 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001516 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001517 pw.println();
1518
Christopher Tate7f2a0352015-12-08 10:24:33 -08001519 if (mInFlight.size() > 0) {
1520 pw.println("Outstanding deliveries:");
1521 for (int i = 0; i < mInFlight.size(); i++) {
1522 pw.print(" #"); pw.print(i); pw.print(": ");
1523 pw.println(mInFlight.get(i));
1524 }
1525 pw.println();
1526 }
1527
Dianne Hackborna750a632015-06-16 17:18:23 -07001528 pw.print(" mAllowWhileIdleMinTime=");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001529 TimeUtils.formatDuration(mAllowWhileIdleMinTime, pw);
1530 pw.println();
1531 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001532 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001533 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
1534 pw.print(" UID ");
1535 UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
1536 pw.print(": ");
1537 TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i),
1538 nowELAPSED, pw);
1539 pw.println();
1540 }
1541 }
1542 pw.println();
1543
Dianne Hackborn81038902012-11-26 17:04:09 -08001544 if (mLog.dump(pw, " Recent problems", " ")) {
1545 pw.println();
1546 }
1547
1548 final FilterStats[] topFilters = new FilterStats[10];
1549 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1550 @Override
1551 public int compare(FilterStats lhs, FilterStats rhs) {
1552 if (lhs.aggregateTime < rhs.aggregateTime) {
1553 return 1;
1554 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1555 return -1;
1556 }
1557 return 0;
1558 }
1559 };
1560 int len = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001561 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1562 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1563 for (int ip=0; ip<uidStats.size(); ip++) {
1564 BroadcastStats bs = uidStats.valueAt(ip);
1565 for (int is=0; is<bs.filterStats.size(); is++) {
1566 FilterStats fs = bs.filterStats.valueAt(is);
1567 int pos = len > 0
1568 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1569 if (pos < 0) {
1570 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001571 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001572 if (pos < topFilters.length) {
1573 int copylen = topFilters.length - pos - 1;
1574 if (copylen > 0) {
1575 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1576 }
1577 topFilters[pos] = fs;
1578 if (len < topFilters.length) {
1579 len++;
1580 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001581 }
1582 }
1583 }
1584 }
1585 if (len > 0) {
1586 pw.println(" Top Alarms:");
1587 for (int i=0; i<len; i++) {
1588 FilterStats fs = topFilters[i];
1589 pw.print(" ");
1590 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1591 TimeUtils.formatDuration(fs.aggregateTime, pw);
1592 pw.print(" running, "); pw.print(fs.numWakeup);
1593 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001594 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1595 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001596 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001597 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001598 pw.println();
1599 }
1600 }
1601
1602 pw.println(" ");
1603 pw.println(" Alarm Stats:");
1604 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001605 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1606 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1607 for (int ip=0; ip<uidStats.size(); ip++) {
1608 BroadcastStats bs = uidStats.valueAt(ip);
1609 pw.print(" ");
1610 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1611 UserHandle.formatUid(pw, bs.mUid);
1612 pw.print(":");
1613 pw.print(bs.mPackageName);
1614 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1615 pw.print(" running, "); pw.print(bs.numWakeup);
1616 pw.println(" wakeups:");
1617 tmpFilters.clear();
1618 for (int is=0; is<bs.filterStats.size(); is++) {
1619 tmpFilters.add(bs.filterStats.valueAt(is));
1620 }
1621 Collections.sort(tmpFilters, comparator);
1622 for (int i=0; i<tmpFilters.size(); i++) {
1623 FilterStats fs = tmpFilters.get(i);
1624 pw.print(" ");
1625 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1626 TimeUtils.formatDuration(fs.aggregateTime, pw);
1627 pw.print(" "); pw.print(fs.numWakeup);
1628 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001629 pw.print(" alarms, last ");
1630 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1631 pw.println(":");
1632 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001633 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001634 pw.println();
1635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 }
1637 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001638
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001639 if (RECORD_DEVICE_IDLE_ALARMS) {
1640 pw.println();
1641 pw.println(" Allow while idle dispatches:");
1642 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
1643 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
1644 pw.print(" ");
1645 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
1646 pw.print(": ");
1647 UserHandle.formatUid(pw, ent.uid);
1648 pw.print(":");
1649 pw.println(ent.pkg);
1650 if (ent.op != null) {
1651 pw.print(" ");
1652 pw.print(ent.op);
1653 pw.print(" / ");
1654 pw.print(ent.tag);
1655 if (ent.argRealtime != 0) {
1656 pw.print(" (");
1657 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
1658 pw.print(")");
1659 }
1660 pw.println();
1661 }
1662 }
1663 }
1664
Christopher Tate18a75f12013-07-01 18:18:59 -07001665 if (WAKEUP_STATS) {
1666 pw.println();
1667 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001668 long last = -1;
1669 for (WakeupEvent event : mRecentWakeups) {
1670 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1671 pw.print('|');
1672 if (last < 0) {
1673 pw.print('0');
1674 } else {
1675 pw.print(event.when - last);
1676 }
1677 last = event.when;
1678 pw.print('|'); pw.print(event.uid);
1679 pw.print('|'); pw.print(event.action);
1680 pw.println();
1681 }
1682 pw.println();
1683 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 }
1685 }
1686
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001687 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001688 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
1689 PrintWriter pw = new PrintWriter(bs);
1690 final long nowRTC = System.currentTimeMillis();
1691 final long nowELAPSED = SystemClock.elapsedRealtime();
1692 final int NZ = mAlarmBatches.size();
1693 for (int iz = 0; iz < NZ; iz++) {
1694 Batch bz = mAlarmBatches.get(iz);
1695 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001696 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001697 pw.flush();
1698 Slog.v(TAG, bs.toString());
1699 bs.reset();
1700 }
1701 }
1702
1703 private boolean validateConsistencyLocked() {
1704 if (DEBUG_VALIDATE) {
1705 long lastTime = Long.MIN_VALUE;
1706 final int N = mAlarmBatches.size();
1707 for (int i = 0; i < N; i++) {
1708 Batch b = mAlarmBatches.get(i);
1709 if (b.start >= lastTime) {
1710 // duplicate start times are okay because of standalone batches
1711 lastTime = b.start;
1712 } else {
1713 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001714 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1715 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001716 return false;
1717 }
1718 }
1719 }
1720 return true;
1721 }
1722
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001723 private Batch findFirstWakeupBatchLocked() {
1724 final int N = mAlarmBatches.size();
1725 for (int i = 0; i < N; i++) {
1726 Batch b = mAlarmBatches.get(i);
1727 if (b.hasWakeups()) {
1728 return b;
1729 }
1730 }
1731 return null;
1732 }
1733
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001734 long getNextWakeFromIdleTimeImpl() {
1735 synchronized (mLock) {
1736 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
1737 }
1738 }
1739
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001740 void setDeviceIdleUserWhitelistImpl(int[] appids) {
1741 synchronized (mLock) {
1742 mDeviceIdleUserWhitelist = appids;
1743 }
1744 }
1745
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001746 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001747 synchronized (mLock) {
1748 return mNextAlarmClockForUser.get(userId);
1749 }
1750 }
1751
1752 /**
1753 * Recomputes the next alarm clock for all users.
1754 */
1755 private void updateNextAlarmClockLocked() {
1756 if (!mNextAlarmClockMayChange) {
1757 return;
1758 }
1759 mNextAlarmClockMayChange = false;
1760
Jose Lima235510e2014-08-13 12:50:01 -07001761 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001762 nextForUser.clear();
1763
1764 final int N = mAlarmBatches.size();
1765 for (int i = 0; i < N; i++) {
1766 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
1767 final int M = alarms.size();
1768
1769 for (int j = 0; j < M; j++) {
1770 Alarm a = alarms.get(j);
1771 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001772 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07001773 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001774
1775 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07001776 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001777 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02001778 " for user " + userId);
1779 }
1780
1781 // Alarms and batches are sorted by time, no need to compare times here.
1782 if (nextForUser.get(userId) == null) {
1783 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07001784 } else if (a.alarmClock.equals(current)
1785 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
1786 // same/earlier time and it's the one we cited before, so stick with it
1787 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001788 }
1789 }
1790 }
1791 }
1792
1793 // Update mNextAlarmForUser with new values.
1794 final int NN = nextForUser.size();
1795 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07001796 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001797 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001798 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001799 if (!newAlarm.equals(currentAlarm)) {
1800 updateNextAlarmInfoForUserLocked(userId, newAlarm);
1801 }
1802 }
1803
1804 // Remove users without any alarm clocks scheduled.
1805 final int NNN = mNextAlarmClockForUser.size();
1806 for (int i = NNN - 1; i >= 0; i--) {
1807 int userId = mNextAlarmClockForUser.keyAt(i);
1808 if (nextForUser.get(userId) == null) {
1809 updateNextAlarmInfoForUserLocked(userId, null);
1810 }
1811 }
1812 }
1813
Jose Lima235510e2014-08-13 12:50:01 -07001814 private void updateNextAlarmInfoForUserLocked(int userId,
1815 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001816 if (alarmClock != null) {
1817 if (DEBUG_ALARM_CLOCK) {
1818 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001819 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02001820 }
1821 mNextAlarmClockForUser.put(userId, alarmClock);
1822 } else {
1823 if (DEBUG_ALARM_CLOCK) {
1824 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
1825 }
1826 mNextAlarmClockForUser.remove(userId);
1827 }
1828
1829 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
1830 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1831 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1832 }
1833
1834 /**
1835 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
1836 * for which alarm clocks have changed since the last call to this.
1837 *
1838 * Do not call with a lock held. Only call from mHandler's thread.
1839 *
1840 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
1841 */
1842 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07001843 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001844 pendingUsers.clear();
1845
1846 synchronized (mLock) {
1847 final int N = mPendingSendNextAlarmClockChangedForUser.size();
1848 for (int i = 0; i < N; i++) {
1849 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
1850 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
1851 }
1852 mPendingSendNextAlarmClockChangedForUser.clear();
1853 }
1854
1855 final int N = pendingUsers.size();
1856 for (int i = 0; i < N; i++) {
1857 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001858 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001859 Settings.System.putStringForUser(getContext().getContentResolver(),
1860 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01001861 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02001862 userId);
1863
1864 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
1865 new UserHandle(userId));
1866 }
1867 }
1868
1869 /**
1870 * Formats an alarm like platform/packages/apps/DeskClock used to.
1871 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01001872 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
1873 int userId) {
1874 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02001875 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
1876 return (info == null) ? "" :
1877 DateFormat.format(pattern, info.getTriggerTime()).toString();
1878 }
1879
Adam Lesinski182f73f2013-12-05 16:48:06 -08001880 void rescheduleKernelAlarmsLocked() {
1881 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
1882 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001883 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001884 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001885 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001886 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07001887 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001888 mNextWakeup = firstWakeup.start;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001889 mLastWakeupSet = SystemClock.elapsedRealtime();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001890 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001891 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001892 if (firstBatch != firstWakeup) {
1893 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001894 }
1895 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001896 if (mPendingNonWakeupAlarms.size() > 0) {
1897 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
1898 nextNonWakeup = mNextNonWakeupDeliveryTime;
1899 }
1900 }
Prashant Malani753e9e02015-06-10 17:43:49 -07001901 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001902 mNextNonWakeup = nextNonWakeup;
1903 setLocked(ELAPSED_REALTIME, nextNonWakeup);
1904 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001905 }
1906
Christopher Tate14a7bb02015-10-01 10:24:31 -07001907 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001908 boolean didRemove = false;
1909 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1910 Batch b = mAlarmBatches.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -07001911 didRemove |= b.remove(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001912 if (b.size() == 0) {
1913 mAlarmBatches.remove(i);
1914 }
1915 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001916 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001917 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001918 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1919 mPendingWhileIdleAlarms.remove(i);
1920 }
1921 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001922
1923 if (didRemove) {
1924 if (DEBUG_BATCH) {
1925 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
1926 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001927 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001928 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001929 mPendingIdleUntil = null;
1930 restorePending = true;
1931 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001932 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001933 mNextWakeFromIdle = null;
1934 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001935 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001936 if (restorePending) {
1937 restorePendingWhileIdleAlarmsLocked();
1938 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001939 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001940 }
1941 }
1942
1943 void removeLocked(String packageName) {
1944 boolean didRemove = false;
1945 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1946 Batch b = mAlarmBatches.get(i);
1947 didRemove |= b.remove(packageName);
1948 if (b.size() == 0) {
1949 mAlarmBatches.remove(i);
1950 }
1951 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001952 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001953 final Alarm a = mPendingWhileIdleAlarms.get(i);
1954 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001955 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1956 mPendingWhileIdleAlarms.remove(i);
1957 }
1958 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001959
1960 if (didRemove) {
1961 if (DEBUG_BATCH) {
1962 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1963 }
1964 rebatchAllAlarmsLocked(true);
1965 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001966 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001967 }
1968 }
1969
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001970 void removeForStoppedLocked(int uid) {
1971 boolean didRemove = false;
1972 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1973 Batch b = mAlarmBatches.get(i);
1974 didRemove |= b.removeForStopped(uid);
1975 if (b.size() == 0) {
1976 mAlarmBatches.remove(i);
1977 }
1978 }
1979 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1980 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08001981 if (a.uid == uid) {
1982 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1983 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001984 }
1985 }
1986
1987 if (didRemove) {
1988 if (DEBUG_BATCH) {
1989 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1990 }
1991 rebatchAllAlarmsLocked(true);
1992 rescheduleKernelAlarmsLocked();
1993 updateNextAlarmClockLocked();
1994 }
1995 }
1996
Adam Lesinski182f73f2013-12-05 16:48:06 -08001997 void removeUserLocked(int userHandle) {
1998 boolean didRemove = false;
1999 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2000 Batch b = mAlarmBatches.get(i);
2001 didRemove |= b.remove(userHandle);
2002 if (b.size() == 0) {
2003 mAlarmBatches.remove(i);
2004 }
2005 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002006 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002007 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002008 == userHandle) {
2009 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2010 mPendingWhileIdleAlarms.remove(i);
2011 }
2012 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002013 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
2014 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
2015 mLastAllowWhileIdleDispatch.removeAt(i);
2016 }
2017 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002018
2019 if (didRemove) {
2020 if (DEBUG_BATCH) {
2021 Slog.v(TAG, "remove(user) changed bounds; rebatching");
2022 }
2023 rebatchAllAlarmsLocked(true);
2024 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002025 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002026 }
2027 }
2028
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002029 void interactiveStateChangedLocked(boolean interactive) {
2030 if (mInteractive != interactive) {
2031 mInteractive = interactive;
2032 final long nowELAPSED = SystemClock.elapsedRealtime();
2033 if (interactive) {
2034 if (mPendingNonWakeupAlarms.size() > 0) {
2035 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2036 mTotalDelayTime += thisDelayTime;
2037 if (mMaxDelayTime < thisDelayTime) {
2038 mMaxDelayTime = thisDelayTime;
2039 }
2040 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2041 mPendingNonWakeupAlarms.clear();
2042 }
2043 if (mNonInteractiveStartTime > 0) {
2044 long dur = nowELAPSED - mNonInteractiveStartTime;
2045 if (dur > mNonInteractiveTime) {
2046 mNonInteractiveTime = dur;
2047 }
2048 }
2049 } else {
2050 mNonInteractiveStartTime = nowELAPSED;
2051 }
2052 }
2053 }
2054
Adam Lesinski182f73f2013-12-05 16:48:06 -08002055 boolean lookForPackageLocked(String packageName) {
2056 for (int i = 0; i < mAlarmBatches.size(); i++) {
2057 Batch b = mAlarmBatches.get(i);
2058 if (b.hasPackage(packageName)) {
2059 return true;
2060 }
2061 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002062 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002063 final Alarm a = mPendingWhileIdleAlarms.get(i);
2064 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002065 return true;
2066 }
2067 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002068 return false;
2069 }
2070
2071 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002072 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002073 // The kernel never triggers alarms with negative wakeup times
2074 // so we ensure they are positive.
2075 long alarmSeconds, alarmNanoseconds;
2076 if (when < 0) {
2077 alarmSeconds = 0;
2078 alarmNanoseconds = 0;
2079 } else {
2080 alarmSeconds = when / 1000;
2081 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2082 }
2083
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002084 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002085 } else {
2086 Message msg = Message.obtain();
2087 msg.what = ALARM_EVENT;
2088
2089 mHandler.removeMessages(ALARM_EVENT);
2090 mHandler.sendMessageAtTime(msg, when);
2091 }
2092 }
2093
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002094 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002095 String prefix, String label, long nowRTC, long nowELAPSED, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002096 for (int i=list.size()-1; i>=0; i--) {
2097 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002098 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2099 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002100 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002101 }
2102 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002103
2104 private static final String labelForType(int type) {
2105 switch (type) {
2106 case RTC: return "RTC";
2107 case RTC_WAKEUP : return "RTC_WAKEUP";
2108 case ELAPSED_REALTIME : return "ELAPSED";
2109 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
2110 default:
2111 break;
2112 }
2113 return "--unknown--";
2114 }
2115
2116 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002117 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002118 for (int i=list.size()-1; i>=0; i--) {
2119 Alarm a = list.get(i);
2120 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002121 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2122 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002123 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002124 }
2125 }
2126
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002127 private native long init();
2128 private native void close(long nativeData);
2129 private native void set(long nativeData, int type, long seconds, long nanoseconds);
2130 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08002131 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002132 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002133
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002134 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002135 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002136 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002137 // batches are temporally sorted, so we need only pull from the
2138 // start of the list until we either empty it or hit a batch
2139 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07002140 while (mAlarmBatches.size() > 0) {
2141 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002142 if (batch.start > nowELAPSED) {
2143 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002144 break;
2145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002146
Christopher Tatee0a22b32013-07-11 14:43:13 -07002147 // We will (re)schedule some alarms now; don't let that interfere
2148 // with delivery of this current batch
2149 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002150
Christopher Tatee0a22b32013-07-11 14:43:13 -07002151 final int N = batch.size();
2152 for (int i = 0; i < N; i++) {
2153 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002154
2155 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
2156 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
2157 // schedule such alarms.
2158 long lastTime = mLastAllowWhileIdleDispatch.get(alarm.uid, 0);
2159 long minTime = lastTime + mAllowWhileIdleMinTime;
2160 if (nowELAPSED < minTime) {
2161 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
2162 // alarm went off for this app. Reschedule the alarm to be in the
2163 // correct time period.
2164 alarm.whenElapsed = minTime;
2165 if (alarm.maxWhenElapsed < minTime) {
2166 alarm.maxWhenElapsed = minTime;
2167 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002168 if (RECORD_DEVICE_IDLE_ALARMS) {
2169 IdleDispatchEntry ent = new IdleDispatchEntry();
2170 ent.uid = alarm.uid;
2171 ent.pkg = alarm.operation.getCreatorPackage();
2172 ent.tag = alarm.operation.getTag("");
2173 ent.op = "RESCHEDULE";
2174 ent.elapsedRealtime = nowELAPSED;
2175 ent.argRealtime = lastTime;
2176 mAllowWhileIdleDispatches.add(ent);
2177 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002178 setImplLocked(alarm, true, false);
2179 continue;
2180 }
2181 }
2182
Christopher Tatee0a22b32013-07-11 14:43:13 -07002183 alarm.count = 1;
2184 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002185 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
2186 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002187 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002188 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002189 if (mPendingIdleUntil == alarm) {
2190 mPendingIdleUntil = null;
2191 rebatchAllAlarmsLocked(false);
2192 restorePendingWhileIdleAlarmsLocked();
2193 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002194 if (mNextWakeFromIdle == alarm) {
2195 mNextWakeFromIdle = null;
2196 rebatchAllAlarmsLocked(false);
2197 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002198
2199 // Recurring alarms may have passed several alarm intervals while the
2200 // phone was asleep or off, so pass a trigger count when sending them.
2201 if (alarm.repeatInterval > 0) {
2202 // this adjustment will be zero if we're late by
2203 // less than one full repeat interval
2204 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
2205
2206 // Also schedule its next recurrence
2207 final long delta = alarm.count * alarm.repeatInterval;
2208 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07002209 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07002210 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07002211 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
2212 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08002213 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002214
Christopher Tate864d42e2014-12-02 11:48:53 -08002215 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002216 hasWakeup = true;
2217 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002218
2219 // We removed an alarm clock. Let the caller recompute the next alarm clock.
2220 if (alarm.alarmClock != null) {
2221 mNextAlarmClockMayChange = true;
2222 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07002223 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002224 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002225
Christopher Tate1590f1e2014-10-02 17:27:57 -07002226 // This is a new alarm delivery set; bump the sequence number to indicate that
2227 // all apps' alarm delivery classes should be recalculated.
2228 mCurrentSeq++;
2229 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002230 Collections.sort(triggerList, mAlarmDispatchComparator);
2231
2232 if (localLOGV) {
2233 for (int i=0; i<triggerList.size(); i++) {
2234 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
2235 }
2236 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002237
2238 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002239 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002241 /**
2242 * This Comparator sorts Alarms into increasing time order.
2243 */
2244 public static class IncreasingTimeOrder implements Comparator<Alarm> {
2245 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09002246 long when1 = a1.whenElapsed;
2247 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002248 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002249 return 1;
2250 }
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 }
2254 return 0;
2255 }
2256 }
2257
2258 private static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002259 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002260 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002261 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002262 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002263 public final IAlarmListener listener;
2264 public final String listenerTag;
2265 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002266 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002267 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002268 public final AlarmManager.AlarmClockInfo alarmClock;
2269 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002270 public final int creatorUid;
2271 public final String packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002272 public int count;
2273 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07002274 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002275 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002276 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002277 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07002278 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002279
Christopher Tate3e04b472013-10-21 17:51:31 -07002280 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002281 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
2282 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
2283 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002284 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002285 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002286 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
2287 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002288 when = _when;
2289 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07002290 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002291 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002292 repeatInterval = _interval;
2293 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002294 listener = _rec;
2295 listenerTag = _listenerTag;
2296 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07002297 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002298 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002299 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002300 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002301 packageName = _pkgName;
2302
2303 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002304 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002305
Christopher Tate14a7bb02015-10-01 10:24:31 -07002306 public static String makeTag(PendingIntent pi, String tag, int type) {
2307 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
2308 ? "*walarm*:" : "*alarm*:";
2309 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
2310 }
2311
2312 public WakeupEvent makeWakeupEvent(long nowRTC) {
2313 return new WakeupEvent(nowRTC, creatorUid,
2314 (operation != null)
2315 ? operation.getIntent().getAction()
2316 : ("<listener>:" + listenerTag));
2317 }
2318
2319 // Returns true if either matches
2320 public boolean matches(PendingIntent pi, IAlarmListener rec) {
2321 return (operation != null)
2322 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09002323 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07002324 }
2325
2326 public boolean matches(String packageName) {
2327 return (operation != null)
2328 ? packageName.equals(operation.getTargetPackage())
2329 : packageName.equals(this.packageName);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002330 }
2331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002332 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002333 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002334 StringBuilder sb = new StringBuilder(128);
2335 sb.append("Alarm{");
2336 sb.append(Integer.toHexString(System.identityHashCode(this)));
2337 sb.append(" type ");
2338 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002339 sb.append(" when ");
2340 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002341 sb.append(" ");
Christopher Tate14a7bb02015-10-01 10:24:31 -07002342 if (operation != null) {
2343 sb.append(operation.getTargetPackage());
2344 } else {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002345 sb.append(packageName);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002346 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002347 sb.append('}');
2348 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002349 }
2350
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002351 public void dump(PrintWriter pw, String prefix, long nowRTC, long nowELAPSED,
2352 SimpleDateFormat sdf) {
2353 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002354 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002355 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002356 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
2357 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002358 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002359 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002360 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002361 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002362 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002363 }
2364 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002365 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002366 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002367 pw.print(" count="); pw.print(count);
2368 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002369 if (alarmClock != null) {
2370 pw.print(prefix); pw.println("Alarm clock:");
2371 pw.print(prefix); pw.print(" triggerTime=");
2372 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
2373 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
2374 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002375 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002376 if (listener != null) {
2377 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
2378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002379 }
2380 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002381
Christopher Tatee0a22b32013-07-11 14:43:13 -07002382 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
2383 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002384 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
2385 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002386 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07002387 break;
2388 }
2389
Christopher Tatee0a22b32013-07-11 14:43:13 -07002390 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002391 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
2392 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002393 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07002394 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002395 }
2396 }
2397
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002398 long currentNonWakeupFuzzLocked(long nowELAPSED) {
2399 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
2400 if (timeSinceOn < 5*60*1000) {
2401 // If the screen has been off for 5 minutes, only delay by at most two minutes.
2402 return 2*60*1000;
2403 } else if (timeSinceOn < 30*60*1000) {
2404 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
2405 return 15*60*1000;
2406 } else {
2407 // Otherwise, we will delay by at most an hour.
2408 return 60*60*1000;
2409 }
2410 }
2411
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002412 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002413 if (duration < 15*60*1000) {
2414 // If the duration until the time is less than 15 minutes, the maximum fuzz
2415 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002416 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002417 } else if (duration < 90*60*1000) {
2418 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
2419 return 15*60*1000;
2420 } else {
2421 // Otherwise, we will fuzz by at most half an hour.
2422 return 30*60*1000;
2423 }
2424 }
2425
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002426 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
2427 if (mInteractive) {
2428 return false;
2429 }
2430 if (mLastAlarmDeliveryTime <= 0) {
2431 return false;
2432 }
minho.choo649acab2014-12-12 16:13:55 +09002433 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002434 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
2435 // and the next delivery time is in the past, then just deliver them all. This
2436 // avoids bugs where we get stuck in a loop trying to poll for alarms.
2437 return false;
2438 }
2439 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
2440 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
2441 }
2442
2443 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
2444 mLastAlarmDeliveryTime = nowELAPSED;
2445 for (int i=0; i<triggerList.size(); i++) {
2446 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07002447 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002448 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07002449 if (localLOGV) {
2450 Slog.v(TAG, "sending alarm " + alarm);
2451 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07002452 if (RECORD_ALARMS_IN_HISTORY) {
2453 if (alarm.workSource != null && alarm.workSource.size() > 0) {
2454 for (int wi=0; wi<alarm.workSource.size(); wi++) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002455 ActivityManager.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002456 alarm.operation, alarm.workSource.get(wi), alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002457 }
2458 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002459 ActivityManager.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002460 alarm.operation, alarm.uid, alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002461 }
2462 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002463 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002464 } catch (RuntimeException e) {
2465 Slog.w(TAG, "Failure sending alarm.", e);
2466 }
2467 }
2468 }
2469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002470 private class AlarmThread extends Thread
2471 {
2472 public AlarmThread()
2473 {
2474 super("AlarmManager");
2475 }
2476
2477 public void run()
2478 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002479 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002481 while (true)
2482 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002483 int result = waitForAlarm(mNativeData);
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002484 mLastWakeup = SystemClock.elapsedRealtime();
Dianne Hackborn390517b2013-05-30 15:03:32 -07002485
2486 triggerList.clear();
2487
Dianne Hackbornc3527222015-05-13 14:03:20 -07002488 final long nowRTC = System.currentTimeMillis();
2489 final long nowELAPSED = SystemClock.elapsedRealtime();
2490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002491 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002492 // The kernel can give us spurious time change notifications due to
2493 // small adjustments it makes internally; we want to filter those out.
2494 final long lastTimeChangeClockTime;
2495 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07002496 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002497 lastTimeChangeClockTime = mLastTimeChangeClockTime;
2498 expectedClockTime = lastTimeChangeClockTime
2499 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07002500 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08002501 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
2502 || nowRTC > (expectedClockTime+1000)) {
2503 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07002504 // let's do it!
2505 if (DEBUG_BATCH) {
2506 Slog.v(TAG, "Time changed notification from kernel; rebatching");
2507 }
2508 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07002509 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07002510 rebatchAllAlarms();
2511 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07002512 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07002513 synchronized (mLock) {
2514 mNumTimeChanged++;
2515 mLastTimeChangeClockTime = nowRTC;
2516 mLastTimeChangeRealtime = nowELAPSED;
2517 }
2518 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
2519 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08002520 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
2521 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Dianne Hackbornc3527222015-05-13 14:03:20 -07002522 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
2523
2524 // The world has changed on us, so we need to re-evaluate alarms
2525 // regardless of whether the kernel has told us one went off.
2526 result |= IS_WAKEUP_MASK;
2527 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002528 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529
Dianne Hackbornc3527222015-05-13 14:03:20 -07002530 if (result != TIME_CHANGED_MASK) {
2531 // If this was anything besides just a time change, then figure what if
2532 // anything to do about alarms.
2533 synchronized (mLock) {
2534 if (localLOGV) Slog.v(
2535 TAG, "Checking for alarms... rtc=" + nowRTC
2536 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07002537
Dianne Hackbornc3527222015-05-13 14:03:20 -07002538 if (WAKEUP_STATS) {
2539 if ((result & IS_WAKEUP_MASK) != 0) {
2540 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
2541 int n = 0;
2542 for (WakeupEvent event : mRecentWakeups) {
2543 if (event.when > newEarliest) break;
2544 n++; // number of now-stale entries at the list head
2545 }
2546 for (int i = 0; i < n; i++) {
2547 mRecentWakeups.remove();
2548 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002549
Dianne Hackbornc3527222015-05-13 14:03:20 -07002550 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002551 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002552 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002553
2554 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2555 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
2556 // if there are no wakeup alarms and the screen is off, we can
2557 // delay what we have so far until the future.
2558 if (mPendingNonWakeupAlarms.size() == 0) {
2559 mStartCurrentDelayTime = nowELAPSED;
2560 mNextNonWakeupDeliveryTime = nowELAPSED
2561 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
2562 }
2563 mPendingNonWakeupAlarms.addAll(triggerList);
2564 mNumDelayedAlarms += triggerList.size();
2565 rescheduleKernelAlarmsLocked();
2566 updateNextAlarmClockLocked();
2567 } else {
2568 // now deliver the alarm intents; if there are pending non-wakeup
2569 // alarms, we need to merge them in to the list. note we don't
2570 // just deliver them first because we generally want non-wakeup
2571 // alarms delivered after wakeup alarms.
2572 rescheduleKernelAlarmsLocked();
2573 updateNextAlarmClockLocked();
2574 if (mPendingNonWakeupAlarms.size() > 0) {
2575 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
2576 triggerList.addAll(mPendingNonWakeupAlarms);
2577 Collections.sort(triggerList, mAlarmDispatchComparator);
2578 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2579 mTotalDelayTime += thisDelayTime;
2580 if (mMaxDelayTime < thisDelayTime) {
2581 mMaxDelayTime = thisDelayTime;
2582 }
2583 mPendingNonWakeupAlarms.clear();
2584 }
2585 deliverAlarmsLocked(triggerList, nowELAPSED);
2586 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002588
2589 } else {
2590 // Just in case -- even though no wakeup flag was set, make sure
2591 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07002592 synchronized (mLock) {
2593 rescheduleKernelAlarmsLocked();
2594 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002595 }
2596 }
2597 }
2598 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002599
David Christieebe51fc2013-07-26 13:23:29 -07002600 /**
2601 * Attribute blame for a WakeLock.
2602 * @param pi PendingIntent to attribute blame to if ws is null.
2603 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002604 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07002605 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002606 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002607 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07002608 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002609 final boolean unimportant = pi == mTimeTickSender;
2610 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002611 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002612 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002613 } else {
2614 mWakeLock.setHistoryTag(null);
2615 }
2616 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07002617 if (ws != null) {
2618 mWakeLock.setWorkSource(ws);
2619 return;
2620 }
2621
Christopher Tate14a7bb02015-10-01 10:24:31 -07002622 final int uid = (knownUid >= 0)
2623 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002624 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07002625 if (uid >= 0) {
2626 mWakeLock.setWorkSource(new WorkSource(uid));
2627 return;
2628 }
2629 } catch (Exception e) {
2630 }
2631
2632 // Something went wrong; fall back to attributing the lock to the OS
2633 mWakeLock.setWorkSource(null);
2634 }
2635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002636 private class AlarmHandler extends Handler {
2637 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002638 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
2639 public static final int LISTENER_TIMEOUT = 3;
2640 public static final int REPORT_ALARMS_ACTIVE = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002641
2642 public AlarmHandler() {
2643 }
2644
2645 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002646 switch (msg.what) {
2647 case ALARM_EVENT: {
2648 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2649 synchronized (mLock) {
2650 final long nowRTC = System.currentTimeMillis();
2651 final long nowELAPSED = SystemClock.elapsedRealtime();
2652 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2653 updateNextAlarmClockLocked();
2654 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002655
Christopher Tate14a7bb02015-10-01 10:24:31 -07002656 // now trigger the alarms without the lock held
2657 for (int i=0; i<triggerList.size(); i++) {
2658 Alarm alarm = triggerList.get(i);
2659 try {
2660 alarm.operation.send();
2661 } catch (PendingIntent.CanceledException e) {
2662 if (alarm.repeatInterval > 0) {
2663 // This IntentSender is no longer valid, but this
2664 // is a repeating alarm, so toss the hoser.
2665 removeImpl(alarm.operation);
2666 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002667 }
2668 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002669 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002670 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002671
2672 case SEND_NEXT_ALARM_CLOCK_CHANGED:
2673 sendNextAlarmClockChanged();
2674 break;
2675
2676 case LISTENER_TIMEOUT:
2677 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
2678 break;
2679
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002680 case REPORT_ALARMS_ACTIVE:
2681 if (mLocalDeviceIdleController != null) {
2682 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
2683 }
2684 break;
2685
Christopher Tate14a7bb02015-10-01 10:24:31 -07002686 default:
2687 // nope, just ignore it
2688 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002689 }
2690 }
2691 }
2692
2693 class ClockReceiver extends BroadcastReceiver {
2694 public ClockReceiver() {
2695 IntentFilter filter = new IntentFilter();
2696 filter.addAction(Intent.ACTION_TIME_TICK);
2697 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002698 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002699 }
2700
2701 @Override
2702 public void onReceive(Context context, Intent intent) {
2703 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07002704 if (DEBUG_BATCH) {
2705 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
2706 }
2707 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002708 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
2709 // Since the kernel does not keep track of DST, we need to
2710 // reset the TZ information at the beginning of each day
2711 // based off of the current Zone gmt offset + userspace tracked
2712 // daylight savings information.
2713 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02002714 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002715 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07002716 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002717 }
2718 }
2719
2720 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07002721 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09002722 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07002723
2724 // Schedule this event for the amount of time that it would take to get to
2725 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09002726 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07002727
David Christieebe51fc2013-07-26 13:23:29 -07002728 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002729 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002730 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
2731 null, Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002732 }
Christopher Tate385e4982013-07-23 18:22:29 -07002733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002734 public void scheduleDateChangedEvent() {
2735 Calendar calendar = Calendar.getInstance();
2736 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07002737 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002738 calendar.set(Calendar.MINUTE, 0);
2739 calendar.set(Calendar.SECOND, 0);
2740 calendar.set(Calendar.MILLISECOND, 0);
2741 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07002742
2743 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002744 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
2745 AlarmManager.FLAG_STANDALONE, workSource, null,
2746 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002747 }
2748 }
2749
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002750 class InteractiveStateReceiver extends BroadcastReceiver {
2751 public InteractiveStateReceiver() {
2752 IntentFilter filter = new IntentFilter();
2753 filter.addAction(Intent.ACTION_SCREEN_OFF);
2754 filter.addAction(Intent.ACTION_SCREEN_ON);
2755 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
2756 getContext().registerReceiver(this, filter);
2757 }
2758
2759 @Override
2760 public void onReceive(Context context, Intent intent) {
2761 synchronized (mLock) {
2762 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
2763 }
2764 }
2765 }
2766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002767 class UninstallReceiver extends BroadcastReceiver {
2768 public UninstallReceiver() {
2769 IntentFilter filter = new IntentFilter();
2770 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2771 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002772 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002773 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08002774 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002775 // Register for events related to sdcard installation.
2776 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08002777 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002778 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002779 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002780 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002781 }
2782
2783 @Override
2784 public void onReceive(Context context, Intent intent) {
2785 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002786 String action = intent.getAction();
2787 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002788 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
2789 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
2790 for (String packageName : pkgList) {
2791 if (lookForPackageLocked(packageName)) {
2792 setResultCode(Activity.RESULT_OK);
2793 return;
2794 }
2795 }
2796 return;
2797 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002798 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002799 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
2800 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
2801 if (userHandle >= 0) {
2802 removeUserLocked(userHandle);
2803 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002804 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
2805 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
2806 if (uid >= 0) {
2807 mLastAllowWhileIdleDispatch.delete(uid);
2808 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002809 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08002810 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
2811 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
2812 // This package is being updated; don't kill its alarms.
2813 return;
2814 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002815 Uri data = intent.getData();
2816 if (data != null) {
2817 String pkg = data.getSchemeSpecificPart();
2818 if (pkg != null) {
2819 pkgList = new String[]{pkg};
2820 }
2821 }
2822 }
2823 if (pkgList != null && (pkgList.length > 0)) {
2824 for (String pkg : pkgList) {
2825 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07002826 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002827 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
2828 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
2829 if (uidStats.remove(pkg) != null) {
2830 if (uidStats.size() <= 0) {
2831 mBroadcastStats.removeAt(i);
2832 }
2833 }
2834 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002835 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002836 }
2837 }
2838 }
2839 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002840
2841 final class UidObserver extends IUidObserver.Stub {
2842 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
2843 }
2844
Dianne Hackborne07641d2016-11-09 15:07:23 -08002845 @Override public void onUidGone(int uid, boolean disabled) throws RemoteException {
2846 if (disabled) {
2847 synchronized (mLock) {
2848 removeForStoppedLocked(uid);
2849 }
2850 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002851 }
2852
2853 @Override public void onUidActive(int uid) throws RemoteException {
2854 }
2855
Dianne Hackborne07641d2016-11-09 15:07:23 -08002856 @Override public void onUidIdle(int uid, boolean disabled) throws RemoteException {
2857 if (disabled) {
2858 synchronized (mLock) {
2859 removeForStoppedLocked(uid);
2860 }
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08002861 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002862 }
2863 };
2864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002865 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002866 String pkg = pi.getCreatorPackage();
2867 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002868 return getStatsLocked(uid, pkg);
2869 }
2870
2871 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002872 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
2873 if (uidStats == null) {
2874 uidStats = new ArrayMap<String, BroadcastStats>();
2875 mBroadcastStats.put(uid, uidStats);
2876 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002877 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002878 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002879 bs = new BroadcastStats(uid, pkgName);
2880 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002881 }
2882 return bs;
2883 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002884
Christopher Tate14a7bb02015-10-01 10:24:31 -07002885 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
2886 private InFlight removeLocked(PendingIntent pi, Intent intent) {
2887 for (int i = 0; i < mInFlight.size(); i++) {
2888 if (mInFlight.get(i).mPendingIntent == pi) {
2889 return mInFlight.remove(i);
2890 }
2891 }
2892 mLog.w("No in-flight alarm for " + pi + " " + intent);
2893 return null;
2894 }
2895
2896 private InFlight removeLocked(IBinder listener) {
2897 for (int i = 0; i < mInFlight.size(); i++) {
2898 if (mInFlight.get(i).mListener == listener) {
2899 return mInFlight.remove(i);
2900 }
2901 }
2902 mLog.w("No in-flight alarm for listener " + listener);
2903 return null;
2904 }
2905
2906 private void updateStatsLocked(InFlight inflight) {
2907 final long nowELAPSED = SystemClock.elapsedRealtime();
2908 BroadcastStats bs = inflight.mBroadcastStats;
2909 bs.nesting--;
2910 if (bs.nesting <= 0) {
2911 bs.nesting = 0;
2912 bs.aggregateTime += nowELAPSED - bs.startTime;
2913 }
2914 FilterStats fs = inflight.mFilterStats;
2915 fs.nesting--;
2916 if (fs.nesting <= 0) {
2917 fs.nesting = 0;
2918 fs.aggregateTime += nowELAPSED - fs.startTime;
2919 }
2920 if (RECORD_ALARMS_IN_HISTORY) {
2921 if (inflight.mWorkSource != null && inflight.mWorkSource.size() > 0) {
2922 for (int wi=0; wi<inflight.mWorkSource.size(); wi++) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002923 ActivityManager.noteAlarmFinish(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002924 inflight.mPendingIntent, inflight.mWorkSource.get(wi), inflight.mTag);
2925 }
2926 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002927 ActivityManager.noteAlarmFinish(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002928 inflight.mPendingIntent, inflight.mUid, inflight.mTag);
2929 }
2930 }
2931 }
2932
2933 private void updateTrackingLocked(InFlight inflight) {
2934 if (inflight != null) {
2935 updateStatsLocked(inflight);
2936 }
2937 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08002938 if (DEBUG_WAKELOCK) {
2939 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
2940 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002941 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002942 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002943 mWakeLock.release();
2944 if (mInFlight.size() > 0) {
2945 mLog.w("Finished all dispatches with " + mInFlight.size()
2946 + " remaining inflights");
2947 for (int i=0; i<mInFlight.size(); i++) {
2948 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
2949 }
2950 mInFlight.clear();
2951 }
2952 } else {
2953 // the next of our alarms is now in flight. reattribute the wakelock.
2954 if (mInFlight.size() > 0) {
2955 InFlight inFlight = mInFlight.get(0);
2956 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
2957 inFlight.mAlarmType, inFlight.mTag, -1, false);
2958 } else {
2959 // should never happen
2960 mLog.w("Alarm wakelock still held but sent queue empty");
2961 mWakeLock.setWorkSource(null);
2962 }
2963 }
2964 }
2965
2966 /**
2967 * Callback that arrives when a direct-call alarm reports that delivery has finished
2968 */
2969 @Override
2970 public void alarmComplete(IBinder who) {
2971 if (who == null) {
2972 Slog.w(TAG, "Invalid alarmComplete: uid=" + Binder.getCallingUid()
2973 + " pid=" + Binder.getCallingPid());
2974 return;
2975 }
2976
2977 final long ident = Binder.clearCallingIdentity();
2978 try {
2979 synchronized (mLock) {
2980 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
2981 InFlight inflight = removeLocked(who);
2982 if (inflight != null) {
2983 if (DEBUG_LISTENER_CALLBACK) {
2984 Slog.i(TAG, "alarmComplete() from " + who);
2985 }
2986 updateTrackingLocked(inflight);
2987 } else {
2988 // Delivery timed out, and the timeout handling already took care of
2989 // updating our tracking here, so we needn't do anything further.
2990 if (DEBUG_LISTENER_CALLBACK) {
2991 Slog.i(TAG, "Late alarmComplete() from " + who);
2992 }
2993 }
2994 }
2995 } finally {
2996 Binder.restoreCallingIdentity(ident);
2997 }
2998 }
2999
3000 /**
3001 * Callback that arrives when a PendingIntent alarm has finished delivery
3002 */
3003 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003004 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
3005 String resultData, Bundle resultExtras) {
3006 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003007 updateTrackingLocked(removeLocked(pi, intent));
3008 }
3009 }
3010
3011 /**
3012 * Timeout of a direct-call alarm delivery
3013 */
3014 public void alarmTimedOut(IBinder who) {
3015 synchronized (mLock) {
3016 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08003017 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003018 // TODO: implement ANR policy for the target
3019 if (DEBUG_LISTENER_CALLBACK) {
3020 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003021 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003022 updateTrackingLocked(inflight);
Dianne Hackborn81038902012-11-26 17:04:09 -08003023 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003024 if (DEBUG_LISTENER_CALLBACK) {
3025 Slog.i(TAG, "Spurious timeout of listener " + who);
3026 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003027 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003028 }
3029 }
3030
3031 /**
3032 * Deliver an alarm and set up the post-delivery handling appropriately
3033 */
3034 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
3035 if (alarm.operation != null) {
3036 // PendingIntent alarm
3037 try {
3038 alarm.operation.send(getContext(), 0,
3039 mBackgroundIntent.putExtra(
3040 Intent.EXTRA_ALARM_COUNT, alarm.count),
3041 mDeliveryTracker, mHandler, null,
3042 allowWhileIdle ? mIdleOptions : null);
3043 } catch (PendingIntent.CanceledException e) {
3044 if (alarm.repeatInterval > 0) {
3045 // This IntentSender is no longer valid, but this
3046 // is a repeating alarm, so toss it
3047 removeImpl(alarm.operation);
3048 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003049 // No actual delivery was possible, so the delivery tracker's
3050 // 'finished' callback won't be invoked. We also don't need
3051 // to do any wakelock or stats tracking, so we have nothing
3052 // left to do here but go on to the next thing.
3053 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003054 }
3055 } else {
3056 // Direct listener callback alarm
3057 try {
3058 if (DEBUG_LISTENER_CALLBACK) {
3059 Slog.v(TAG, "Alarm to uid=" + alarm.uid
3060 + " listener=" + alarm.listener.asBinder());
3061 }
3062 alarm.listener.doAlarm(this);
3063 mHandler.sendMessageDelayed(
3064 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
3065 alarm.listener.asBinder()),
3066 mConstants.LISTENER_TIMEOUT);
3067 } catch (Exception e) {
3068 if (DEBUG_LISTENER_CALLBACK) {
3069 Slog.i(TAG, "Alarm undeliverable to listener "
3070 + alarm.listener.asBinder(), e);
3071 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003072 // As in the PendingIntent.CanceledException case, delivery of the
3073 // alarm was not possible, so we have no wakelock or timeout or
3074 // stats management to do. It threw before we posted the delayed
3075 // timeout message, so we're done here.
3076 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003077 }
3078 }
3079
3080 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08003081 if (DEBUG_WAKELOCK) {
3082 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
3083 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003084 if (mBroadcastRefCount == 0) {
3085 setWakelockWorkSource(alarm.operation, alarm.workSource,
3086 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
3087 true);
3088 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003089 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003090 }
3091 final InFlight inflight = new InFlight(AlarmManagerService.this,
3092 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
3093 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
3094 mInFlight.add(inflight);
3095 mBroadcastRefCount++;
3096
3097 if (allowWhileIdle) {
3098 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
3099 mLastAllowWhileIdleDispatch.put(alarm.uid, nowELAPSED);
3100 if (RECORD_DEVICE_IDLE_ALARMS) {
3101 IdleDispatchEntry ent = new IdleDispatchEntry();
3102 ent.uid = alarm.uid;
3103 ent.pkg = alarm.packageName;
3104 ent.tag = alarm.statsTag;
3105 ent.op = "DELIVER";
3106 ent.elapsedRealtime = nowELAPSED;
3107 mAllowWhileIdleDispatches.add(ent);
3108 }
3109 }
3110
3111 final BroadcastStats bs = inflight.mBroadcastStats;
3112 bs.count++;
3113 if (bs.nesting == 0) {
3114 bs.nesting = 1;
3115 bs.startTime = nowELAPSED;
3116 } else {
3117 bs.nesting++;
3118 }
3119 final FilterStats fs = inflight.mFilterStats;
3120 fs.count++;
3121 if (fs.nesting == 0) {
3122 fs.nesting = 1;
3123 fs.startTime = nowELAPSED;
3124 } else {
3125 fs.nesting++;
3126 }
3127 if (alarm.type == ELAPSED_REALTIME_WAKEUP
3128 || alarm.type == RTC_WAKEUP) {
3129 bs.numWakeup++;
3130 fs.numWakeup++;
3131 if (alarm.workSource != null && alarm.workSource.size() > 0) {
3132 for (int wi=0; wi<alarm.workSource.size(); wi++) {
Christopher Tate0029f572016-06-14 10:16:28 -07003133 final String wsName = alarm.workSource.getName(wi);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003134 ActivityManager.noteWakeupAlarm(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003135 alarm.operation, alarm.workSource.get(wi),
Christopher Tate0029f572016-06-14 10:16:28 -07003136 (wsName != null) ? wsName : alarm.packageName,
3137 alarm.statsTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08003138 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003139 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003140 ActivityManager.noteWakeupAlarm(
Joe Onorato78bcdf92016-05-09 10:10:29 -07003141 alarm.operation, alarm.uid, alarm.packageName, alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003142 }
3143 }
3144 }
3145 }
3146}