blob: 0e07ec0e27f4cfe42fa902568915f33b42922d7d [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;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700102 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700103 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800104 static final int ALARM_EVENT = 1;
105 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200106
Christopher Tate14a7bb02015-10-01 10:24:31 -0700107 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800109 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110
Adam Lesinski182f73f2013-12-05 16:48:06 -0800111 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700112
Christopher Tate24cd46f2016-02-02 14:28:01 -0800113 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT =
114 new Intent(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED)
115 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Adrian Roosc42a1e12014-07-07 23:35:53 +0200116
Adam Lesinski182f73f2013-12-05 16:48:06 -0800117 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800118
Christopher Tate14a7bb02015-10-01 10:24:31 -0700119 AppOpsManager mAppOps;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800120 DeviceIdleController.LocalService mLocalDeviceIdleController;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700121
Adam Lesinski182f73f2013-12-05 16:48:06 -0800122 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800123
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800124 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800125 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700126 private long mNextNonWakeup;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -0700127 private long mLastWakeupSet;
128 private long mLastWakeup;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800129 int mBroadcastRefCount = 0;
130 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700131 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700132 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
133 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800134 final AlarmHandler mHandler = new AlarmHandler();
135 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700136 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700138 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800139 PendingIntent mTimeTickSender;
140 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700141 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700142 boolean mInteractive = true;
143 long mNonInteractiveStartTime;
144 long mNonInteractiveTime;
145 long mLastAlarmDeliveryTime;
146 long mStartCurrentDelayTime;
147 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700148 long mLastTimeChangeClockTime;
149 long mLastTimeChangeRealtime;
Dianne Hackborna750a632015-06-16 17:18:23 -0700150 long mAllowWhileIdleMinTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700151 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800152
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700153 /**
Dianne Hackborn262ae5c2016-02-10 16:28:29 -0800154 * The current set of user whitelisted apps for device idle mode, meaning these are allowed
155 * to freely schedule alarms.
156 */
157 int[] mDeviceIdleUserWhitelist = new int[0];
158
159 /**
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700160 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
161 * used to determine the earliest we can dispatch the next such alarm.
162 */
163 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
164
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700165 final static class IdleDispatchEntry {
166 int uid;
167 String pkg;
168 String tag;
169 String op;
170 long elapsedRealtime;
171 long argRealtime;
172 }
173 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
174
Dianne Hackborna750a632015-06-16 17:18:23 -0700175 /**
176 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
177 */
178 Bundle mIdleOptions;
179
Jose Lima235510e2014-08-13 12:50:01 -0700180 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
181 new SparseArray<>();
182 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
183 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200184 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
185 new SparseBooleanArray();
186 private boolean mNextAlarmClockMayChange;
187
188 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700189 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
190 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200191
Dianne Hackborna750a632015-06-16 17:18:23 -0700192 /**
193 * All times are in milliseconds. These constants are kept synchronized with the system
194 * global Settings. Any access to this class or its fields should be done while
195 * holding the AlarmManagerService.mLock lock.
196 */
197 private final class Constants extends ContentObserver {
198 // Key names stored in the settings value.
199 private static final String KEY_MIN_FUTURITY = "min_futurity";
200 private static final String KEY_MIN_INTERVAL = "min_interval";
201 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
202 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
203 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
204 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700205 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Dianne Hackborna750a632015-06-16 17:18:23 -0700206
207 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
208 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tateaa244da2015-08-27 15:57:57 -0700209 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700210 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700211 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
212
Christopher Tate14a7bb02015-10-01 10:24:31 -0700213 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
214
Dianne Hackborna750a632015-06-16 17:18:23 -0700215 // Minimum futurity of a new alarm
216 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
217
218 // Minimum alarm recurrence interval
219 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
220
221 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
222 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
223
224 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
225 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
226
227 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
228 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
229 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
230
Christopher Tate14a7bb02015-10-01 10:24:31 -0700231 // Direct alarm listener callback timeout
232 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
233
Dianne Hackborna750a632015-06-16 17:18:23 -0700234 private ContentResolver mResolver;
235 private final KeyValueListParser mParser = new KeyValueListParser(',');
236 private long mLastAllowWhileIdleWhitelistDuration = -1;
237
238 public Constants(Handler handler) {
239 super(handler);
240 updateAllowWhileIdleMinTimeLocked();
241 updateAllowWhileIdleWhitelistDurationLocked();
242 }
243
244 public void start(ContentResolver resolver) {
245 mResolver = resolver;
246 mResolver.registerContentObserver(Settings.Global.getUriFor(
247 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
248 updateConstants();
249 }
250
251 public void updateAllowWhileIdleMinTimeLocked() {
252 mAllowWhileIdleMinTime = mPendingIdleUntil != null
253 ? ALLOW_WHILE_IDLE_LONG_TIME : ALLOW_WHILE_IDLE_SHORT_TIME;
254 }
255
256 public void updateAllowWhileIdleWhitelistDurationLocked() {
257 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
258 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
259 BroadcastOptions opts = BroadcastOptions.makeBasic();
260 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
261 mIdleOptions = opts.toBundle();
262 }
263 }
264
265 @Override
266 public void onChange(boolean selfChange, Uri uri) {
267 updateConstants();
268 }
269
270 private void updateConstants() {
271 synchronized (mLock) {
272 try {
273 mParser.setString(Settings.Global.getString(mResolver,
274 Settings.Global.ALARM_MANAGER_CONSTANTS));
275 } catch (IllegalArgumentException e) {
276 // Failed to parse the settings string, log this and move on
277 // with defaults.
278 Slog.e(TAG, "Bad device idle settings", e);
279 }
280
281 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
282 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
283 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
284 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
285 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
286 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
287 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
288 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
289 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700290 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
291 DEFAULT_LISTENER_TIMEOUT);
Dianne Hackborna750a632015-06-16 17:18:23 -0700292
293 updateAllowWhileIdleMinTimeLocked();
294 updateAllowWhileIdleWhitelistDurationLocked();
295 }
296 }
297
298 void dump(PrintWriter pw) {
299 pw.println(" Settings:");
300
301 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
302 TimeUtils.formatDuration(MIN_FUTURITY, pw);
303 pw.println();
304
305 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
306 TimeUtils.formatDuration(MIN_INTERVAL, pw);
307 pw.println();
308
Christopher Tate14a7bb02015-10-01 10:24:31 -0700309 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
310 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
311 pw.println();
312
Dianne Hackborna750a632015-06-16 17:18:23 -0700313 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
314 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
315 pw.println();
316
317 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
318 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
319 pw.println();
320
321 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
322 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
323 pw.println();
324 }
325 }
326
327 final Constants mConstants;
328
Christopher Tate1590f1e2014-10-02 17:27:57 -0700329 // Alarm delivery ordering bookkeeping
330 static final int PRIO_TICK = 0;
331 static final int PRIO_WAKEUP = 1;
332 static final int PRIO_NORMAL = 2;
333
Dianne Hackborna750a632015-06-16 17:18:23 -0700334 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700335 int seq;
336 int priority;
337
338 PriorityClass() {
339 seq = mCurrentSeq - 1;
340 priority = PRIO_NORMAL;
341 }
342 }
343
Dianne Hackborna750a632015-06-16 17:18:23 -0700344 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700345 int mCurrentSeq = 0;
346
Dianne Hackborna750a632015-06-16 17:18:23 -0700347 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700348 public long when;
349 public int uid;
350 public String action;
351
352 public WakeupEvent(long theTime, int theUid, String theAction) {
353 when = theTime;
354 uid = theUid;
355 action = theAction;
356 }
357 }
358
Adam Lesinski182f73f2013-12-05 16:48:06 -0800359 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
360 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700361
Adrian Roosc42a1e12014-07-07 23:35:53 +0200362 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700363 long start; // These endpoints are always in ELAPSED
364 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700365 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700366
367 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
368
369 Batch() {
370 start = 0;
371 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700372 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700373 }
374
375 Batch(Alarm seed) {
376 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700377 end = seed.maxWhenElapsed;
378 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700379 alarms.add(seed);
380 }
381
382 int size() {
383 return alarms.size();
384 }
385
386 Alarm get(int index) {
387 return alarms.get(index);
388 }
389
390 boolean canHold(long whenElapsed, long maxWhen) {
391 return (end >= whenElapsed) && (start <= maxWhen);
392 }
393
394 boolean add(Alarm alarm) {
395 boolean newStart = false;
396 // narrows the batch if necessary; presumes that canHold(alarm) is true
397 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
398 if (index < 0) {
399 index = 0 - index - 1;
400 }
401 alarms.add(index, alarm);
402 if (DEBUG_BATCH) {
403 Slog.v(TAG, "Adding " + alarm + " to " + this);
404 }
405 if (alarm.whenElapsed > start) {
406 start = alarm.whenElapsed;
407 newStart = true;
408 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700409 if (alarm.maxWhenElapsed < end) {
410 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700411 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700412 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700413
414 if (DEBUG_BATCH) {
415 Slog.v(TAG, " => now " + this);
416 }
417 return newStart;
418 }
419
Christopher Tate14a7bb02015-10-01 10:24:31 -0700420 boolean remove(final PendingIntent operation, final IAlarmListener listener) {
421 if (operation == null && listener == null) {
422 if (localLOGV) {
423 Slog.w(TAG, "requested remove() of null operation",
424 new RuntimeException("here"));
425 }
426 return false;
427 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700428 boolean didRemove = false;
429 long newStart = 0; // recalculate endpoints as we go
430 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700431 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700432 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700433 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700434 if (alarm.matches(operation, listener)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700435 alarms.remove(i);
436 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200437 if (alarm.alarmClock != null) {
438 mNextAlarmClockMayChange = true;
439 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700440 } else {
441 if (alarm.whenElapsed > newStart) {
442 newStart = alarm.whenElapsed;
443 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700444 if (alarm.maxWhenElapsed < newEnd) {
445 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700446 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700447 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700448 i++;
449 }
450 }
451 if (didRemove) {
452 // commit the new batch bounds
453 start = newStart;
454 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700455 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700456 }
457 return didRemove;
458 }
459
460 boolean remove(final String packageName) {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700461 if (packageName == null) {
462 if (localLOGV) {
463 Slog.w(TAG, "requested remove() of null packageName",
464 new RuntimeException("here"));
465 }
466 return false;
467 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700468 boolean didRemove = false;
469 long newStart = 0; // recalculate endpoints as we go
470 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700471 int newFlags = 0;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700472 for (int i = alarms.size()-1; i >= 0; i--) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700473 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700474 if (alarm.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700475 alarms.remove(i);
476 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200477 if (alarm.alarmClock != null) {
478 mNextAlarmClockMayChange = true;
479 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700480 } else {
481 if (alarm.whenElapsed > newStart) {
482 newStart = alarm.whenElapsed;
483 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700484 if (alarm.maxWhenElapsed < newEnd) {
485 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700486 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700487 newFlags |= alarm.flags;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700488 }
489 }
490 if (didRemove) {
491 // commit the new batch bounds
492 start = newStart;
493 end = newEnd;
494 flags = newFlags;
495 }
496 return didRemove;
497 }
498
499 boolean removeForStopped(final int uid) {
500 boolean didRemove = false;
501 long newStart = 0; // recalculate endpoints as we go
502 long newEnd = Long.MAX_VALUE;
503 int newFlags = 0;
504 for (int i = alarms.size()-1; i >= 0; i--) {
505 Alarm alarm = alarms.get(i);
506 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800507 if (alarm.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
508 uid, alarm.packageName)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700509 alarms.remove(i);
510 didRemove = true;
511 if (alarm.alarmClock != null) {
512 mNextAlarmClockMayChange = true;
513 }
514 } else {
515 if (alarm.whenElapsed > newStart) {
516 newStart = alarm.whenElapsed;
517 }
518 if (alarm.maxWhenElapsed < newEnd) {
519 newEnd = alarm.maxWhenElapsed;
520 }
521 newFlags |= alarm.flags;
522 }
523 } catch (RemoteException e) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700524 }
525 }
526 if (didRemove) {
527 // commit the new batch bounds
528 start = newStart;
529 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700530 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700531 }
532 return didRemove;
533 }
534
535 boolean remove(final int userHandle) {
536 boolean didRemove = false;
537 long newStart = 0; // recalculate endpoints as we go
538 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700539 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700540 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700541 if (UserHandle.getUserId(alarm.creatorUid) == userHandle) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700542 alarms.remove(i);
543 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200544 if (alarm.alarmClock != null) {
545 mNextAlarmClockMayChange = true;
546 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700547 } else {
548 if (alarm.whenElapsed > newStart) {
549 newStart = alarm.whenElapsed;
550 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700551 if (alarm.maxWhenElapsed < newEnd) {
552 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700553 }
554 i++;
555 }
556 }
557 if (didRemove) {
558 // commit the new batch bounds
559 start = newStart;
560 end = newEnd;
561 }
562 return didRemove;
563 }
564
565 boolean hasPackage(final String packageName) {
566 final int N = alarms.size();
567 for (int i = 0; i < N; i++) {
568 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700569 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700570 return true;
571 }
572 }
573 return false;
574 }
575
576 boolean hasWakeups() {
577 final int N = alarms.size();
578 for (int i = 0; i < N; i++) {
579 Alarm a = alarms.get(i);
580 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
581 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
582 return true;
583 }
584 }
585 return false;
586 }
587
588 @Override
589 public String toString() {
590 StringBuilder b = new StringBuilder(40);
591 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
592 b.append(" num="); b.append(size());
593 b.append(" start="); b.append(start);
594 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700595 if (flags != 0) {
596 b.append(" flgs=0x");
597 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700598 }
599 b.append('}');
600 return b.toString();
601 }
602 }
603
604 static class BatchTimeOrder implements Comparator<Batch> {
605 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800606 long when1 = b1.start;
607 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800608 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700609 return 1;
610 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800611 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700612 return -1;
613 }
614 return 0;
615 }
616 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800617
618 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
619 @Override
620 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700621 // priority class trumps everything. TICK < WAKEUP < NORMAL
622 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
623 return -1;
624 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
625 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800626 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700627
628 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800629 if (lhs.whenElapsed < rhs.whenElapsed) {
630 return -1;
631 } else if (lhs.whenElapsed > rhs.whenElapsed) {
632 return 1;
633 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700634
635 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800636 return 0;
637 }
638 };
639
Christopher Tate1590f1e2014-10-02 17:27:57 -0700640 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
641 final int N = alarms.size();
642 for (int i = 0; i < N; i++) {
643 Alarm a = alarms.get(i);
644
645 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700646 if (a.operation != null
647 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700648 alarmPrio = PRIO_TICK;
649 } else if (a.wakeup) {
650 alarmPrio = PRIO_WAKEUP;
651 } else {
652 alarmPrio = PRIO_NORMAL;
653 }
654
655 PriorityClass packagePrio = a.priorityClass;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700656 String alarmPackage = (a.operation != null)
657 ? a.operation.getCreatorPackage()
658 : a.packageName;
659 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700660 if (packagePrio == null) {
661 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700662 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700663 }
664 a.priorityClass = packagePrio;
665
666 if (packagePrio.seq != mCurrentSeq) {
667 // first alarm we've seen in the current delivery generation from this package
668 packagePrio.priority = alarmPrio;
669 packagePrio.seq = mCurrentSeq;
670 } else {
671 // Multiple alarms from this package being delivered in this generation;
672 // bump the package's delivery class if it's warranted.
673 // TICK < WAKEUP < NORMAL
674 if (alarmPrio < packagePrio.priority) {
675 packagePrio.priority = alarmPrio;
676 }
677 }
678 }
679 }
680
Christopher Tatee0a22b32013-07-11 14:43:13 -0700681 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800682 static final long MIN_FUZZABLE_INTERVAL = 10000;
683 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700684 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
685
686 // set to null if in idle mode; while in this mode, any alarms we don't want
687 // to run during this time are placed in mPendingWhileIdleAlarms
688 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700689 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700690 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700691
Jeff Brownb880d882014-02-10 19:47:07 -0800692 public AlarmManagerService(Context context) {
693 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700694 mConstants = new Constants(mHandler);
Jeff Brownb880d882014-02-10 19:47:07 -0800695 }
696
Christopher Tatee0a22b32013-07-11 14:43:13 -0700697 static long convertToElapsed(long when, int type) {
698 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
699 if (isRtc) {
700 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
701 }
702 return when;
703 }
704
705 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
706 // calculate the end of our nominal delivery window for the alarm.
707 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
708 // Current heuristic: batchable window is 75% of either the recurrence interval
709 // [for a periodic alarm] or of the time from now to the desired delivery time,
710 // with a minimum delay/interval of 10 seconds, under which we will simply not
711 // defer the alarm.
712 long futurity = (interval == 0)
713 ? (triggerAtTime - now)
714 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700715 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700716 futurity = 0;
717 }
718 return triggerAtTime + (long)(.75 * futurity);
719 }
720
721 // returns true if the batch was added at the head
722 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
723 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
724 if (index < 0) {
725 index = 0 - index - 1;
726 }
727 list.add(index, newBatch);
728 return (index == 0);
729 }
730
Christopher Tate385e4982013-07-23 18:22:29 -0700731 // Return the index of the matching batch, or -1 if none found.
732 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700733 final int N = mAlarmBatches.size();
734 for (int i = 0; i < N; i++) {
735 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700736 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700737 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700738 }
739 }
Christopher Tate385e4982013-07-23 18:22:29 -0700740 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700741 }
742
743 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
744 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700745 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700746 rebatchAllAlarmsLocked(true);
747 }
748 }
749
750 void rebatchAllAlarmsLocked(boolean doValidate) {
751 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
752 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700753 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700754 final long nowElapsed = SystemClock.elapsedRealtime();
755 final int oldBatches = oldSet.size();
756 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
757 Batch batch = oldSet.get(batchNum);
758 final int N = batch.size();
759 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700760 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700761 }
762 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700763 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
764 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
765 + " to " + mPendingIdleUntil);
766 if (mPendingIdleUntil == null) {
767 // Somehow we lost this... we need to restore all of the pending alarms.
768 restorePendingWhileIdleAlarmsLocked();
769 }
770 }
771 rescheduleKernelAlarmsLocked();
772 updateNextAlarmClockLocked();
773 }
774
775 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
776 a.when = a.origWhen;
777 long whenElapsed = convertToElapsed(a.when, a.type);
778 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700779 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700780 // Exact
781 maxElapsed = whenElapsed;
782 } else {
783 // Not exact. Preserve any explicit window, otherwise recalculate
784 // the window based on the alarm's new futurity. Note that this
785 // reflects a policy of preferring timely to deferred delivery.
786 maxElapsed = (a.windowLength > 0)
787 ? (whenElapsed + a.windowLength)
788 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
789 }
790 a.whenElapsed = whenElapsed;
791 a.maxWhenElapsed = maxElapsed;
792 setImplLocked(a, true, doValidate);
793 }
794
795 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700796 if (RECORD_DEVICE_IDLE_ALARMS) {
797 IdleDispatchEntry ent = new IdleDispatchEntry();
798 ent.uid = 0;
799 ent.pkg = "FINISH IDLE";
800 ent.elapsedRealtime = SystemClock.elapsedRealtime();
801 mAllowWhileIdleDispatches.add(ent);
802 }
803
Dianne Hackborn35d54032015-04-23 10:30:43 -0700804 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700805 if (mPendingWhileIdleAlarms.size() > 0) {
806 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
807 mPendingWhileIdleAlarms = new ArrayList<>();
808 final long nowElapsed = SystemClock.elapsedRealtime();
809 for (int i=alarms.size() - 1; i >= 0; i--) {
810 Alarm a = alarms.get(i);
811 reAddAlarmLocked(a, nowElapsed, false);
812 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700813 }
Dianne Hackborn35d54032015-04-23 10:30:43 -0700814
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700815 // Make sure we are using the correct ALLOW_WHILE_IDLE min time.
Dianne Hackborna750a632015-06-16 17:18:23 -0700816 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700817
Dianne Hackborn35d54032015-04-23 10:30:43 -0700818 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700819 rescheduleKernelAlarmsLocked();
820 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -0700821
822 // And send a TIME_TICK right now, since it is important to get the UI updated.
823 try {
824 mTimeTickSender.send();
825 } catch (PendingIntent.CanceledException e) {
826 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700827 }
828
Christopher Tate14a7bb02015-10-01 10:24:31 -0700829 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -0800830 final PendingIntent mPendingIntent;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700831 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -0700832 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700833 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700834 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800835 final BroadcastStats mBroadcastStats;
836 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800837 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800838
Christopher Tate14a7bb02015-10-01 10:24:31 -0700839 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
840 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
841 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800842 mPendingIntent = pendingIntent;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700843 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -0700844 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700845 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700846 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700847 mBroadcastStats = (pendingIntent != null)
848 ? service.getStatsLocked(pendingIntent)
849 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700850 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -0800851 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700852 fs = new FilterStats(mBroadcastStats, mTag);
853 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -0800854 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700855 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -0800856 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800857 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800858 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800860
Adam Lesinski182f73f2013-12-05 16:48:06 -0800861 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -0800862 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700863 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800864
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700865 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800867 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 int numWakeup;
869 long startTime;
870 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -0800871
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700872 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800873 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700874 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800875 }
876 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700877
Adam Lesinski182f73f2013-12-05 16:48:06 -0800878 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800879 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800880 final String mPackageName;
881
882 long aggregateTime;
883 int count;
884 int numWakeup;
885 long startTime;
886 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700887 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -0800888
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800889 BroadcastStats(int uid, String packageName) {
890 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800891 mPackageName = packageName;
892 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700894
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800895 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
896 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700897
898 int mNumDelayedAlarms = 0;
899 long mTotalDelayTime = 0;
900 long mMaxDelayTime = 0;
901
Adam Lesinski182f73f2013-12-05 16:48:06 -0800902 @Override
903 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800904 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800905 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800906
907 // We have to set current TimeZone info to kernel
908 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -0800909 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800910
Adam Lesinski182f73f2013-12-05 16:48:06 -0800911 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800912 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800913
Adam Lesinski182f73f2013-12-05 16:48:06 -0800914 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700916 Intent.FLAG_RECEIVER_REGISTERED_ONLY
917 | Intent.FLAG_RECEIVER_FOREGROUND), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700918 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800919 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
920 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800921 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700922 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923
924 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -0800925 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800926 mClockReceiver.scheduleTimeTickEvent();
927 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700928 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 mUninstallReceiver = new UninstallReceiver();
930
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800931 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800932 AlarmThread waitThread = new AlarmThread();
933 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800935 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800937
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700938 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800939 ActivityManager.getService().registerUidObserver(new UidObserver(),
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800940 ActivityManager.UID_OBSERVER_IDLE, ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700941 } catch (RemoteException e) {
942 // ignored; both services live in system_server
943 }
944
Adam Lesinski182f73f2013-12-05 16:48:06 -0800945 publishBinderService(Context.ALARM_SERVICE, mService);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -0800946 publishLocalService(LocalService.class, new LocalService());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800948
949 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -0700950 public void onBootPhase(int phase) {
951 if (phase == PHASE_SYSTEM_SERVICES_READY) {
952 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -0700953 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800954 mLocalDeviceIdleController
955 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackborna750a632015-06-16 17:18:23 -0700956 }
957 }
958
959 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 protected void finalize() throws Throwable {
961 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800962 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963 } finally {
964 super.finalize();
965 }
966 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700967
Adam Lesinski182f73f2013-12-05 16:48:06 -0800968 void setTimeZoneImpl(String tz) {
969 if (TextUtils.isEmpty(tz)) {
970 return;
David Christieebe51fc2013-07-26 13:23:29 -0700971 }
972
Adam Lesinski182f73f2013-12-05 16:48:06 -0800973 TimeZone zone = TimeZone.getTimeZone(tz);
974 // Prevent reentrant calls from stepping on each other when writing
975 // the time zone property
976 boolean timeZoneWasChanged = false;
977 synchronized (this) {
978 String current = SystemProperties.get(TIMEZONE_PROPERTY);
979 if (current == null || !current.equals(zone.getID())) {
980 if (localLOGV) {
981 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
982 }
983 timeZoneWasChanged = true;
984 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
985 }
986
987 // Update the kernel timezone information
988 // Kernel tracks time offsets as 'minutes west of GMT'
989 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800990 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -0800991 }
992
993 TimeZone.setDefault(null);
994
995 if (timeZoneWasChanged) {
996 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
997 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
998 intent.putExtra("time-zone", zone.getID());
999 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1000 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001002
Adam Lesinski182f73f2013-12-05 16:48:06 -08001003 void removeImpl(PendingIntent operation) {
1004 if (operation == null) {
1005 return;
1006 }
1007 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001008 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001009 }
1010 }
1011
1012 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001013 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1014 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1015 int callingUid, String callingPackage) {
1016 // must be *either* PendingIntent or AlarmReceiver, but not both
1017 if ((operation == null && directReceiver == null)
1018 || (operation != null && directReceiver != null)) {
1019 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1020 // NB: previous releases failed silently here, so we are continuing to do the same
1021 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022 return;
1023 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001024
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001025 // Sanity check the window length. This will catch people mistakenly
1026 // trying to pass an end-of-window timestamp rather than a duration.
1027 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1028 Slog.w(TAG, "Window length " + windowLength
1029 + "ms suspiciously long; limiting to 1 hour");
1030 windowLength = AlarmManager.INTERVAL_HOUR;
1031 }
1032
Christopher Tate498c6cb2014-11-17 16:09:27 -08001033 // Sanity check the recurrence interval. This will catch people who supply
1034 // seconds when the API expects milliseconds.
Dianne Hackborna750a632015-06-16 17:18:23 -07001035 final long minInterval = mConstants.MIN_INTERVAL;
1036 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001037 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001038 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001039 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001040 interval = minInterval;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001041 }
1042
Christopher Tatee0a22b32013-07-11 14:43:13 -07001043 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1044 throw new IllegalArgumentException("Invalid alarm type " + type);
1045 }
1046
Christopher Tate5f221e82013-07-30 17:13:15 -07001047 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001048 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001049 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001050 + " pid=" + what);
1051 triggerAtTime = 0;
1052 }
1053
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001054 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001055 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1056 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001057 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001058 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1059
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001060 final long maxElapsed;
1061 if (windowLength == AlarmManager.WINDOW_EXACT) {
1062 maxElapsed = triggerElapsed;
1063 } else if (windowLength < 0) {
1064 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001065 // Fix this window in place, so that as time approaches we don't collapse it.
1066 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001067 } else {
1068 maxElapsed = triggerElapsed + windowLength;
1069 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001072 if (DEBUG_BATCH) {
1073 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001074 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001075 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001076 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001078 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001079 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1080 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 }
1082 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083
Christopher Tate3e04b472013-10-21 17:51:31 -07001084 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001085 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1086 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1087 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001088 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001089 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1090 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001091 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001092 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001093 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1094 + " -- package not allowed to start");
1095 return;
1096 }
1097 } catch (RemoteException e) {
1098 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001099 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001100 setImplLocked(a, false, doValidate);
1101 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001102
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001103 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1104 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001105 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001106 // The caller has given the time they want this to happen at, however we need
1107 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001108 // bring us out of idle at an earlier time.
1109 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001110 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001111 }
1112 // Add fuzz to make the alarm go off some time before the actual desired time.
1113 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001114 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001115 if (fuzz > 0) {
1116 if (mRandom == null) {
1117 mRandom = new Random();
1118 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001119 final int delta = mRandom.nextInt(fuzz);
1120 a.whenElapsed -= delta;
1121 if (false) {
1122 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1123 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1124 Slog.d(TAG, "Applied fuzz: " + fuzz);
1125 Slog.d(TAG, "Final delta: " + delta);
1126 Slog.d(TAG, "Final when: " + a.whenElapsed);
1127 }
1128 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001129 }
1130
1131 } else if (mPendingIdleUntil != null) {
1132 // We currently have an idle until alarm scheduled; if the new alarm has
1133 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001134 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1135 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1136 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001137 == 0) {
1138 mPendingWhileIdleAlarms.add(a);
1139 return;
1140 }
1141 }
1142
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001143 if (RECORD_DEVICE_IDLE_ALARMS) {
1144 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1145 IdleDispatchEntry ent = new IdleDispatchEntry();
1146 ent.uid = a.uid;
1147 ent.pkg = a.operation.getCreatorPackage();
1148 ent.tag = a.operation.getTag("");
1149 ent.op = "SET";
1150 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1151 ent.argRealtime = a.whenElapsed;
1152 mAllowWhileIdleDispatches.add(ent);
1153 }
1154 }
1155
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001156 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
1157 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -07001158 if (whichBatch < 0) {
1159 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001160 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 } else {
Christopher Tate385e4982013-07-23 18:22:29 -07001162 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001163 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001164 // The start time of this batch advanced, so batch ordering may
1165 // have just been broken. Move it to where it now belongs.
1166 mAlarmBatches.remove(whichBatch);
1167 addBatchLocked(mAlarmBatches, batch);
1168 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 }
1170
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001171 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001172 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001173 }
1174
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001175 boolean needRebatch = false;
1176
1177 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001178 if (RECORD_DEVICE_IDLE_ALARMS) {
1179 if (mPendingIdleUntil == null) {
1180 IdleDispatchEntry ent = new IdleDispatchEntry();
1181 ent.uid = 0;
1182 ent.pkg = "START IDLE";
1183 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1184 mAllowWhileIdleDispatches.add(ent);
1185 }
1186 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001187 mPendingIdleUntil = a;
Dianne Hackborna750a632015-06-16 17:18:23 -07001188 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001189 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001190 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1191 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1192 mNextWakeFromIdle = a;
1193 // If this wake from idle is earlier than whatever was previously scheduled,
1194 // and we are currently idling, then we need to rebatch alarms in case the idle
1195 // until time needs to be updated.
1196 if (mPendingIdleUntil != null) {
1197 needRebatch = true;
1198 }
1199 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001200 }
1201
1202 if (!rebatching) {
1203 if (DEBUG_VALIDATE) {
1204 if (doValidate && !validateConsistencyLocked()) {
1205 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1206 + " when(hex)=" + Long.toHexString(a.when)
1207 + " whenElapsed=" + a.whenElapsed
1208 + " maxWhenElapsed=" + a.maxWhenElapsed
1209 + " interval=" + a.repeatInterval + " op=" + a.operation
1210 + " flags=0x" + Integer.toHexString(a.flags));
1211 rebatchAllAlarmsLocked(false);
1212 needRebatch = false;
1213 }
1214 }
1215
1216 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001217 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001218 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001219
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001220 rescheduleKernelAlarmsLocked();
1221 updateNextAlarmClockLocked();
1222 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001223 }
1224
Adam Lesinski182f73f2013-12-05 16:48:06 -08001225 private final IBinder mService = new IAlarmManager.Stub() {
1226 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001227 public void set(String callingPackage,
1228 int type, long triggerAtTime, long windowLength, long interval, int flags,
1229 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1230 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001231 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001232
1233 // make sure the caller is not lying about which package should be blamed for
1234 // wakelock time spent in alarm delivery
1235 mAppOps.checkPackage(callingUid, callingPackage);
1236
1237 // Repeating alarms must use PendingIntent, not direct listener
1238 if (interval != 0) {
1239 if (directReceiver != null) {
1240 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1241 }
1242 }
1243
Adam Lesinski182f73f2013-12-05 16:48:06 -08001244 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001245 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001246 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001247 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001248 }
1249
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001250 // No incoming callers can request either WAKE_FROM_IDLE or
1251 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1252 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1253 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1254
1255 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1256 // manager when to come out of idle mode, which is only for DeviceIdleController.
1257 if (callingUid != Process.SYSTEM_UID) {
1258 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1259 }
1260
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001261 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001262 if (windowLength == AlarmManager.WINDOW_EXACT) {
1263 flags |= AlarmManager.FLAG_STANDALONE;
1264 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001265
1266 // If this alarm is for an alarm clock, then it must be standalone and we will
1267 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001268 if (alarmClock != null) {
1269 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001270
1271 // If the caller is a core system component or on the user's whitelist, and not calling
1272 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1273 // This means we will allow these alarms to go off as normal even while idle, with no
1274 // timing restrictions.
1275 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
1276 || Arrays.binarySearch(mDeviceIdleUserWhitelist,
1277 UserHandle.getAppId(callingUid)) >= 0)) {
1278 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1279 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001280 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001281
Christopher Tate14a7bb02015-10-01 10:24:31 -07001282 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1283 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001284 }
Christopher Tate89779822012-08-31 14:40:03 -07001285
Adam Lesinski182f73f2013-12-05 16:48:06 -08001286 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001287 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001288 getContext().enforceCallingOrSelfPermission(
1289 "android.permission.SET_TIME",
1290 "setTime");
1291
Greg Hackmann0cab8962014-02-21 16:35:52 -08001292 if (mNativeData == 0) {
1293 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1294 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001295 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001296
1297 synchronized (mLock) {
1298 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001301
1302 @Override
1303 public void setTimeZone(String tz) {
1304 getContext().enforceCallingOrSelfPermission(
1305 "android.permission.SET_TIME_ZONE",
1306 "setTimeZone");
1307
1308 final long oldId = Binder.clearCallingIdentity();
1309 try {
1310 setTimeZoneImpl(tz);
1311 } finally {
1312 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001313 }
1314 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001315
Adam Lesinski182f73f2013-12-05 16:48:06 -08001316 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001317 public void remove(PendingIntent operation, IAlarmListener listener) {
1318 if (operation == null && listener == null) {
1319 Slog.w(TAG, "remove() with no intent or listener");
1320 return;
1321 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001322
Christopher Tate14a7bb02015-10-01 10:24:31 -07001323 synchronized (mLock) {
1324 removeLocked(operation, listener);
1325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001327
Adam Lesinski182f73f2013-12-05 16:48:06 -08001328 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001329 public long getNextWakeFromIdleTime() {
1330 return getNextWakeFromIdleTimeImpl();
1331 }
1332
1333 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001334 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001335 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1336 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1337 "getNextAlarmClock", null);
1338
1339 return getNextAlarmClockImpl(userId);
1340 }
1341
1342 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001343 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1344 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1345 != PackageManager.PERMISSION_GRANTED) {
1346 pw.println("Permission Denial: can't dump AlarmManager from from pid="
1347 + Binder.getCallingPid()
1348 + ", uid=" + Binder.getCallingUid());
1349 return;
Christopher Tate4cb338d2013-07-26 13:11:31 -07001350 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001351
Adam Lesinski182f73f2013-12-05 16:48:06 -08001352 dumpImpl(pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001353 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001354 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001355
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001356 public final class LocalService {
1357 public void setDeviceIdleUserWhitelist(int[] appids) {
1358 setDeviceIdleUserWhitelistImpl(appids);
1359 }
1360 }
1361
Adam Lesinski182f73f2013-12-05 16:48:06 -08001362 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363 synchronized (mLock) {
1364 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001365 mConstants.dump(pw);
1366 pw.println();
1367
Christopher Tatee0a22b32013-07-11 14:43:13 -07001368 final long nowRTC = System.currentTimeMillis();
1369 final long nowELAPSED = SystemClock.elapsedRealtime();
1370 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1371
Dianne Hackborna750a632015-06-16 17:18:23 -07001372 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001373 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001374 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001375 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001376 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001377 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001378 pw.print(" mLastTimeChangeRealtime=");
Dianne Hackbornc3527222015-05-13 14:03:20 -07001379 TimeUtils.formatDuration(mLastTimeChangeRealtime, pw);
1380 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001381 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001382 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001383 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1384 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001385 pw.print(" Max wakeup delay: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001386 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1387 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001388 pw.print(" Time since last dispatch: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001389 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1390 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001391 pw.print(" Next non-wakeup delivery time: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001392 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1393 pw.println();
1394 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001395
1396 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1397 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001398 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001399 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001400 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001401 pw.print(" Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001402 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001403 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
1404 pw.print(" set at "); TimeUtils.formatDuration(mLastWakeupSet, nowELAPSED, pw);
1405 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001406 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001407 pw.println(" mDeviceIdleUserWhitelist=" + Arrays.toString(mDeviceIdleUserWhitelist));
Christopher Tatee0a22b32013-07-11 14:43:13 -07001408
John Spurlock604a5ee2015-06-01 12:27:22 -04001409 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001410 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001411 final TreeSet<Integer> users = new TreeSet<>();
1412 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1413 users.add(mNextAlarmClockForUser.keyAt(i));
1414 }
1415 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1416 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1417 }
1418 for (int user : users) {
1419 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1420 final long time = next != null ? next.getTriggerTime() : 0;
1421 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001422 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001423 pw.print(" pendingSend:"); pw.print(pendingSend);
1424 pw.print(" time:"); pw.print(time);
1425 if (time > 0) {
1426 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1427 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1428 }
1429 pw.println();
1430 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001431 if (mAlarmBatches.size() > 0) {
1432 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001433 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001434 pw.println(mAlarmBatches.size());
1435 for (Batch b : mAlarmBatches) {
1436 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001437 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001438 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001440 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001441 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001442 pw.println(" Idle mode state:");
1443 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001444 if (mPendingIdleUntil != null) {
1445 pw.println(mPendingIdleUntil);
Dianne Hackbornf3831292015-10-15 14:51:06 -07001446 mPendingIdleUntil.dump(pw, " ", nowRTC, nowELAPSED, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001447 } else {
1448 pw.println("null");
1449 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001450 pw.println(" Pending alarms:");
1451 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001452 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001453 if (mNextWakeFromIdle != null) {
1454 pw.println();
1455 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
1456 mNextWakeFromIdle.dump(pw, " ", nowRTC, nowELAPSED, sdf);
1457 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001458
1459 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001460 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001461 if (mPendingNonWakeupAlarms.size() > 0) {
1462 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001463 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001464 } else {
1465 pw.println("(none)");
1466 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001467 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001468 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1469 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001470 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001471 pw.print(", max non-interactive time: ");
1472 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1473 pw.println();
1474
1475 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001476 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001477 pw.println();
1478
Christopher Tate7f2a0352015-12-08 10:24:33 -08001479 if (mInFlight.size() > 0) {
1480 pw.println("Outstanding deliveries:");
1481 for (int i = 0; i < mInFlight.size(); i++) {
1482 pw.print(" #"); pw.print(i); pw.print(": ");
1483 pw.println(mInFlight.get(i));
1484 }
1485 pw.println();
1486 }
1487
Dianne Hackborna750a632015-06-16 17:18:23 -07001488 pw.print(" mAllowWhileIdleMinTime=");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001489 TimeUtils.formatDuration(mAllowWhileIdleMinTime, pw);
1490 pw.println();
1491 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001492 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001493 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
1494 pw.print(" UID ");
1495 UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
1496 pw.print(": ");
1497 TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i),
1498 nowELAPSED, pw);
1499 pw.println();
1500 }
1501 }
1502 pw.println();
1503
Dianne Hackborn81038902012-11-26 17:04:09 -08001504 if (mLog.dump(pw, " Recent problems", " ")) {
1505 pw.println();
1506 }
1507
1508 final FilterStats[] topFilters = new FilterStats[10];
1509 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1510 @Override
1511 public int compare(FilterStats lhs, FilterStats rhs) {
1512 if (lhs.aggregateTime < rhs.aggregateTime) {
1513 return 1;
1514 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1515 return -1;
1516 }
1517 return 0;
1518 }
1519 };
1520 int len = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001521 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1522 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1523 for (int ip=0; ip<uidStats.size(); ip++) {
1524 BroadcastStats bs = uidStats.valueAt(ip);
1525 for (int is=0; is<bs.filterStats.size(); is++) {
1526 FilterStats fs = bs.filterStats.valueAt(is);
1527 int pos = len > 0
1528 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1529 if (pos < 0) {
1530 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001531 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001532 if (pos < topFilters.length) {
1533 int copylen = topFilters.length - pos - 1;
1534 if (copylen > 0) {
1535 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1536 }
1537 topFilters[pos] = fs;
1538 if (len < topFilters.length) {
1539 len++;
1540 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001541 }
1542 }
1543 }
1544 }
1545 if (len > 0) {
1546 pw.println(" Top Alarms:");
1547 for (int i=0; i<len; i++) {
1548 FilterStats fs = topFilters[i];
1549 pw.print(" ");
1550 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1551 TimeUtils.formatDuration(fs.aggregateTime, pw);
1552 pw.print(" running, "); pw.print(fs.numWakeup);
1553 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001554 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1555 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001556 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001557 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001558 pw.println();
1559 }
1560 }
1561
1562 pw.println(" ");
1563 pw.println(" Alarm Stats:");
1564 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001565 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1566 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1567 for (int ip=0; ip<uidStats.size(); ip++) {
1568 BroadcastStats bs = uidStats.valueAt(ip);
1569 pw.print(" ");
1570 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1571 UserHandle.formatUid(pw, bs.mUid);
1572 pw.print(":");
1573 pw.print(bs.mPackageName);
1574 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1575 pw.print(" running, "); pw.print(bs.numWakeup);
1576 pw.println(" wakeups:");
1577 tmpFilters.clear();
1578 for (int is=0; is<bs.filterStats.size(); is++) {
1579 tmpFilters.add(bs.filterStats.valueAt(is));
1580 }
1581 Collections.sort(tmpFilters, comparator);
1582 for (int i=0; i<tmpFilters.size(); i++) {
1583 FilterStats fs = tmpFilters.get(i);
1584 pw.print(" ");
1585 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1586 TimeUtils.formatDuration(fs.aggregateTime, pw);
1587 pw.print(" "); pw.print(fs.numWakeup);
1588 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001589 pw.print(" alarms, last ");
1590 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1591 pw.println(":");
1592 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001593 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001594 pw.println();
1595 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 }
1597 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001598
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001599 if (RECORD_DEVICE_IDLE_ALARMS) {
1600 pw.println();
1601 pw.println(" Allow while idle dispatches:");
1602 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
1603 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
1604 pw.print(" ");
1605 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
1606 pw.print(": ");
1607 UserHandle.formatUid(pw, ent.uid);
1608 pw.print(":");
1609 pw.println(ent.pkg);
1610 if (ent.op != null) {
1611 pw.print(" ");
1612 pw.print(ent.op);
1613 pw.print(" / ");
1614 pw.print(ent.tag);
1615 if (ent.argRealtime != 0) {
1616 pw.print(" (");
1617 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
1618 pw.print(")");
1619 }
1620 pw.println();
1621 }
1622 }
1623 }
1624
Christopher Tate18a75f12013-07-01 18:18:59 -07001625 if (WAKEUP_STATS) {
1626 pw.println();
1627 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001628 long last = -1;
1629 for (WakeupEvent event : mRecentWakeups) {
1630 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1631 pw.print('|');
1632 if (last < 0) {
1633 pw.print('0');
1634 } else {
1635 pw.print(event.when - last);
1636 }
1637 last = event.when;
1638 pw.print('|'); pw.print(event.uid);
1639 pw.print('|'); pw.print(event.action);
1640 pw.println();
1641 }
1642 pw.println();
1643 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 }
1645 }
1646
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001647 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001648 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
1649 PrintWriter pw = new PrintWriter(bs);
1650 final long nowRTC = System.currentTimeMillis();
1651 final long nowELAPSED = SystemClock.elapsedRealtime();
1652 final int NZ = mAlarmBatches.size();
1653 for (int iz = 0; iz < NZ; iz++) {
1654 Batch bz = mAlarmBatches.get(iz);
1655 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001656 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001657 pw.flush();
1658 Slog.v(TAG, bs.toString());
1659 bs.reset();
1660 }
1661 }
1662
1663 private boolean validateConsistencyLocked() {
1664 if (DEBUG_VALIDATE) {
1665 long lastTime = Long.MIN_VALUE;
1666 final int N = mAlarmBatches.size();
1667 for (int i = 0; i < N; i++) {
1668 Batch b = mAlarmBatches.get(i);
1669 if (b.start >= lastTime) {
1670 // duplicate start times are okay because of standalone batches
1671 lastTime = b.start;
1672 } else {
1673 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001674 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1675 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001676 return false;
1677 }
1678 }
1679 }
1680 return true;
1681 }
1682
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001683 private Batch findFirstWakeupBatchLocked() {
1684 final int N = mAlarmBatches.size();
1685 for (int i = 0; i < N; i++) {
1686 Batch b = mAlarmBatches.get(i);
1687 if (b.hasWakeups()) {
1688 return b;
1689 }
1690 }
1691 return null;
1692 }
1693
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001694 long getNextWakeFromIdleTimeImpl() {
1695 synchronized (mLock) {
1696 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
1697 }
1698 }
1699
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001700 void setDeviceIdleUserWhitelistImpl(int[] appids) {
1701 synchronized (mLock) {
1702 mDeviceIdleUserWhitelist = appids;
1703 }
1704 }
1705
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001706 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001707 synchronized (mLock) {
1708 return mNextAlarmClockForUser.get(userId);
1709 }
1710 }
1711
1712 /**
1713 * Recomputes the next alarm clock for all users.
1714 */
1715 private void updateNextAlarmClockLocked() {
1716 if (!mNextAlarmClockMayChange) {
1717 return;
1718 }
1719 mNextAlarmClockMayChange = false;
1720
Jose Lima235510e2014-08-13 12:50:01 -07001721 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001722 nextForUser.clear();
1723
1724 final int N = mAlarmBatches.size();
1725 for (int i = 0; i < N; i++) {
1726 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
1727 final int M = alarms.size();
1728
1729 for (int j = 0; j < M; j++) {
1730 Alarm a = alarms.get(j);
1731 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001732 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07001733 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001734
1735 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07001736 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001737 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02001738 " for user " + userId);
1739 }
1740
1741 // Alarms and batches are sorted by time, no need to compare times here.
1742 if (nextForUser.get(userId) == null) {
1743 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07001744 } else if (a.alarmClock.equals(current)
1745 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
1746 // same/earlier time and it's the one we cited before, so stick with it
1747 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001748 }
1749 }
1750 }
1751 }
1752
1753 // Update mNextAlarmForUser with new values.
1754 final int NN = nextForUser.size();
1755 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07001756 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001757 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001758 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001759 if (!newAlarm.equals(currentAlarm)) {
1760 updateNextAlarmInfoForUserLocked(userId, newAlarm);
1761 }
1762 }
1763
1764 // Remove users without any alarm clocks scheduled.
1765 final int NNN = mNextAlarmClockForUser.size();
1766 for (int i = NNN - 1; i >= 0; i--) {
1767 int userId = mNextAlarmClockForUser.keyAt(i);
1768 if (nextForUser.get(userId) == null) {
1769 updateNextAlarmInfoForUserLocked(userId, null);
1770 }
1771 }
1772 }
1773
Jose Lima235510e2014-08-13 12:50:01 -07001774 private void updateNextAlarmInfoForUserLocked(int userId,
1775 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001776 if (alarmClock != null) {
1777 if (DEBUG_ALARM_CLOCK) {
1778 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001779 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02001780 }
1781 mNextAlarmClockForUser.put(userId, alarmClock);
1782 } else {
1783 if (DEBUG_ALARM_CLOCK) {
1784 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
1785 }
1786 mNextAlarmClockForUser.remove(userId);
1787 }
1788
1789 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
1790 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1791 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1792 }
1793
1794 /**
1795 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
1796 * for which alarm clocks have changed since the last call to this.
1797 *
1798 * Do not call with a lock held. Only call from mHandler's thread.
1799 *
1800 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
1801 */
1802 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07001803 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001804 pendingUsers.clear();
1805
1806 synchronized (mLock) {
1807 final int N = mPendingSendNextAlarmClockChangedForUser.size();
1808 for (int i = 0; i < N; i++) {
1809 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
1810 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
1811 }
1812 mPendingSendNextAlarmClockChangedForUser.clear();
1813 }
1814
1815 final int N = pendingUsers.size();
1816 for (int i = 0; i < N; i++) {
1817 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001818 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001819 Settings.System.putStringForUser(getContext().getContentResolver(),
1820 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01001821 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02001822 userId);
1823
1824 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
1825 new UserHandle(userId));
1826 }
1827 }
1828
1829 /**
1830 * Formats an alarm like platform/packages/apps/DeskClock used to.
1831 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01001832 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
1833 int userId) {
1834 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02001835 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
1836 return (info == null) ? "" :
1837 DateFormat.format(pattern, info.getTriggerTime()).toString();
1838 }
1839
Adam Lesinski182f73f2013-12-05 16:48:06 -08001840 void rescheduleKernelAlarmsLocked() {
1841 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
1842 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001843 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001844 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001845 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001846 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07001847 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001848 mNextWakeup = firstWakeup.start;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001849 mLastWakeupSet = SystemClock.elapsedRealtime();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001850 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001851 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001852 if (firstBatch != firstWakeup) {
1853 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001854 }
1855 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001856 if (mPendingNonWakeupAlarms.size() > 0) {
1857 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
1858 nextNonWakeup = mNextNonWakeupDeliveryTime;
1859 }
1860 }
Prashant Malani753e9e02015-06-10 17:43:49 -07001861 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001862 mNextNonWakeup = nextNonWakeup;
1863 setLocked(ELAPSED_REALTIME, nextNonWakeup);
1864 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001865 }
1866
Christopher Tate14a7bb02015-10-01 10:24:31 -07001867 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001868 boolean didRemove = false;
1869 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1870 Batch b = mAlarmBatches.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -07001871 didRemove |= b.remove(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001872 if (b.size() == 0) {
1873 mAlarmBatches.remove(i);
1874 }
1875 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001876 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001877 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001878 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1879 mPendingWhileIdleAlarms.remove(i);
1880 }
1881 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001882
1883 if (didRemove) {
1884 if (DEBUG_BATCH) {
1885 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
1886 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001887 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001888 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001889 mPendingIdleUntil = null;
1890 restorePending = true;
1891 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001892 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001893 mNextWakeFromIdle = null;
1894 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001895 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001896 if (restorePending) {
1897 restorePendingWhileIdleAlarmsLocked();
1898 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001899 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001900 }
1901 }
1902
1903 void removeLocked(String packageName) {
1904 boolean didRemove = false;
1905 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1906 Batch b = mAlarmBatches.get(i);
1907 didRemove |= b.remove(packageName);
1908 if (b.size() == 0) {
1909 mAlarmBatches.remove(i);
1910 }
1911 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001912 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001913 final Alarm a = mPendingWhileIdleAlarms.get(i);
1914 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001915 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1916 mPendingWhileIdleAlarms.remove(i);
1917 }
1918 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001919
1920 if (didRemove) {
1921 if (DEBUG_BATCH) {
1922 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1923 }
1924 rebatchAllAlarmsLocked(true);
1925 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001926 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001927 }
1928 }
1929
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001930 void removeForStoppedLocked(int uid) {
1931 boolean didRemove = false;
1932 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1933 Batch b = mAlarmBatches.get(i);
1934 didRemove |= b.removeForStopped(uid);
1935 if (b.size() == 0) {
1936 mAlarmBatches.remove(i);
1937 }
1938 }
1939 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1940 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08001941 if (a.uid == uid) {
1942 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1943 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001944 }
1945 }
1946
1947 if (didRemove) {
1948 if (DEBUG_BATCH) {
1949 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1950 }
1951 rebatchAllAlarmsLocked(true);
1952 rescheduleKernelAlarmsLocked();
1953 updateNextAlarmClockLocked();
1954 }
1955 }
1956
Adam Lesinski182f73f2013-12-05 16:48:06 -08001957 void removeUserLocked(int userHandle) {
1958 boolean didRemove = false;
1959 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1960 Batch b = mAlarmBatches.get(i);
1961 didRemove |= b.remove(userHandle);
1962 if (b.size() == 0) {
1963 mAlarmBatches.remove(i);
1964 }
1965 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001966 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001967 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001968 == userHandle) {
1969 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1970 mPendingWhileIdleAlarms.remove(i);
1971 }
1972 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001973 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
1974 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
1975 mLastAllowWhileIdleDispatch.removeAt(i);
1976 }
1977 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001978
1979 if (didRemove) {
1980 if (DEBUG_BATCH) {
1981 Slog.v(TAG, "remove(user) changed bounds; rebatching");
1982 }
1983 rebatchAllAlarmsLocked(true);
1984 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001985 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001986 }
1987 }
1988
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001989 void interactiveStateChangedLocked(boolean interactive) {
1990 if (mInteractive != interactive) {
1991 mInteractive = interactive;
1992 final long nowELAPSED = SystemClock.elapsedRealtime();
1993 if (interactive) {
1994 if (mPendingNonWakeupAlarms.size() > 0) {
1995 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1996 mTotalDelayTime += thisDelayTime;
1997 if (mMaxDelayTime < thisDelayTime) {
1998 mMaxDelayTime = thisDelayTime;
1999 }
2000 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2001 mPendingNonWakeupAlarms.clear();
2002 }
2003 if (mNonInteractiveStartTime > 0) {
2004 long dur = nowELAPSED - mNonInteractiveStartTime;
2005 if (dur > mNonInteractiveTime) {
2006 mNonInteractiveTime = dur;
2007 }
2008 }
2009 } else {
2010 mNonInteractiveStartTime = nowELAPSED;
2011 }
2012 }
2013 }
2014
Adam Lesinski182f73f2013-12-05 16:48:06 -08002015 boolean lookForPackageLocked(String packageName) {
2016 for (int i = 0; i < mAlarmBatches.size(); i++) {
2017 Batch b = mAlarmBatches.get(i);
2018 if (b.hasPackage(packageName)) {
2019 return true;
2020 }
2021 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002022 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002023 final Alarm a = mPendingWhileIdleAlarms.get(i);
2024 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002025 return true;
2026 }
2027 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002028 return false;
2029 }
2030
2031 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002032 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002033 // The kernel never triggers alarms with negative wakeup times
2034 // so we ensure they are positive.
2035 long alarmSeconds, alarmNanoseconds;
2036 if (when < 0) {
2037 alarmSeconds = 0;
2038 alarmNanoseconds = 0;
2039 } else {
2040 alarmSeconds = when / 1000;
2041 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2042 }
2043
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002044 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002045 } else {
2046 Message msg = Message.obtain();
2047 msg.what = ALARM_EVENT;
2048
2049 mHandler.removeMessages(ALARM_EVENT);
2050 mHandler.sendMessageAtTime(msg, when);
2051 }
2052 }
2053
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002054 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002055 String prefix, String label, long nowRTC, long nowELAPSED, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002056 for (int i=list.size()-1; i>=0; i--) {
2057 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002058 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2059 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002060 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002061 }
2062 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002063
2064 private static final String labelForType(int type) {
2065 switch (type) {
2066 case RTC: return "RTC";
2067 case RTC_WAKEUP : return "RTC_WAKEUP";
2068 case ELAPSED_REALTIME : return "ELAPSED";
2069 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
2070 default:
2071 break;
2072 }
2073 return "--unknown--";
2074 }
2075
2076 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002077 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002078 for (int i=list.size()-1; i>=0; i--) {
2079 Alarm a = list.get(i);
2080 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002081 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2082 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002083 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002084 }
2085 }
2086
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002087 private native long init();
2088 private native void close(long nativeData);
2089 private native void set(long nativeData, int type, long seconds, long nanoseconds);
2090 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08002091 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002092 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002094 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002095 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002096 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002097 // batches are temporally sorted, so we need only pull from the
2098 // start of the list until we either empty it or hit a batch
2099 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07002100 while (mAlarmBatches.size() > 0) {
2101 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002102 if (batch.start > nowELAPSED) {
2103 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002104 break;
2105 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002106
Christopher Tatee0a22b32013-07-11 14:43:13 -07002107 // We will (re)schedule some alarms now; don't let that interfere
2108 // with delivery of this current batch
2109 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002110
Christopher Tatee0a22b32013-07-11 14:43:13 -07002111 final int N = batch.size();
2112 for (int i = 0; i < N; i++) {
2113 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002114
2115 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
2116 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
2117 // schedule such alarms.
2118 long lastTime = mLastAllowWhileIdleDispatch.get(alarm.uid, 0);
2119 long minTime = lastTime + mAllowWhileIdleMinTime;
2120 if (nowELAPSED < minTime) {
2121 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
2122 // alarm went off for this app. Reschedule the alarm to be in the
2123 // correct time period.
2124 alarm.whenElapsed = minTime;
2125 if (alarm.maxWhenElapsed < minTime) {
2126 alarm.maxWhenElapsed = minTime;
2127 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002128 if (RECORD_DEVICE_IDLE_ALARMS) {
2129 IdleDispatchEntry ent = new IdleDispatchEntry();
2130 ent.uid = alarm.uid;
2131 ent.pkg = alarm.operation.getCreatorPackage();
2132 ent.tag = alarm.operation.getTag("");
2133 ent.op = "RESCHEDULE";
2134 ent.elapsedRealtime = nowELAPSED;
2135 ent.argRealtime = lastTime;
2136 mAllowWhileIdleDispatches.add(ent);
2137 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002138 setImplLocked(alarm, true, false);
2139 continue;
2140 }
2141 }
2142
Christopher Tatee0a22b32013-07-11 14:43:13 -07002143 alarm.count = 1;
2144 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002145 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
2146 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002147 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002148 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002149 if (mPendingIdleUntil == alarm) {
2150 mPendingIdleUntil = null;
2151 rebatchAllAlarmsLocked(false);
2152 restorePendingWhileIdleAlarmsLocked();
2153 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002154 if (mNextWakeFromIdle == alarm) {
2155 mNextWakeFromIdle = null;
2156 rebatchAllAlarmsLocked(false);
2157 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002158
2159 // Recurring alarms may have passed several alarm intervals while the
2160 // phone was asleep or off, so pass a trigger count when sending them.
2161 if (alarm.repeatInterval > 0) {
2162 // this adjustment will be zero if we're late by
2163 // less than one full repeat interval
2164 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
2165
2166 // Also schedule its next recurrence
2167 final long delta = alarm.count * alarm.repeatInterval;
2168 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07002169 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07002170 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07002171 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
2172 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08002173 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002174
Christopher Tate864d42e2014-12-02 11:48:53 -08002175 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002176 hasWakeup = true;
2177 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002178
2179 // We removed an alarm clock. Let the caller recompute the next alarm clock.
2180 if (alarm.alarmClock != null) {
2181 mNextAlarmClockMayChange = true;
2182 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07002183 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002184 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002185
Christopher Tate1590f1e2014-10-02 17:27:57 -07002186 // This is a new alarm delivery set; bump the sequence number to indicate that
2187 // all apps' alarm delivery classes should be recalculated.
2188 mCurrentSeq++;
2189 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002190 Collections.sort(triggerList, mAlarmDispatchComparator);
2191
2192 if (localLOGV) {
2193 for (int i=0; i<triggerList.size(); i++) {
2194 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
2195 }
2196 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002197
2198 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002199 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002201 /**
2202 * This Comparator sorts Alarms into increasing time order.
2203 */
2204 public static class IncreasingTimeOrder implements Comparator<Alarm> {
2205 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09002206 long when1 = a1.whenElapsed;
2207 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002208 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002209 return 1;
2210 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002211 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002212 return -1;
2213 }
2214 return 0;
2215 }
2216 }
2217
2218 private static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002219 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002220 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002221 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002222 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002223 public final IAlarmListener listener;
2224 public final String listenerTag;
2225 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002226 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002227 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002228 public final AlarmManager.AlarmClockInfo alarmClock;
2229 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002230 public final int creatorUid;
2231 public final String packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002232 public int count;
2233 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07002234 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002235 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002236 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002237 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07002238 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002239
Christopher Tate3e04b472013-10-21 17:51:31 -07002240 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002241 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
2242 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
2243 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002244 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002245 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002246 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
2247 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002248 when = _when;
2249 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07002250 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002251 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002252 repeatInterval = _interval;
2253 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002254 listener = _rec;
2255 listenerTag = _listenerTag;
2256 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07002257 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002258 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002259 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002260 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002261 packageName = _pkgName;
2262
2263 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002264 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002265
Christopher Tate14a7bb02015-10-01 10:24:31 -07002266 public static String makeTag(PendingIntent pi, String tag, int type) {
2267 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
2268 ? "*walarm*:" : "*alarm*:";
2269 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
2270 }
2271
2272 public WakeupEvent makeWakeupEvent(long nowRTC) {
2273 return new WakeupEvent(nowRTC, creatorUid,
2274 (operation != null)
2275 ? operation.getIntent().getAction()
2276 : ("<listener>:" + listenerTag));
2277 }
2278
2279 // Returns true if either matches
2280 public boolean matches(PendingIntent pi, IAlarmListener rec) {
2281 return (operation != null)
2282 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09002283 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07002284 }
2285
2286 public boolean matches(String packageName) {
2287 return (operation != null)
2288 ? packageName.equals(operation.getTargetPackage())
2289 : packageName.equals(this.packageName);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002290 }
2291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002292 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002293 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002294 StringBuilder sb = new StringBuilder(128);
2295 sb.append("Alarm{");
2296 sb.append(Integer.toHexString(System.identityHashCode(this)));
2297 sb.append(" type ");
2298 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002299 sb.append(" when ");
2300 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002301 sb.append(" ");
Christopher Tate14a7bb02015-10-01 10:24:31 -07002302 if (operation != null) {
2303 sb.append(operation.getTargetPackage());
2304 } else {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002305 sb.append(packageName);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002306 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002307 sb.append('}');
2308 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002309 }
2310
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002311 public void dump(PrintWriter pw, String prefix, long nowRTC, long nowELAPSED,
2312 SimpleDateFormat sdf) {
2313 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002314 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002315 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002316 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
2317 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002318 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002319 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002320 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002321 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002322 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002323 }
2324 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002325 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002326 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002327 pw.print(" count="); pw.print(count);
2328 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002329 if (alarmClock != null) {
2330 pw.print(prefix); pw.println("Alarm clock:");
2331 pw.print(prefix); pw.print(" triggerTime=");
2332 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
2333 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
2334 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002335 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002336 if (listener != null) {
2337 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
2338 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002339 }
2340 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002341
Christopher Tatee0a22b32013-07-11 14:43:13 -07002342 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
2343 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002344 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
2345 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002346 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07002347 break;
2348 }
2349
Christopher Tatee0a22b32013-07-11 14:43:13 -07002350 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002351 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
2352 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002353 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07002354 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002355 }
2356 }
2357
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002358 long currentNonWakeupFuzzLocked(long nowELAPSED) {
2359 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
2360 if (timeSinceOn < 5*60*1000) {
2361 // If the screen has been off for 5 minutes, only delay by at most two minutes.
2362 return 2*60*1000;
2363 } else if (timeSinceOn < 30*60*1000) {
2364 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
2365 return 15*60*1000;
2366 } else {
2367 // Otherwise, we will delay by at most an hour.
2368 return 60*60*1000;
2369 }
2370 }
2371
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002372 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002373 if (duration < 15*60*1000) {
2374 // If the duration until the time is less than 15 minutes, the maximum fuzz
2375 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002376 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002377 } else if (duration < 90*60*1000) {
2378 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
2379 return 15*60*1000;
2380 } else {
2381 // Otherwise, we will fuzz by at most half an hour.
2382 return 30*60*1000;
2383 }
2384 }
2385
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002386 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
2387 if (mInteractive) {
2388 return false;
2389 }
2390 if (mLastAlarmDeliveryTime <= 0) {
2391 return false;
2392 }
minho.choo649acab2014-12-12 16:13:55 +09002393 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002394 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
2395 // and the next delivery time is in the past, then just deliver them all. This
2396 // avoids bugs where we get stuck in a loop trying to poll for alarms.
2397 return false;
2398 }
2399 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
2400 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
2401 }
2402
2403 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
2404 mLastAlarmDeliveryTime = nowELAPSED;
2405 for (int i=0; i<triggerList.size(); i++) {
2406 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07002407 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002408 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07002409 if (localLOGV) {
2410 Slog.v(TAG, "sending alarm " + alarm);
2411 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07002412 if (RECORD_ALARMS_IN_HISTORY) {
2413 if (alarm.workSource != null && alarm.workSource.size() > 0) {
2414 for (int wi=0; wi<alarm.workSource.size(); wi++) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002415 ActivityManager.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002416 alarm.operation, alarm.workSource.get(wi), alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002417 }
2418 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002419 ActivityManager.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002420 alarm.operation, alarm.uid, alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002421 }
2422 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002423 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002424 } catch (RuntimeException e) {
2425 Slog.w(TAG, "Failure sending alarm.", e);
2426 }
2427 }
2428 }
2429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430 private class AlarmThread extends Thread
2431 {
2432 public AlarmThread()
2433 {
2434 super("AlarmManager");
2435 }
2436
2437 public void run()
2438 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002439 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2440
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002441 while (true)
2442 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002443 int result = waitForAlarm(mNativeData);
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002444 mLastWakeup = SystemClock.elapsedRealtime();
Dianne Hackborn390517b2013-05-30 15:03:32 -07002445
2446 triggerList.clear();
2447
Dianne Hackbornc3527222015-05-13 14:03:20 -07002448 final long nowRTC = System.currentTimeMillis();
2449 final long nowELAPSED = SystemClock.elapsedRealtime();
2450
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002451 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002452 // The kernel can give us spurious time change notifications due to
2453 // small adjustments it makes internally; we want to filter those out.
2454 final long lastTimeChangeClockTime;
2455 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07002456 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002457 lastTimeChangeClockTime = mLastTimeChangeClockTime;
2458 expectedClockTime = lastTimeChangeClockTime
2459 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07002460 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002461 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-500)
2462 || nowRTC > (expectedClockTime+500)) {
2463 // The change is by at least +/- 500 ms (or this is the first change),
2464 // let's do it!
2465 if (DEBUG_BATCH) {
2466 Slog.v(TAG, "Time changed notification from kernel; rebatching");
2467 }
2468 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07002469 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07002470 rebatchAllAlarms();
2471 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07002472 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07002473 synchronized (mLock) {
2474 mNumTimeChanged++;
2475 mLastTimeChangeClockTime = nowRTC;
2476 mLastTimeChangeRealtime = nowELAPSED;
2477 }
2478 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
2479 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
2480 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2481 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
2482
2483 // The world has changed on us, so we need to re-evaluate alarms
2484 // regardless of whether the kernel has told us one went off.
2485 result |= IS_WAKEUP_MASK;
2486 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002487 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488
Dianne Hackbornc3527222015-05-13 14:03:20 -07002489 if (result != TIME_CHANGED_MASK) {
2490 // If this was anything besides just a time change, then figure what if
2491 // anything to do about alarms.
2492 synchronized (mLock) {
2493 if (localLOGV) Slog.v(
2494 TAG, "Checking for alarms... rtc=" + nowRTC
2495 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07002496
Dianne Hackbornc3527222015-05-13 14:03:20 -07002497 if (WAKEUP_STATS) {
2498 if ((result & IS_WAKEUP_MASK) != 0) {
2499 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
2500 int n = 0;
2501 for (WakeupEvent event : mRecentWakeups) {
2502 if (event.when > newEarliest) break;
2503 n++; // number of now-stale entries at the list head
2504 }
2505 for (int i = 0; i < n; i++) {
2506 mRecentWakeups.remove();
2507 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002508
Dianne Hackbornc3527222015-05-13 14:03:20 -07002509 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002510 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002511 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002512
2513 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2514 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
2515 // if there are no wakeup alarms and the screen is off, we can
2516 // delay what we have so far until the future.
2517 if (mPendingNonWakeupAlarms.size() == 0) {
2518 mStartCurrentDelayTime = nowELAPSED;
2519 mNextNonWakeupDeliveryTime = nowELAPSED
2520 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
2521 }
2522 mPendingNonWakeupAlarms.addAll(triggerList);
2523 mNumDelayedAlarms += triggerList.size();
2524 rescheduleKernelAlarmsLocked();
2525 updateNextAlarmClockLocked();
2526 } else {
2527 // now deliver the alarm intents; if there are pending non-wakeup
2528 // alarms, we need to merge them in to the list. note we don't
2529 // just deliver them first because we generally want non-wakeup
2530 // alarms delivered after wakeup alarms.
2531 rescheduleKernelAlarmsLocked();
2532 updateNextAlarmClockLocked();
2533 if (mPendingNonWakeupAlarms.size() > 0) {
2534 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
2535 triggerList.addAll(mPendingNonWakeupAlarms);
2536 Collections.sort(triggerList, mAlarmDispatchComparator);
2537 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2538 mTotalDelayTime += thisDelayTime;
2539 if (mMaxDelayTime < thisDelayTime) {
2540 mMaxDelayTime = thisDelayTime;
2541 }
2542 mPendingNonWakeupAlarms.clear();
2543 }
2544 deliverAlarmsLocked(triggerList, nowELAPSED);
2545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002546 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002547
2548 } else {
2549 // Just in case -- even though no wakeup flag was set, make sure
2550 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07002551 synchronized (mLock) {
2552 rescheduleKernelAlarmsLocked();
2553 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002554 }
2555 }
2556 }
2557 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002558
David Christieebe51fc2013-07-26 13:23:29 -07002559 /**
2560 * Attribute blame for a WakeLock.
2561 * @param pi PendingIntent to attribute blame to if ws is null.
2562 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002563 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07002564 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002565 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002566 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07002567 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002568 final boolean unimportant = pi == mTimeTickSender;
2569 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002570 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002571 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002572 } else {
2573 mWakeLock.setHistoryTag(null);
2574 }
2575 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07002576 if (ws != null) {
2577 mWakeLock.setWorkSource(ws);
2578 return;
2579 }
2580
Christopher Tate14a7bb02015-10-01 10:24:31 -07002581 final int uid = (knownUid >= 0)
2582 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002583 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07002584 if (uid >= 0) {
2585 mWakeLock.setWorkSource(new WorkSource(uid));
2586 return;
2587 }
2588 } catch (Exception e) {
2589 }
2590
2591 // Something went wrong; fall back to attributing the lock to the OS
2592 mWakeLock.setWorkSource(null);
2593 }
2594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002595 private class AlarmHandler extends Handler {
2596 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002597 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
2598 public static final int LISTENER_TIMEOUT = 3;
2599 public static final int REPORT_ALARMS_ACTIVE = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002600
2601 public AlarmHandler() {
2602 }
2603
2604 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002605 switch (msg.what) {
2606 case ALARM_EVENT: {
2607 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2608 synchronized (mLock) {
2609 final long nowRTC = System.currentTimeMillis();
2610 final long nowELAPSED = SystemClock.elapsedRealtime();
2611 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2612 updateNextAlarmClockLocked();
2613 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002614
Christopher Tate14a7bb02015-10-01 10:24:31 -07002615 // now trigger the alarms without the lock held
2616 for (int i=0; i<triggerList.size(); i++) {
2617 Alarm alarm = triggerList.get(i);
2618 try {
2619 alarm.operation.send();
2620 } catch (PendingIntent.CanceledException e) {
2621 if (alarm.repeatInterval > 0) {
2622 // This IntentSender is no longer valid, but this
2623 // is a repeating alarm, so toss the hoser.
2624 removeImpl(alarm.operation);
2625 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002626 }
2627 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002628 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002629 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002630
2631 case SEND_NEXT_ALARM_CLOCK_CHANGED:
2632 sendNextAlarmClockChanged();
2633 break;
2634
2635 case LISTENER_TIMEOUT:
2636 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
2637 break;
2638
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002639 case REPORT_ALARMS_ACTIVE:
2640 if (mLocalDeviceIdleController != null) {
2641 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
2642 }
2643 break;
2644
Christopher Tate14a7bb02015-10-01 10:24:31 -07002645 default:
2646 // nope, just ignore it
2647 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002648 }
2649 }
2650 }
2651
2652 class ClockReceiver extends BroadcastReceiver {
2653 public ClockReceiver() {
2654 IntentFilter filter = new IntentFilter();
2655 filter.addAction(Intent.ACTION_TIME_TICK);
2656 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002657 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002658 }
2659
2660 @Override
2661 public void onReceive(Context context, Intent intent) {
2662 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07002663 if (DEBUG_BATCH) {
2664 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
2665 }
2666 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002667 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
2668 // Since the kernel does not keep track of DST, we need to
2669 // reset the TZ information at the beginning of each day
2670 // based off of the current Zone gmt offset + userspace tracked
2671 // daylight savings information.
2672 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02002673 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002674 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07002675 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002676 }
2677 }
2678
2679 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07002680 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09002681 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07002682
2683 // Schedule this event for the amount of time that it would take to get to
2684 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09002685 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07002686
David Christieebe51fc2013-07-26 13:23:29 -07002687 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002688 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002689 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
2690 null, Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002691 }
Christopher Tate385e4982013-07-23 18:22:29 -07002692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002693 public void scheduleDateChangedEvent() {
2694 Calendar calendar = Calendar.getInstance();
2695 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07002696 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002697 calendar.set(Calendar.MINUTE, 0);
2698 calendar.set(Calendar.SECOND, 0);
2699 calendar.set(Calendar.MILLISECOND, 0);
2700 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07002701
2702 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002703 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
2704 AlarmManager.FLAG_STANDALONE, workSource, null,
2705 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002706 }
2707 }
2708
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002709 class InteractiveStateReceiver extends BroadcastReceiver {
2710 public InteractiveStateReceiver() {
2711 IntentFilter filter = new IntentFilter();
2712 filter.addAction(Intent.ACTION_SCREEN_OFF);
2713 filter.addAction(Intent.ACTION_SCREEN_ON);
2714 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
2715 getContext().registerReceiver(this, filter);
2716 }
2717
2718 @Override
2719 public void onReceive(Context context, Intent intent) {
2720 synchronized (mLock) {
2721 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
2722 }
2723 }
2724 }
2725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002726 class UninstallReceiver extends BroadcastReceiver {
2727 public UninstallReceiver() {
2728 IntentFilter filter = new IntentFilter();
2729 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2730 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002731 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002732 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08002733 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002734 // Register for events related to sdcard installation.
2735 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08002736 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002737 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002738 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002739 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002740 }
2741
2742 @Override
2743 public void onReceive(Context context, Intent intent) {
2744 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002745 String action = intent.getAction();
2746 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002747 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
2748 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
2749 for (String packageName : pkgList) {
2750 if (lookForPackageLocked(packageName)) {
2751 setResultCode(Activity.RESULT_OK);
2752 return;
2753 }
2754 }
2755 return;
2756 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002757 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002758 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
2759 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
2760 if (userHandle >= 0) {
2761 removeUserLocked(userHandle);
2762 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002763 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
2764 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
2765 if (uid >= 0) {
2766 mLastAllowWhileIdleDispatch.delete(uid);
2767 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002768 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08002769 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
2770 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
2771 // This package is being updated; don't kill its alarms.
2772 return;
2773 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002774 Uri data = intent.getData();
2775 if (data != null) {
2776 String pkg = data.getSchemeSpecificPart();
2777 if (pkg != null) {
2778 pkgList = new String[]{pkg};
2779 }
2780 }
2781 }
2782 if (pkgList != null && (pkgList.length > 0)) {
2783 for (String pkg : pkgList) {
2784 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07002785 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002786 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
2787 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
2788 if (uidStats.remove(pkg) != null) {
2789 if (uidStats.size() <= 0) {
2790 mBroadcastStats.removeAt(i);
2791 }
2792 }
2793 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002794 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002795 }
2796 }
2797 }
2798 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002799
2800 final class UidObserver extends IUidObserver.Stub {
2801 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
2802 }
2803
Dianne Hackborne07641d2016-11-09 15:07:23 -08002804 @Override public void onUidGone(int uid, boolean disabled) throws RemoteException {
2805 if (disabled) {
2806 synchronized (mLock) {
2807 removeForStoppedLocked(uid);
2808 }
2809 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002810 }
2811
2812 @Override public void onUidActive(int uid) throws RemoteException {
2813 }
2814
Dianne Hackborne07641d2016-11-09 15:07:23 -08002815 @Override public void onUidIdle(int uid, boolean disabled) throws RemoteException {
2816 if (disabled) {
2817 synchronized (mLock) {
2818 removeForStoppedLocked(uid);
2819 }
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08002820 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002821 }
2822 };
2823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002825 String pkg = pi.getCreatorPackage();
2826 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002827 return getStatsLocked(uid, pkg);
2828 }
2829
2830 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002831 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
2832 if (uidStats == null) {
2833 uidStats = new ArrayMap<String, BroadcastStats>();
2834 mBroadcastStats.put(uid, uidStats);
2835 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002836 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002837 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002838 bs = new BroadcastStats(uid, pkgName);
2839 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002840 }
2841 return bs;
2842 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002843
Christopher Tate14a7bb02015-10-01 10:24:31 -07002844 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
2845 private InFlight removeLocked(PendingIntent pi, Intent intent) {
2846 for (int i = 0; i < mInFlight.size(); i++) {
2847 if (mInFlight.get(i).mPendingIntent == pi) {
2848 return mInFlight.remove(i);
2849 }
2850 }
2851 mLog.w("No in-flight alarm for " + pi + " " + intent);
2852 return null;
2853 }
2854
2855 private InFlight removeLocked(IBinder listener) {
2856 for (int i = 0; i < mInFlight.size(); i++) {
2857 if (mInFlight.get(i).mListener == listener) {
2858 return mInFlight.remove(i);
2859 }
2860 }
2861 mLog.w("No in-flight alarm for listener " + listener);
2862 return null;
2863 }
2864
2865 private void updateStatsLocked(InFlight inflight) {
2866 final long nowELAPSED = SystemClock.elapsedRealtime();
2867 BroadcastStats bs = inflight.mBroadcastStats;
2868 bs.nesting--;
2869 if (bs.nesting <= 0) {
2870 bs.nesting = 0;
2871 bs.aggregateTime += nowELAPSED - bs.startTime;
2872 }
2873 FilterStats fs = inflight.mFilterStats;
2874 fs.nesting--;
2875 if (fs.nesting <= 0) {
2876 fs.nesting = 0;
2877 fs.aggregateTime += nowELAPSED - fs.startTime;
2878 }
2879 if (RECORD_ALARMS_IN_HISTORY) {
2880 if (inflight.mWorkSource != null && inflight.mWorkSource.size() > 0) {
2881 for (int wi=0; wi<inflight.mWorkSource.size(); wi++) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002882 ActivityManager.noteAlarmFinish(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002883 inflight.mPendingIntent, inflight.mWorkSource.get(wi), inflight.mTag);
2884 }
2885 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002886 ActivityManager.noteAlarmFinish(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002887 inflight.mPendingIntent, inflight.mUid, inflight.mTag);
2888 }
2889 }
2890 }
2891
2892 private void updateTrackingLocked(InFlight inflight) {
2893 if (inflight != null) {
2894 updateStatsLocked(inflight);
2895 }
2896 mBroadcastRefCount--;
2897 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002898 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002899 mWakeLock.release();
2900 if (mInFlight.size() > 0) {
2901 mLog.w("Finished all dispatches with " + mInFlight.size()
2902 + " remaining inflights");
2903 for (int i=0; i<mInFlight.size(); i++) {
2904 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
2905 }
2906 mInFlight.clear();
2907 }
2908 } else {
2909 // the next of our alarms is now in flight. reattribute the wakelock.
2910 if (mInFlight.size() > 0) {
2911 InFlight inFlight = mInFlight.get(0);
2912 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
2913 inFlight.mAlarmType, inFlight.mTag, -1, false);
2914 } else {
2915 // should never happen
2916 mLog.w("Alarm wakelock still held but sent queue empty");
2917 mWakeLock.setWorkSource(null);
2918 }
2919 }
2920 }
2921
2922 /**
2923 * Callback that arrives when a direct-call alarm reports that delivery has finished
2924 */
2925 @Override
2926 public void alarmComplete(IBinder who) {
2927 if (who == null) {
2928 Slog.w(TAG, "Invalid alarmComplete: uid=" + Binder.getCallingUid()
2929 + " pid=" + Binder.getCallingPid());
2930 return;
2931 }
2932
2933 final long ident = Binder.clearCallingIdentity();
2934 try {
2935 synchronized (mLock) {
2936 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
2937 InFlight inflight = removeLocked(who);
2938 if (inflight != null) {
2939 if (DEBUG_LISTENER_CALLBACK) {
2940 Slog.i(TAG, "alarmComplete() from " + who);
2941 }
2942 updateTrackingLocked(inflight);
2943 } else {
2944 // Delivery timed out, and the timeout handling already took care of
2945 // updating our tracking here, so we needn't do anything further.
2946 if (DEBUG_LISTENER_CALLBACK) {
2947 Slog.i(TAG, "Late alarmComplete() from " + who);
2948 }
2949 }
2950 }
2951 } finally {
2952 Binder.restoreCallingIdentity(ident);
2953 }
2954 }
2955
2956 /**
2957 * Callback that arrives when a PendingIntent alarm has finished delivery
2958 */
2959 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002960 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
2961 String resultData, Bundle resultExtras) {
2962 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002963 updateTrackingLocked(removeLocked(pi, intent));
2964 }
2965 }
2966
2967 /**
2968 * Timeout of a direct-call alarm delivery
2969 */
2970 public void alarmTimedOut(IBinder who) {
2971 synchronized (mLock) {
2972 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08002973 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002974 // TODO: implement ANR policy for the target
2975 if (DEBUG_LISTENER_CALLBACK) {
2976 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002977 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002978 updateTrackingLocked(inflight);
Dianne Hackborn81038902012-11-26 17:04:09 -08002979 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002980 if (DEBUG_LISTENER_CALLBACK) {
2981 Slog.i(TAG, "Spurious timeout of listener " + who);
2982 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002983 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002984 }
2985 }
2986
2987 /**
2988 * Deliver an alarm and set up the post-delivery handling appropriately
2989 */
2990 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
2991 if (alarm.operation != null) {
2992 // PendingIntent alarm
2993 try {
2994 alarm.operation.send(getContext(), 0,
2995 mBackgroundIntent.putExtra(
2996 Intent.EXTRA_ALARM_COUNT, alarm.count),
2997 mDeliveryTracker, mHandler, null,
2998 allowWhileIdle ? mIdleOptions : null);
2999 } catch (PendingIntent.CanceledException e) {
3000 if (alarm.repeatInterval > 0) {
3001 // This IntentSender is no longer valid, but this
3002 // is a repeating alarm, so toss it
3003 removeImpl(alarm.operation);
3004 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003005 // No actual delivery was possible, so the delivery tracker's
3006 // 'finished' callback won't be invoked. We also don't need
3007 // to do any wakelock or stats tracking, so we have nothing
3008 // left to do here but go on to the next thing.
3009 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003010 }
3011 } else {
3012 // Direct listener callback alarm
3013 try {
3014 if (DEBUG_LISTENER_CALLBACK) {
3015 Slog.v(TAG, "Alarm to uid=" + alarm.uid
3016 + " listener=" + alarm.listener.asBinder());
3017 }
3018 alarm.listener.doAlarm(this);
3019 mHandler.sendMessageDelayed(
3020 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
3021 alarm.listener.asBinder()),
3022 mConstants.LISTENER_TIMEOUT);
3023 } catch (Exception e) {
3024 if (DEBUG_LISTENER_CALLBACK) {
3025 Slog.i(TAG, "Alarm undeliverable to listener "
3026 + alarm.listener.asBinder(), e);
3027 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003028 // As in the PendingIntent.CanceledException case, delivery of the
3029 // alarm was not possible, so we have no wakelock or timeout or
3030 // stats management to do. It threw before we posted the delayed
3031 // timeout message, so we're done here.
3032 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003033 }
3034 }
3035
3036 // The alarm is now in flight; now arrange wakelock and stats tracking
3037 if (mBroadcastRefCount == 0) {
3038 setWakelockWorkSource(alarm.operation, alarm.workSource,
3039 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
3040 true);
3041 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003042 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003043 }
3044 final InFlight inflight = new InFlight(AlarmManagerService.this,
3045 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
3046 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
3047 mInFlight.add(inflight);
3048 mBroadcastRefCount++;
3049
3050 if (allowWhileIdle) {
3051 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
3052 mLastAllowWhileIdleDispatch.put(alarm.uid, nowELAPSED);
3053 if (RECORD_DEVICE_IDLE_ALARMS) {
3054 IdleDispatchEntry ent = new IdleDispatchEntry();
3055 ent.uid = alarm.uid;
3056 ent.pkg = alarm.packageName;
3057 ent.tag = alarm.statsTag;
3058 ent.op = "DELIVER";
3059 ent.elapsedRealtime = nowELAPSED;
3060 mAllowWhileIdleDispatches.add(ent);
3061 }
3062 }
3063
3064 final BroadcastStats bs = inflight.mBroadcastStats;
3065 bs.count++;
3066 if (bs.nesting == 0) {
3067 bs.nesting = 1;
3068 bs.startTime = nowELAPSED;
3069 } else {
3070 bs.nesting++;
3071 }
3072 final FilterStats fs = inflight.mFilterStats;
3073 fs.count++;
3074 if (fs.nesting == 0) {
3075 fs.nesting = 1;
3076 fs.startTime = nowELAPSED;
3077 } else {
3078 fs.nesting++;
3079 }
3080 if (alarm.type == ELAPSED_REALTIME_WAKEUP
3081 || alarm.type == RTC_WAKEUP) {
3082 bs.numWakeup++;
3083 fs.numWakeup++;
3084 if (alarm.workSource != null && alarm.workSource.size() > 0) {
3085 for (int wi=0; wi<alarm.workSource.size(); wi++) {
Christopher Tate0029f572016-06-14 10:16:28 -07003086 final String wsName = alarm.workSource.getName(wi);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003087 ActivityManager.noteWakeupAlarm(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003088 alarm.operation, alarm.workSource.get(wi),
Christopher Tate0029f572016-06-14 10:16:28 -07003089 (wsName != null) ? wsName : alarm.packageName,
3090 alarm.statsTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08003091 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003092 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003093 ActivityManager.noteWakeupAlarm(
Joe Onorato78bcdf92016-05-09 10:10:29 -07003094 alarm.operation, alarm.uid, alarm.packageName, alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003095 }
3096 }
3097 }
3098 }
3099}