blob: 581aa05d7d3299601eab67c4e9eaa6f62b98a708 [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 {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800507 if (alarm.uid == uid && ActivityManager.getService().getAppStartMode(
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700508 uid, alarm.packageName) == ActivityManager.APP_START_MODE_DISABLED) {
509 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 {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001092 if (ActivityManager.getService().getAppStartMode(callingUid, callingPackage)
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001093 == ActivityManager.APP_START_MODE_DISABLED) {
1094 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1095 + " -- package not allowed to start");
1096 return;
1097 }
1098 } catch (RemoteException e) {
1099 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001100 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001101 setImplLocked(a, false, doValidate);
1102 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001103
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001104 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1105 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001106 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001107 // The caller has given the time they want this to happen at, however we need
1108 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001109 // bring us out of idle at an earlier time.
1110 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001111 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001112 }
1113 // Add fuzz to make the alarm go off some time before the actual desired time.
1114 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001115 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001116 if (fuzz > 0) {
1117 if (mRandom == null) {
1118 mRandom = new Random();
1119 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001120 final int delta = mRandom.nextInt(fuzz);
1121 a.whenElapsed -= delta;
1122 if (false) {
1123 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1124 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1125 Slog.d(TAG, "Applied fuzz: " + fuzz);
1126 Slog.d(TAG, "Final delta: " + delta);
1127 Slog.d(TAG, "Final when: " + a.whenElapsed);
1128 }
1129 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001130 }
1131
1132 } else if (mPendingIdleUntil != null) {
1133 // We currently have an idle until alarm scheduled; if the new alarm has
1134 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001135 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1136 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1137 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001138 == 0) {
1139 mPendingWhileIdleAlarms.add(a);
1140 return;
1141 }
1142 }
1143
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001144 if (RECORD_DEVICE_IDLE_ALARMS) {
1145 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1146 IdleDispatchEntry ent = new IdleDispatchEntry();
1147 ent.uid = a.uid;
1148 ent.pkg = a.operation.getCreatorPackage();
1149 ent.tag = a.operation.getTag("");
1150 ent.op = "SET";
1151 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1152 ent.argRealtime = a.whenElapsed;
1153 mAllowWhileIdleDispatches.add(ent);
1154 }
1155 }
1156
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001157 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
1158 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -07001159 if (whichBatch < 0) {
1160 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001161 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162 } else {
Christopher Tate385e4982013-07-23 18:22:29 -07001163 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001164 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001165 // The start time of this batch advanced, so batch ordering may
1166 // have just been broken. Move it to where it now belongs.
1167 mAlarmBatches.remove(whichBatch);
1168 addBatchLocked(mAlarmBatches, batch);
1169 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001170 }
1171
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001172 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001173 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001174 }
1175
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001176 boolean needRebatch = false;
1177
1178 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001179 if (RECORD_DEVICE_IDLE_ALARMS) {
1180 if (mPendingIdleUntil == null) {
1181 IdleDispatchEntry ent = new IdleDispatchEntry();
1182 ent.uid = 0;
1183 ent.pkg = "START IDLE";
1184 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1185 mAllowWhileIdleDispatches.add(ent);
1186 }
1187 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001188 mPendingIdleUntil = a;
Dianne Hackborna750a632015-06-16 17:18:23 -07001189 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001190 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001191 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1192 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1193 mNextWakeFromIdle = a;
1194 // If this wake from idle is earlier than whatever was previously scheduled,
1195 // and we are currently idling, then we need to rebatch alarms in case the idle
1196 // until time needs to be updated.
1197 if (mPendingIdleUntil != null) {
1198 needRebatch = true;
1199 }
1200 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001201 }
1202
1203 if (!rebatching) {
1204 if (DEBUG_VALIDATE) {
1205 if (doValidate && !validateConsistencyLocked()) {
1206 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1207 + " when(hex)=" + Long.toHexString(a.when)
1208 + " whenElapsed=" + a.whenElapsed
1209 + " maxWhenElapsed=" + a.maxWhenElapsed
1210 + " interval=" + a.repeatInterval + " op=" + a.operation
1211 + " flags=0x" + Integer.toHexString(a.flags));
1212 rebatchAllAlarmsLocked(false);
1213 needRebatch = false;
1214 }
1215 }
1216
1217 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001218 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001219 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001220
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001221 rescheduleKernelAlarmsLocked();
1222 updateNextAlarmClockLocked();
1223 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001224 }
1225
Adam Lesinski182f73f2013-12-05 16:48:06 -08001226 private final IBinder mService = new IAlarmManager.Stub() {
1227 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001228 public void set(String callingPackage,
1229 int type, long triggerAtTime, long windowLength, long interval, int flags,
1230 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1231 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001232 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001233
1234 // make sure the caller is not lying about which package should be blamed for
1235 // wakelock time spent in alarm delivery
1236 mAppOps.checkPackage(callingUid, callingPackage);
1237
1238 // Repeating alarms must use PendingIntent, not direct listener
1239 if (interval != 0) {
1240 if (directReceiver != null) {
1241 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1242 }
1243 }
1244
Adam Lesinski182f73f2013-12-05 16:48:06 -08001245 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001246 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001247 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001248 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001249 }
1250
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001251 // No incoming callers can request either WAKE_FROM_IDLE or
1252 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1253 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1254 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1255
1256 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1257 // manager when to come out of idle mode, which is only for DeviceIdleController.
1258 if (callingUid != Process.SYSTEM_UID) {
1259 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1260 }
1261
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001262 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001263 if (windowLength == AlarmManager.WINDOW_EXACT) {
1264 flags |= AlarmManager.FLAG_STANDALONE;
1265 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001266
1267 // If this alarm is for an alarm clock, then it must be standalone and we will
1268 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001269 if (alarmClock != null) {
1270 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001271
1272 // If the caller is a core system component or on the user's whitelist, and not calling
1273 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1274 // This means we will allow these alarms to go off as normal even while idle, with no
1275 // timing restrictions.
1276 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
1277 || Arrays.binarySearch(mDeviceIdleUserWhitelist,
1278 UserHandle.getAppId(callingUid)) >= 0)) {
1279 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1280 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001281 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001282
Christopher Tate14a7bb02015-10-01 10:24:31 -07001283 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1284 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001285 }
Christopher Tate89779822012-08-31 14:40:03 -07001286
Adam Lesinski182f73f2013-12-05 16:48:06 -08001287 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001288 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001289 getContext().enforceCallingOrSelfPermission(
1290 "android.permission.SET_TIME",
1291 "setTime");
1292
Greg Hackmann0cab8962014-02-21 16:35:52 -08001293 if (mNativeData == 0) {
1294 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1295 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001296 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001297
1298 synchronized (mLock) {
1299 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001302
1303 @Override
1304 public void setTimeZone(String tz) {
1305 getContext().enforceCallingOrSelfPermission(
1306 "android.permission.SET_TIME_ZONE",
1307 "setTimeZone");
1308
1309 final long oldId = Binder.clearCallingIdentity();
1310 try {
1311 setTimeZoneImpl(tz);
1312 } finally {
1313 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 }
1315 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001316
Adam Lesinski182f73f2013-12-05 16:48:06 -08001317 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001318 public void remove(PendingIntent operation, IAlarmListener listener) {
1319 if (operation == null && listener == null) {
1320 Slog.w(TAG, "remove() with no intent or listener");
1321 return;
1322 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001323
Christopher Tate14a7bb02015-10-01 10:24:31 -07001324 synchronized (mLock) {
1325 removeLocked(operation, listener);
1326 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001328
Adam Lesinski182f73f2013-12-05 16:48:06 -08001329 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001330 public long getNextWakeFromIdleTime() {
1331 return getNextWakeFromIdleTimeImpl();
1332 }
1333
1334 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001335 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001336 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1337 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1338 "getNextAlarmClock", null);
1339
1340 return getNextAlarmClockImpl(userId);
1341 }
1342
1343 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001344 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1345 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1346 != PackageManager.PERMISSION_GRANTED) {
1347 pw.println("Permission Denial: can't dump AlarmManager from from pid="
1348 + Binder.getCallingPid()
1349 + ", uid=" + Binder.getCallingUid());
1350 return;
Christopher Tate4cb338d2013-07-26 13:11:31 -07001351 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001352
Adam Lesinski182f73f2013-12-05 16:48:06 -08001353 dumpImpl(pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001354 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001355 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001356
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001357 public final class LocalService {
1358 public void setDeviceIdleUserWhitelist(int[] appids) {
1359 setDeviceIdleUserWhitelistImpl(appids);
1360 }
1361 }
1362
Adam Lesinski182f73f2013-12-05 16:48:06 -08001363 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 synchronized (mLock) {
1365 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001366 mConstants.dump(pw);
1367 pw.println();
1368
Christopher Tatee0a22b32013-07-11 14:43:13 -07001369 final long nowRTC = System.currentTimeMillis();
1370 final long nowELAPSED = SystemClock.elapsedRealtime();
1371 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1372
Dianne Hackborna750a632015-06-16 17:18:23 -07001373 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001374 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001375 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001376 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001377 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001378 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001379 pw.print(" mLastTimeChangeRealtime=");
Dianne Hackbornc3527222015-05-13 14:03:20 -07001380 TimeUtils.formatDuration(mLastTimeChangeRealtime, pw);
1381 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001382 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001383 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001384 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1385 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001386 pw.print(" Max wakeup delay: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001387 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1388 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001389 pw.print(" Time since last dispatch: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001390 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1391 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001392 pw.print(" Next non-wakeup delivery time: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001393 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1394 pw.println();
1395 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001396
1397 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1398 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001399 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001400 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001401 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001402 pw.print(" Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001403 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001404 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
1405 pw.print(" set at "); TimeUtils.formatDuration(mLastWakeupSet, nowELAPSED, pw);
1406 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001407 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001408 pw.println(" mDeviceIdleUserWhitelist=" + Arrays.toString(mDeviceIdleUserWhitelist));
Christopher Tatee0a22b32013-07-11 14:43:13 -07001409
John Spurlock604a5ee2015-06-01 12:27:22 -04001410 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001411 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001412 final TreeSet<Integer> users = new TreeSet<>();
1413 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1414 users.add(mNextAlarmClockForUser.keyAt(i));
1415 }
1416 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1417 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1418 }
1419 for (int user : users) {
1420 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1421 final long time = next != null ? next.getTriggerTime() : 0;
1422 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001423 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001424 pw.print(" pendingSend:"); pw.print(pendingSend);
1425 pw.print(" time:"); pw.print(time);
1426 if (time > 0) {
1427 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1428 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1429 }
1430 pw.println();
1431 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001432 if (mAlarmBatches.size() > 0) {
1433 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001434 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001435 pw.println(mAlarmBatches.size());
1436 for (Batch b : mAlarmBatches) {
1437 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001438 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001439 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001441 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001442 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001443 pw.println(" Idle mode state:");
1444 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001445 if (mPendingIdleUntil != null) {
1446 pw.println(mPendingIdleUntil);
Dianne Hackbornf3831292015-10-15 14:51:06 -07001447 mPendingIdleUntil.dump(pw, " ", nowRTC, nowELAPSED, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001448 } else {
1449 pw.println("null");
1450 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001451 pw.println(" Pending alarms:");
1452 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001453 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001454 if (mNextWakeFromIdle != null) {
1455 pw.println();
1456 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
1457 mNextWakeFromIdle.dump(pw, " ", nowRTC, nowELAPSED, sdf);
1458 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001459
1460 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001461 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001462 if (mPendingNonWakeupAlarms.size() > 0) {
1463 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001464 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001465 } else {
1466 pw.println("(none)");
1467 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001468 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001469 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1470 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001471 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001472 pw.print(", max non-interactive time: ");
1473 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1474 pw.println();
1475
1476 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001477 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001478 pw.println();
1479
Christopher Tate7f2a0352015-12-08 10:24:33 -08001480 if (mInFlight.size() > 0) {
1481 pw.println("Outstanding deliveries:");
1482 for (int i = 0; i < mInFlight.size(); i++) {
1483 pw.print(" #"); pw.print(i); pw.print(": ");
1484 pw.println(mInFlight.get(i));
1485 }
1486 pw.println();
1487 }
1488
Dianne Hackborna750a632015-06-16 17:18:23 -07001489 pw.print(" mAllowWhileIdleMinTime=");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001490 TimeUtils.formatDuration(mAllowWhileIdleMinTime, pw);
1491 pw.println();
1492 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001493 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001494 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
1495 pw.print(" UID ");
1496 UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
1497 pw.print(": ");
1498 TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i),
1499 nowELAPSED, pw);
1500 pw.println();
1501 }
1502 }
1503 pw.println();
1504
Dianne Hackborn81038902012-11-26 17:04:09 -08001505 if (mLog.dump(pw, " Recent problems", " ")) {
1506 pw.println();
1507 }
1508
1509 final FilterStats[] topFilters = new FilterStats[10];
1510 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1511 @Override
1512 public int compare(FilterStats lhs, FilterStats rhs) {
1513 if (lhs.aggregateTime < rhs.aggregateTime) {
1514 return 1;
1515 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1516 return -1;
1517 }
1518 return 0;
1519 }
1520 };
1521 int len = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001522 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1523 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1524 for (int ip=0; ip<uidStats.size(); ip++) {
1525 BroadcastStats bs = uidStats.valueAt(ip);
1526 for (int is=0; is<bs.filterStats.size(); is++) {
1527 FilterStats fs = bs.filterStats.valueAt(is);
1528 int pos = len > 0
1529 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1530 if (pos < 0) {
1531 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001532 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001533 if (pos < topFilters.length) {
1534 int copylen = topFilters.length - pos - 1;
1535 if (copylen > 0) {
1536 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1537 }
1538 topFilters[pos] = fs;
1539 if (len < topFilters.length) {
1540 len++;
1541 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001542 }
1543 }
1544 }
1545 }
1546 if (len > 0) {
1547 pw.println(" Top Alarms:");
1548 for (int i=0; i<len; i++) {
1549 FilterStats fs = topFilters[i];
1550 pw.print(" ");
1551 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1552 TimeUtils.formatDuration(fs.aggregateTime, pw);
1553 pw.print(" running, "); pw.print(fs.numWakeup);
1554 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001555 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1556 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001557 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001558 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001559 pw.println();
1560 }
1561 }
1562
1563 pw.println(" ");
1564 pw.println(" Alarm Stats:");
1565 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001566 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1567 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1568 for (int ip=0; ip<uidStats.size(); ip++) {
1569 BroadcastStats bs = uidStats.valueAt(ip);
1570 pw.print(" ");
1571 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1572 UserHandle.formatUid(pw, bs.mUid);
1573 pw.print(":");
1574 pw.print(bs.mPackageName);
1575 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1576 pw.print(" running, "); pw.print(bs.numWakeup);
1577 pw.println(" wakeups:");
1578 tmpFilters.clear();
1579 for (int is=0; is<bs.filterStats.size(); is++) {
1580 tmpFilters.add(bs.filterStats.valueAt(is));
1581 }
1582 Collections.sort(tmpFilters, comparator);
1583 for (int i=0; i<tmpFilters.size(); i++) {
1584 FilterStats fs = tmpFilters.get(i);
1585 pw.print(" ");
1586 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1587 TimeUtils.formatDuration(fs.aggregateTime, pw);
1588 pw.print(" "); pw.print(fs.numWakeup);
1589 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001590 pw.print(" alarms, last ");
1591 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1592 pw.println(":");
1593 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001594 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001595 pw.println();
1596 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597 }
1598 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001599
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001600 if (RECORD_DEVICE_IDLE_ALARMS) {
1601 pw.println();
1602 pw.println(" Allow while idle dispatches:");
1603 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
1604 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
1605 pw.print(" ");
1606 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
1607 pw.print(": ");
1608 UserHandle.formatUid(pw, ent.uid);
1609 pw.print(":");
1610 pw.println(ent.pkg);
1611 if (ent.op != null) {
1612 pw.print(" ");
1613 pw.print(ent.op);
1614 pw.print(" / ");
1615 pw.print(ent.tag);
1616 if (ent.argRealtime != 0) {
1617 pw.print(" (");
1618 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
1619 pw.print(")");
1620 }
1621 pw.println();
1622 }
1623 }
1624 }
1625
Christopher Tate18a75f12013-07-01 18:18:59 -07001626 if (WAKEUP_STATS) {
1627 pw.println();
1628 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001629 long last = -1;
1630 for (WakeupEvent event : mRecentWakeups) {
1631 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1632 pw.print('|');
1633 if (last < 0) {
1634 pw.print('0');
1635 } else {
1636 pw.print(event.when - last);
1637 }
1638 last = event.when;
1639 pw.print('|'); pw.print(event.uid);
1640 pw.print('|'); pw.print(event.action);
1641 pw.println();
1642 }
1643 pw.println();
1644 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 }
1646 }
1647
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001648 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001649 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
1650 PrintWriter pw = new PrintWriter(bs);
1651 final long nowRTC = System.currentTimeMillis();
1652 final long nowELAPSED = SystemClock.elapsedRealtime();
1653 final int NZ = mAlarmBatches.size();
1654 for (int iz = 0; iz < NZ; iz++) {
1655 Batch bz = mAlarmBatches.get(iz);
1656 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001657 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001658 pw.flush();
1659 Slog.v(TAG, bs.toString());
1660 bs.reset();
1661 }
1662 }
1663
1664 private boolean validateConsistencyLocked() {
1665 if (DEBUG_VALIDATE) {
1666 long lastTime = Long.MIN_VALUE;
1667 final int N = mAlarmBatches.size();
1668 for (int i = 0; i < N; i++) {
1669 Batch b = mAlarmBatches.get(i);
1670 if (b.start >= lastTime) {
1671 // duplicate start times are okay because of standalone batches
1672 lastTime = b.start;
1673 } else {
1674 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001675 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1676 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001677 return false;
1678 }
1679 }
1680 }
1681 return true;
1682 }
1683
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001684 private Batch findFirstWakeupBatchLocked() {
1685 final int N = mAlarmBatches.size();
1686 for (int i = 0; i < N; i++) {
1687 Batch b = mAlarmBatches.get(i);
1688 if (b.hasWakeups()) {
1689 return b;
1690 }
1691 }
1692 return null;
1693 }
1694
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001695 long getNextWakeFromIdleTimeImpl() {
1696 synchronized (mLock) {
1697 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
1698 }
1699 }
1700
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001701 void setDeviceIdleUserWhitelistImpl(int[] appids) {
1702 synchronized (mLock) {
1703 mDeviceIdleUserWhitelist = appids;
1704 }
1705 }
1706
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001707 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001708 synchronized (mLock) {
1709 return mNextAlarmClockForUser.get(userId);
1710 }
1711 }
1712
1713 /**
1714 * Recomputes the next alarm clock for all users.
1715 */
1716 private void updateNextAlarmClockLocked() {
1717 if (!mNextAlarmClockMayChange) {
1718 return;
1719 }
1720 mNextAlarmClockMayChange = false;
1721
Jose Lima235510e2014-08-13 12:50:01 -07001722 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001723 nextForUser.clear();
1724
1725 final int N = mAlarmBatches.size();
1726 for (int i = 0; i < N; i++) {
1727 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
1728 final int M = alarms.size();
1729
1730 for (int j = 0; j < M; j++) {
1731 Alarm a = alarms.get(j);
1732 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001733 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07001734 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001735
1736 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07001737 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001738 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02001739 " for user " + userId);
1740 }
1741
1742 // Alarms and batches are sorted by time, no need to compare times here.
1743 if (nextForUser.get(userId) == null) {
1744 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07001745 } else if (a.alarmClock.equals(current)
1746 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
1747 // same/earlier time and it's the one we cited before, so stick with it
1748 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001749 }
1750 }
1751 }
1752 }
1753
1754 // Update mNextAlarmForUser with new values.
1755 final int NN = nextForUser.size();
1756 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07001757 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001758 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001759 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001760 if (!newAlarm.equals(currentAlarm)) {
1761 updateNextAlarmInfoForUserLocked(userId, newAlarm);
1762 }
1763 }
1764
1765 // Remove users without any alarm clocks scheduled.
1766 final int NNN = mNextAlarmClockForUser.size();
1767 for (int i = NNN - 1; i >= 0; i--) {
1768 int userId = mNextAlarmClockForUser.keyAt(i);
1769 if (nextForUser.get(userId) == null) {
1770 updateNextAlarmInfoForUserLocked(userId, null);
1771 }
1772 }
1773 }
1774
Jose Lima235510e2014-08-13 12:50:01 -07001775 private void updateNextAlarmInfoForUserLocked(int userId,
1776 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001777 if (alarmClock != null) {
1778 if (DEBUG_ALARM_CLOCK) {
1779 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001780 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02001781 }
1782 mNextAlarmClockForUser.put(userId, alarmClock);
1783 } else {
1784 if (DEBUG_ALARM_CLOCK) {
1785 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
1786 }
1787 mNextAlarmClockForUser.remove(userId);
1788 }
1789
1790 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
1791 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1792 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1793 }
1794
1795 /**
1796 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
1797 * for which alarm clocks have changed since the last call to this.
1798 *
1799 * Do not call with a lock held. Only call from mHandler's thread.
1800 *
1801 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
1802 */
1803 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07001804 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001805 pendingUsers.clear();
1806
1807 synchronized (mLock) {
1808 final int N = mPendingSendNextAlarmClockChangedForUser.size();
1809 for (int i = 0; i < N; i++) {
1810 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
1811 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
1812 }
1813 mPendingSendNextAlarmClockChangedForUser.clear();
1814 }
1815
1816 final int N = pendingUsers.size();
1817 for (int i = 0; i < N; i++) {
1818 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001819 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001820 Settings.System.putStringForUser(getContext().getContentResolver(),
1821 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01001822 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02001823 userId);
1824
1825 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
1826 new UserHandle(userId));
1827 }
1828 }
1829
1830 /**
1831 * Formats an alarm like platform/packages/apps/DeskClock used to.
1832 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01001833 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
1834 int userId) {
1835 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02001836 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
1837 return (info == null) ? "" :
1838 DateFormat.format(pattern, info.getTriggerTime()).toString();
1839 }
1840
Adam Lesinski182f73f2013-12-05 16:48:06 -08001841 void rescheduleKernelAlarmsLocked() {
1842 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
1843 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001844 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001845 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001846 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001847 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07001848 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001849 mNextWakeup = firstWakeup.start;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001850 mLastWakeupSet = SystemClock.elapsedRealtime();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001851 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001852 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001853 if (firstBatch != firstWakeup) {
1854 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001855 }
1856 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001857 if (mPendingNonWakeupAlarms.size() > 0) {
1858 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
1859 nextNonWakeup = mNextNonWakeupDeliveryTime;
1860 }
1861 }
Prashant Malani753e9e02015-06-10 17:43:49 -07001862 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001863 mNextNonWakeup = nextNonWakeup;
1864 setLocked(ELAPSED_REALTIME, nextNonWakeup);
1865 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001866 }
1867
Christopher Tate14a7bb02015-10-01 10:24:31 -07001868 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001869 boolean didRemove = false;
1870 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1871 Batch b = mAlarmBatches.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -07001872 didRemove |= b.remove(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001873 if (b.size() == 0) {
1874 mAlarmBatches.remove(i);
1875 }
1876 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001877 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001878 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001879 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1880 mPendingWhileIdleAlarms.remove(i);
1881 }
1882 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001883
1884 if (didRemove) {
1885 if (DEBUG_BATCH) {
1886 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
1887 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001888 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001889 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001890 mPendingIdleUntil = null;
1891 restorePending = true;
1892 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001893 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001894 mNextWakeFromIdle = null;
1895 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001896 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001897 if (restorePending) {
1898 restorePendingWhileIdleAlarmsLocked();
1899 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001900 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001901 }
1902 }
1903
1904 void removeLocked(String packageName) {
1905 boolean didRemove = false;
1906 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1907 Batch b = mAlarmBatches.get(i);
1908 didRemove |= b.remove(packageName);
1909 if (b.size() == 0) {
1910 mAlarmBatches.remove(i);
1911 }
1912 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001913 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001914 final Alarm a = mPendingWhileIdleAlarms.get(i);
1915 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001916 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1917 mPendingWhileIdleAlarms.remove(i);
1918 }
1919 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001920
1921 if (didRemove) {
1922 if (DEBUG_BATCH) {
1923 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1924 }
1925 rebatchAllAlarmsLocked(true);
1926 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001927 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001928 }
1929 }
1930
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001931 void removeForStoppedLocked(int uid) {
1932 boolean didRemove = false;
1933 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1934 Batch b = mAlarmBatches.get(i);
1935 didRemove |= b.removeForStopped(uid);
1936 if (b.size() == 0) {
1937 mAlarmBatches.remove(i);
1938 }
1939 }
1940 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1941 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08001942 if (a.uid == uid) {
1943 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1944 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001945 }
1946 }
1947
1948 if (didRemove) {
1949 if (DEBUG_BATCH) {
1950 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1951 }
1952 rebatchAllAlarmsLocked(true);
1953 rescheduleKernelAlarmsLocked();
1954 updateNextAlarmClockLocked();
1955 }
1956 }
1957
Adam Lesinski182f73f2013-12-05 16:48:06 -08001958 void removeUserLocked(int userHandle) {
1959 boolean didRemove = false;
1960 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1961 Batch b = mAlarmBatches.get(i);
1962 didRemove |= b.remove(userHandle);
1963 if (b.size() == 0) {
1964 mAlarmBatches.remove(i);
1965 }
1966 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001967 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001968 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001969 == userHandle) {
1970 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1971 mPendingWhileIdleAlarms.remove(i);
1972 }
1973 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001974 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
1975 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
1976 mLastAllowWhileIdleDispatch.removeAt(i);
1977 }
1978 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001979
1980 if (didRemove) {
1981 if (DEBUG_BATCH) {
1982 Slog.v(TAG, "remove(user) changed bounds; rebatching");
1983 }
1984 rebatchAllAlarmsLocked(true);
1985 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001986 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001987 }
1988 }
1989
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001990 void interactiveStateChangedLocked(boolean interactive) {
1991 if (mInteractive != interactive) {
1992 mInteractive = interactive;
1993 final long nowELAPSED = SystemClock.elapsedRealtime();
1994 if (interactive) {
1995 if (mPendingNonWakeupAlarms.size() > 0) {
1996 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1997 mTotalDelayTime += thisDelayTime;
1998 if (mMaxDelayTime < thisDelayTime) {
1999 mMaxDelayTime = thisDelayTime;
2000 }
2001 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2002 mPendingNonWakeupAlarms.clear();
2003 }
2004 if (mNonInteractiveStartTime > 0) {
2005 long dur = nowELAPSED - mNonInteractiveStartTime;
2006 if (dur > mNonInteractiveTime) {
2007 mNonInteractiveTime = dur;
2008 }
2009 }
2010 } else {
2011 mNonInteractiveStartTime = nowELAPSED;
2012 }
2013 }
2014 }
2015
Adam Lesinski182f73f2013-12-05 16:48:06 -08002016 boolean lookForPackageLocked(String packageName) {
2017 for (int i = 0; i < mAlarmBatches.size(); i++) {
2018 Batch b = mAlarmBatches.get(i);
2019 if (b.hasPackage(packageName)) {
2020 return true;
2021 }
2022 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002023 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002024 final Alarm a = mPendingWhileIdleAlarms.get(i);
2025 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002026 return true;
2027 }
2028 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002029 return false;
2030 }
2031
2032 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002033 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002034 // The kernel never triggers alarms with negative wakeup times
2035 // so we ensure they are positive.
2036 long alarmSeconds, alarmNanoseconds;
2037 if (when < 0) {
2038 alarmSeconds = 0;
2039 alarmNanoseconds = 0;
2040 } else {
2041 alarmSeconds = when / 1000;
2042 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2043 }
2044
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002045 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002046 } else {
2047 Message msg = Message.obtain();
2048 msg.what = ALARM_EVENT;
2049
2050 mHandler.removeMessages(ALARM_EVENT);
2051 mHandler.sendMessageAtTime(msg, when);
2052 }
2053 }
2054
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002055 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002056 String prefix, String label, long nowRTC, long nowELAPSED, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002057 for (int i=list.size()-1; i>=0; i--) {
2058 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002059 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2060 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002061 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002062 }
2063 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002064
2065 private static final String labelForType(int type) {
2066 switch (type) {
2067 case RTC: return "RTC";
2068 case RTC_WAKEUP : return "RTC_WAKEUP";
2069 case ELAPSED_REALTIME : return "ELAPSED";
2070 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
2071 default:
2072 break;
2073 }
2074 return "--unknown--";
2075 }
2076
2077 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002078 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002079 for (int i=list.size()-1; i>=0; i--) {
2080 Alarm a = list.get(i);
2081 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002082 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2083 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002084 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002085 }
2086 }
2087
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002088 private native long init();
2089 private native void close(long nativeData);
2090 private native void set(long nativeData, int type, long seconds, long nanoseconds);
2091 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08002092 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002093 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002094
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002095 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002096 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002097 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002098 // batches are temporally sorted, so we need only pull from the
2099 // start of the list until we either empty it or hit a batch
2100 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07002101 while (mAlarmBatches.size() > 0) {
2102 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002103 if (batch.start > nowELAPSED) {
2104 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002105 break;
2106 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002107
Christopher Tatee0a22b32013-07-11 14:43:13 -07002108 // We will (re)schedule some alarms now; don't let that interfere
2109 // with delivery of this current batch
2110 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002111
Christopher Tatee0a22b32013-07-11 14:43:13 -07002112 final int N = batch.size();
2113 for (int i = 0; i < N; i++) {
2114 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002115
2116 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
2117 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
2118 // schedule such alarms.
2119 long lastTime = mLastAllowWhileIdleDispatch.get(alarm.uid, 0);
2120 long minTime = lastTime + mAllowWhileIdleMinTime;
2121 if (nowELAPSED < minTime) {
2122 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
2123 // alarm went off for this app. Reschedule the alarm to be in the
2124 // correct time period.
2125 alarm.whenElapsed = minTime;
2126 if (alarm.maxWhenElapsed < minTime) {
2127 alarm.maxWhenElapsed = minTime;
2128 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002129 if (RECORD_DEVICE_IDLE_ALARMS) {
2130 IdleDispatchEntry ent = new IdleDispatchEntry();
2131 ent.uid = alarm.uid;
2132 ent.pkg = alarm.operation.getCreatorPackage();
2133 ent.tag = alarm.operation.getTag("");
2134 ent.op = "RESCHEDULE";
2135 ent.elapsedRealtime = nowELAPSED;
2136 ent.argRealtime = lastTime;
2137 mAllowWhileIdleDispatches.add(ent);
2138 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002139 setImplLocked(alarm, true, false);
2140 continue;
2141 }
2142 }
2143
Christopher Tatee0a22b32013-07-11 14:43:13 -07002144 alarm.count = 1;
2145 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002146 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
2147 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002148 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002149 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002150 if (mPendingIdleUntil == alarm) {
2151 mPendingIdleUntil = null;
2152 rebatchAllAlarmsLocked(false);
2153 restorePendingWhileIdleAlarmsLocked();
2154 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002155 if (mNextWakeFromIdle == alarm) {
2156 mNextWakeFromIdle = null;
2157 rebatchAllAlarmsLocked(false);
2158 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002159
2160 // Recurring alarms may have passed several alarm intervals while the
2161 // phone was asleep or off, so pass a trigger count when sending them.
2162 if (alarm.repeatInterval > 0) {
2163 // this adjustment will be zero if we're late by
2164 // less than one full repeat interval
2165 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
2166
2167 // Also schedule its next recurrence
2168 final long delta = alarm.count * alarm.repeatInterval;
2169 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07002170 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07002171 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07002172 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
2173 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08002174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002175
Christopher Tate864d42e2014-12-02 11:48:53 -08002176 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002177 hasWakeup = true;
2178 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002179
2180 // We removed an alarm clock. Let the caller recompute the next alarm clock.
2181 if (alarm.alarmClock != null) {
2182 mNextAlarmClockMayChange = true;
2183 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07002184 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002185 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002186
Christopher Tate1590f1e2014-10-02 17:27:57 -07002187 // This is a new alarm delivery set; bump the sequence number to indicate that
2188 // all apps' alarm delivery classes should be recalculated.
2189 mCurrentSeq++;
2190 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002191 Collections.sort(triggerList, mAlarmDispatchComparator);
2192
2193 if (localLOGV) {
2194 for (int i=0; i<triggerList.size(); i++) {
2195 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
2196 }
2197 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002198
2199 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002200 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002202 /**
2203 * This Comparator sorts Alarms into increasing time order.
2204 */
2205 public static class IncreasingTimeOrder implements Comparator<Alarm> {
2206 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09002207 long when1 = a1.whenElapsed;
2208 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002209 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002210 return 1;
2211 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002212 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002213 return -1;
2214 }
2215 return 0;
2216 }
2217 }
2218
2219 private static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002220 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002221 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002222 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002223 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002224 public final IAlarmListener listener;
2225 public final String listenerTag;
2226 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002227 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002228 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002229 public final AlarmManager.AlarmClockInfo alarmClock;
2230 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002231 public final int creatorUid;
2232 public final String packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002233 public int count;
2234 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07002235 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002236 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002237 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002238 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07002239 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002240
Christopher Tate3e04b472013-10-21 17:51:31 -07002241 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002242 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
2243 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
2244 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002245 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002246 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002247 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
2248 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002249 when = _when;
2250 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07002251 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002252 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002253 repeatInterval = _interval;
2254 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002255 listener = _rec;
2256 listenerTag = _listenerTag;
2257 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07002258 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002259 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002260 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002261 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002262 packageName = _pkgName;
2263
2264 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002265 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002266
Christopher Tate14a7bb02015-10-01 10:24:31 -07002267 public static String makeTag(PendingIntent pi, String tag, int type) {
2268 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
2269 ? "*walarm*:" : "*alarm*:";
2270 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
2271 }
2272
2273 public WakeupEvent makeWakeupEvent(long nowRTC) {
2274 return new WakeupEvent(nowRTC, creatorUid,
2275 (operation != null)
2276 ? operation.getIntent().getAction()
2277 : ("<listener>:" + listenerTag));
2278 }
2279
2280 // Returns true if either matches
2281 public boolean matches(PendingIntent pi, IAlarmListener rec) {
2282 return (operation != null)
2283 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09002284 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07002285 }
2286
2287 public boolean matches(String packageName) {
2288 return (operation != null)
2289 ? packageName.equals(operation.getTargetPackage())
2290 : packageName.equals(this.packageName);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002291 }
2292
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002293 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002294 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002295 StringBuilder sb = new StringBuilder(128);
2296 sb.append("Alarm{");
2297 sb.append(Integer.toHexString(System.identityHashCode(this)));
2298 sb.append(" type ");
2299 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002300 sb.append(" when ");
2301 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002302 sb.append(" ");
Christopher Tate14a7bb02015-10-01 10:24:31 -07002303 if (operation != null) {
2304 sb.append(operation.getTargetPackage());
2305 } else {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002306 sb.append(packageName);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002307 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002308 sb.append('}');
2309 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002310 }
2311
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002312 public void dump(PrintWriter pw, String prefix, long nowRTC, long nowELAPSED,
2313 SimpleDateFormat sdf) {
2314 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002315 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002316 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002317 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
2318 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002319 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002320 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002321 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002322 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002323 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002324 }
2325 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002326 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002327 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002328 pw.print(" count="); pw.print(count);
2329 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002330 if (alarmClock != null) {
2331 pw.print(prefix); pw.println("Alarm clock:");
2332 pw.print(prefix); pw.print(" triggerTime=");
2333 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
2334 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
2335 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002336 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002337 if (listener != null) {
2338 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
2339 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002340 }
2341 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002342
Christopher Tatee0a22b32013-07-11 14:43:13 -07002343 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
2344 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002345 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
2346 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002347 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07002348 break;
2349 }
2350
Christopher Tatee0a22b32013-07-11 14:43:13 -07002351 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002352 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
2353 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002354 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07002355 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002356 }
2357 }
2358
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002359 long currentNonWakeupFuzzLocked(long nowELAPSED) {
2360 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
2361 if (timeSinceOn < 5*60*1000) {
2362 // If the screen has been off for 5 minutes, only delay by at most two minutes.
2363 return 2*60*1000;
2364 } else if (timeSinceOn < 30*60*1000) {
2365 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
2366 return 15*60*1000;
2367 } else {
2368 // Otherwise, we will delay by at most an hour.
2369 return 60*60*1000;
2370 }
2371 }
2372
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002373 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002374 if (duration < 15*60*1000) {
2375 // If the duration until the time is less than 15 minutes, the maximum fuzz
2376 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002377 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002378 } else if (duration < 90*60*1000) {
2379 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
2380 return 15*60*1000;
2381 } else {
2382 // Otherwise, we will fuzz by at most half an hour.
2383 return 30*60*1000;
2384 }
2385 }
2386
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002387 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
2388 if (mInteractive) {
2389 return false;
2390 }
2391 if (mLastAlarmDeliveryTime <= 0) {
2392 return false;
2393 }
minho.choo649acab2014-12-12 16:13:55 +09002394 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002395 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
2396 // and the next delivery time is in the past, then just deliver them all. This
2397 // avoids bugs where we get stuck in a loop trying to poll for alarms.
2398 return false;
2399 }
2400 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
2401 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
2402 }
2403
2404 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
2405 mLastAlarmDeliveryTime = nowELAPSED;
2406 for (int i=0; i<triggerList.size(); i++) {
2407 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07002408 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002409 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07002410 if (localLOGV) {
2411 Slog.v(TAG, "sending alarm " + alarm);
2412 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07002413 if (RECORD_ALARMS_IN_HISTORY) {
2414 if (alarm.workSource != null && alarm.workSource.size() > 0) {
2415 for (int wi=0; wi<alarm.workSource.size(); wi++) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002416 ActivityManager.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002417 alarm.operation, alarm.workSource.get(wi), alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002418 }
2419 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002420 ActivityManager.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002421 alarm.operation, alarm.uid, alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002422 }
2423 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002424 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002425 } catch (RuntimeException e) {
2426 Slog.w(TAG, "Failure sending alarm.", e);
2427 }
2428 }
2429 }
2430
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002431 private class AlarmThread extends Thread
2432 {
2433 public AlarmThread()
2434 {
2435 super("AlarmManager");
2436 }
2437
2438 public void run()
2439 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002440 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002442 while (true)
2443 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002444 int result = waitForAlarm(mNativeData);
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002445 mLastWakeup = SystemClock.elapsedRealtime();
Dianne Hackborn390517b2013-05-30 15:03:32 -07002446
2447 triggerList.clear();
2448
Dianne Hackbornc3527222015-05-13 14:03:20 -07002449 final long nowRTC = System.currentTimeMillis();
2450 final long nowELAPSED = SystemClock.elapsedRealtime();
2451
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002452 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002453 // The kernel can give us spurious time change notifications due to
2454 // small adjustments it makes internally; we want to filter those out.
2455 final long lastTimeChangeClockTime;
2456 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07002457 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002458 lastTimeChangeClockTime = mLastTimeChangeClockTime;
2459 expectedClockTime = lastTimeChangeClockTime
2460 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07002461 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002462 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-500)
2463 || nowRTC > (expectedClockTime+500)) {
2464 // The change is by at least +/- 500 ms (or this is the first change),
2465 // let's do it!
2466 if (DEBUG_BATCH) {
2467 Slog.v(TAG, "Time changed notification from kernel; rebatching");
2468 }
2469 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07002470 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07002471 rebatchAllAlarms();
2472 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07002473 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07002474 synchronized (mLock) {
2475 mNumTimeChanged++;
2476 mLastTimeChangeClockTime = nowRTC;
2477 mLastTimeChangeRealtime = nowELAPSED;
2478 }
2479 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
2480 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
2481 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2482 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
2483
2484 // The world has changed on us, so we need to re-evaluate alarms
2485 // regardless of whether the kernel has told us one went off.
2486 result |= IS_WAKEUP_MASK;
2487 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002489
Dianne Hackbornc3527222015-05-13 14:03:20 -07002490 if (result != TIME_CHANGED_MASK) {
2491 // If this was anything besides just a time change, then figure what if
2492 // anything to do about alarms.
2493 synchronized (mLock) {
2494 if (localLOGV) Slog.v(
2495 TAG, "Checking for alarms... rtc=" + nowRTC
2496 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07002497
Dianne Hackbornc3527222015-05-13 14:03:20 -07002498 if (WAKEUP_STATS) {
2499 if ((result & IS_WAKEUP_MASK) != 0) {
2500 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
2501 int n = 0;
2502 for (WakeupEvent event : mRecentWakeups) {
2503 if (event.when > newEarliest) break;
2504 n++; // number of now-stale entries at the list head
2505 }
2506 for (int i = 0; i < n; i++) {
2507 mRecentWakeups.remove();
2508 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002509
Dianne Hackbornc3527222015-05-13 14:03:20 -07002510 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002511 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002512 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002513
2514 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2515 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
2516 // if there are no wakeup alarms and the screen is off, we can
2517 // delay what we have so far until the future.
2518 if (mPendingNonWakeupAlarms.size() == 0) {
2519 mStartCurrentDelayTime = nowELAPSED;
2520 mNextNonWakeupDeliveryTime = nowELAPSED
2521 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
2522 }
2523 mPendingNonWakeupAlarms.addAll(triggerList);
2524 mNumDelayedAlarms += triggerList.size();
2525 rescheduleKernelAlarmsLocked();
2526 updateNextAlarmClockLocked();
2527 } else {
2528 // now deliver the alarm intents; if there are pending non-wakeup
2529 // alarms, we need to merge them in to the list. note we don't
2530 // just deliver them first because we generally want non-wakeup
2531 // alarms delivered after wakeup alarms.
2532 rescheduleKernelAlarmsLocked();
2533 updateNextAlarmClockLocked();
2534 if (mPendingNonWakeupAlarms.size() > 0) {
2535 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
2536 triggerList.addAll(mPendingNonWakeupAlarms);
2537 Collections.sort(triggerList, mAlarmDispatchComparator);
2538 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2539 mTotalDelayTime += thisDelayTime;
2540 if (mMaxDelayTime < thisDelayTime) {
2541 mMaxDelayTime = thisDelayTime;
2542 }
2543 mPendingNonWakeupAlarms.clear();
2544 }
2545 deliverAlarmsLocked(triggerList, nowELAPSED);
2546 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002547 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002548
2549 } else {
2550 // Just in case -- even though no wakeup flag was set, make sure
2551 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07002552 synchronized (mLock) {
2553 rescheduleKernelAlarmsLocked();
2554 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002555 }
2556 }
2557 }
2558 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002559
David Christieebe51fc2013-07-26 13:23:29 -07002560 /**
2561 * Attribute blame for a WakeLock.
2562 * @param pi PendingIntent to attribute blame to if ws is null.
2563 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002564 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07002565 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002566 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002567 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07002568 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002569 final boolean unimportant = pi == mTimeTickSender;
2570 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002571 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002572 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002573 } else {
2574 mWakeLock.setHistoryTag(null);
2575 }
2576 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07002577 if (ws != null) {
2578 mWakeLock.setWorkSource(ws);
2579 return;
2580 }
2581
Christopher Tate14a7bb02015-10-01 10:24:31 -07002582 final int uid = (knownUid >= 0)
2583 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002584 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07002585 if (uid >= 0) {
2586 mWakeLock.setWorkSource(new WorkSource(uid));
2587 return;
2588 }
2589 } catch (Exception e) {
2590 }
2591
2592 // Something went wrong; fall back to attributing the lock to the OS
2593 mWakeLock.setWorkSource(null);
2594 }
2595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002596 private class AlarmHandler extends Handler {
2597 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002598 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
2599 public static final int LISTENER_TIMEOUT = 3;
2600 public static final int REPORT_ALARMS_ACTIVE = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002601
2602 public AlarmHandler() {
2603 }
2604
2605 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002606 switch (msg.what) {
2607 case ALARM_EVENT: {
2608 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2609 synchronized (mLock) {
2610 final long nowRTC = System.currentTimeMillis();
2611 final long nowELAPSED = SystemClock.elapsedRealtime();
2612 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2613 updateNextAlarmClockLocked();
2614 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002615
Christopher Tate14a7bb02015-10-01 10:24:31 -07002616 // now trigger the alarms without the lock held
2617 for (int i=0; i<triggerList.size(); i++) {
2618 Alarm alarm = triggerList.get(i);
2619 try {
2620 alarm.operation.send();
2621 } catch (PendingIntent.CanceledException e) {
2622 if (alarm.repeatInterval > 0) {
2623 // This IntentSender is no longer valid, but this
2624 // is a repeating alarm, so toss the hoser.
2625 removeImpl(alarm.operation);
2626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002627 }
2628 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002629 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002630 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002631
2632 case SEND_NEXT_ALARM_CLOCK_CHANGED:
2633 sendNextAlarmClockChanged();
2634 break;
2635
2636 case LISTENER_TIMEOUT:
2637 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
2638 break;
2639
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002640 case REPORT_ALARMS_ACTIVE:
2641 if (mLocalDeviceIdleController != null) {
2642 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
2643 }
2644 break;
2645
Christopher Tate14a7bb02015-10-01 10:24:31 -07002646 default:
2647 // nope, just ignore it
2648 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002649 }
2650 }
2651 }
2652
2653 class ClockReceiver extends BroadcastReceiver {
2654 public ClockReceiver() {
2655 IntentFilter filter = new IntentFilter();
2656 filter.addAction(Intent.ACTION_TIME_TICK);
2657 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002658 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002659 }
2660
2661 @Override
2662 public void onReceive(Context context, Intent intent) {
2663 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07002664 if (DEBUG_BATCH) {
2665 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
2666 }
2667 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002668 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
2669 // Since the kernel does not keep track of DST, we need to
2670 // reset the TZ information at the beginning of each day
2671 // based off of the current Zone gmt offset + userspace tracked
2672 // daylight savings information.
2673 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02002674 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002675 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07002676 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002677 }
2678 }
2679
2680 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07002681 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09002682 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07002683
2684 // Schedule this event for the amount of time that it would take to get to
2685 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09002686 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07002687
David Christieebe51fc2013-07-26 13:23:29 -07002688 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002689 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002690 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
2691 null, Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002692 }
Christopher Tate385e4982013-07-23 18:22:29 -07002693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694 public void scheduleDateChangedEvent() {
2695 Calendar calendar = Calendar.getInstance();
2696 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07002697 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002698 calendar.set(Calendar.MINUTE, 0);
2699 calendar.set(Calendar.SECOND, 0);
2700 calendar.set(Calendar.MILLISECOND, 0);
2701 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07002702
2703 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002704 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
2705 AlarmManager.FLAG_STANDALONE, workSource, null,
2706 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002707 }
2708 }
2709
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002710 class InteractiveStateReceiver extends BroadcastReceiver {
2711 public InteractiveStateReceiver() {
2712 IntentFilter filter = new IntentFilter();
2713 filter.addAction(Intent.ACTION_SCREEN_OFF);
2714 filter.addAction(Intent.ACTION_SCREEN_ON);
2715 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
2716 getContext().registerReceiver(this, filter);
2717 }
2718
2719 @Override
2720 public void onReceive(Context context, Intent intent) {
2721 synchronized (mLock) {
2722 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
2723 }
2724 }
2725 }
2726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002727 class UninstallReceiver extends BroadcastReceiver {
2728 public UninstallReceiver() {
2729 IntentFilter filter = new IntentFilter();
2730 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2731 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002732 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002733 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08002734 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002735 // Register for events related to sdcard installation.
2736 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08002737 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002738 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002739 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002740 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002741 }
2742
2743 @Override
2744 public void onReceive(Context context, Intent intent) {
2745 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002746 String action = intent.getAction();
2747 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002748 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
2749 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
2750 for (String packageName : pkgList) {
2751 if (lookForPackageLocked(packageName)) {
2752 setResultCode(Activity.RESULT_OK);
2753 return;
2754 }
2755 }
2756 return;
2757 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002758 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002759 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
2760 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
2761 if (userHandle >= 0) {
2762 removeUserLocked(userHandle);
2763 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002764 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
2765 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
2766 if (uid >= 0) {
2767 mLastAllowWhileIdleDispatch.delete(uid);
2768 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002769 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08002770 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
2771 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
2772 // This package is being updated; don't kill its alarms.
2773 return;
2774 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002775 Uri data = intent.getData();
2776 if (data != null) {
2777 String pkg = data.getSchemeSpecificPart();
2778 if (pkg != null) {
2779 pkgList = new String[]{pkg};
2780 }
2781 }
2782 }
2783 if (pkgList != null && (pkgList.length > 0)) {
2784 for (String pkg : pkgList) {
2785 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07002786 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002787 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
2788 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
2789 if (uidStats.remove(pkg) != null) {
2790 if (uidStats.size() <= 0) {
2791 mBroadcastStats.removeAt(i);
2792 }
2793 }
2794 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002795 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796 }
2797 }
2798 }
2799 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002800
2801 final class UidObserver extends IUidObserver.Stub {
2802 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
2803 }
2804
Dianne Hackborne07641d2016-11-09 15:07:23 -08002805 @Override public void onUidGone(int uid, boolean disabled) throws RemoteException {
2806 if (disabled) {
2807 synchronized (mLock) {
2808 removeForStoppedLocked(uid);
2809 }
2810 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002811 }
2812
2813 @Override public void onUidActive(int uid) throws RemoteException {
2814 }
2815
Dianne Hackborne07641d2016-11-09 15:07:23 -08002816 @Override public void onUidIdle(int uid, boolean disabled) throws RemoteException {
2817 if (disabled) {
2818 synchronized (mLock) {
2819 removeForStoppedLocked(uid);
2820 }
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08002821 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002822 }
2823 };
2824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002826 String pkg = pi.getCreatorPackage();
2827 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002828 return getStatsLocked(uid, pkg);
2829 }
2830
2831 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002832 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
2833 if (uidStats == null) {
2834 uidStats = new ArrayMap<String, BroadcastStats>();
2835 mBroadcastStats.put(uid, uidStats);
2836 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002837 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002838 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002839 bs = new BroadcastStats(uid, pkgName);
2840 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841 }
2842 return bs;
2843 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002844
Christopher Tate14a7bb02015-10-01 10:24:31 -07002845 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
2846 private InFlight removeLocked(PendingIntent pi, Intent intent) {
2847 for (int i = 0; i < mInFlight.size(); i++) {
2848 if (mInFlight.get(i).mPendingIntent == pi) {
2849 return mInFlight.remove(i);
2850 }
2851 }
2852 mLog.w("No in-flight alarm for " + pi + " " + intent);
2853 return null;
2854 }
2855
2856 private InFlight removeLocked(IBinder listener) {
2857 for (int i = 0; i < mInFlight.size(); i++) {
2858 if (mInFlight.get(i).mListener == listener) {
2859 return mInFlight.remove(i);
2860 }
2861 }
2862 mLog.w("No in-flight alarm for listener " + listener);
2863 return null;
2864 }
2865
2866 private void updateStatsLocked(InFlight inflight) {
2867 final long nowELAPSED = SystemClock.elapsedRealtime();
2868 BroadcastStats bs = inflight.mBroadcastStats;
2869 bs.nesting--;
2870 if (bs.nesting <= 0) {
2871 bs.nesting = 0;
2872 bs.aggregateTime += nowELAPSED - bs.startTime;
2873 }
2874 FilterStats fs = inflight.mFilterStats;
2875 fs.nesting--;
2876 if (fs.nesting <= 0) {
2877 fs.nesting = 0;
2878 fs.aggregateTime += nowELAPSED - fs.startTime;
2879 }
2880 if (RECORD_ALARMS_IN_HISTORY) {
2881 if (inflight.mWorkSource != null && inflight.mWorkSource.size() > 0) {
2882 for (int wi=0; wi<inflight.mWorkSource.size(); wi++) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002883 ActivityManager.noteAlarmFinish(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002884 inflight.mPendingIntent, inflight.mWorkSource.get(wi), inflight.mTag);
2885 }
2886 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002887 ActivityManager.noteAlarmFinish(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002888 inflight.mPendingIntent, inflight.mUid, inflight.mTag);
2889 }
2890 }
2891 }
2892
2893 private void updateTrackingLocked(InFlight inflight) {
2894 if (inflight != null) {
2895 updateStatsLocked(inflight);
2896 }
2897 mBroadcastRefCount--;
2898 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002899 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002900 mWakeLock.release();
2901 if (mInFlight.size() > 0) {
2902 mLog.w("Finished all dispatches with " + mInFlight.size()
2903 + " remaining inflights");
2904 for (int i=0; i<mInFlight.size(); i++) {
2905 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
2906 }
2907 mInFlight.clear();
2908 }
2909 } else {
2910 // the next of our alarms is now in flight. reattribute the wakelock.
2911 if (mInFlight.size() > 0) {
2912 InFlight inFlight = mInFlight.get(0);
2913 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
2914 inFlight.mAlarmType, inFlight.mTag, -1, false);
2915 } else {
2916 // should never happen
2917 mLog.w("Alarm wakelock still held but sent queue empty");
2918 mWakeLock.setWorkSource(null);
2919 }
2920 }
2921 }
2922
2923 /**
2924 * Callback that arrives when a direct-call alarm reports that delivery has finished
2925 */
2926 @Override
2927 public void alarmComplete(IBinder who) {
2928 if (who == null) {
2929 Slog.w(TAG, "Invalid alarmComplete: uid=" + Binder.getCallingUid()
2930 + " pid=" + Binder.getCallingPid());
2931 return;
2932 }
2933
2934 final long ident = Binder.clearCallingIdentity();
2935 try {
2936 synchronized (mLock) {
2937 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
2938 InFlight inflight = removeLocked(who);
2939 if (inflight != null) {
2940 if (DEBUG_LISTENER_CALLBACK) {
2941 Slog.i(TAG, "alarmComplete() from " + who);
2942 }
2943 updateTrackingLocked(inflight);
2944 } else {
2945 // Delivery timed out, and the timeout handling already took care of
2946 // updating our tracking here, so we needn't do anything further.
2947 if (DEBUG_LISTENER_CALLBACK) {
2948 Slog.i(TAG, "Late alarmComplete() from " + who);
2949 }
2950 }
2951 }
2952 } finally {
2953 Binder.restoreCallingIdentity(ident);
2954 }
2955 }
2956
2957 /**
2958 * Callback that arrives when a PendingIntent alarm has finished delivery
2959 */
2960 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002961 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
2962 String resultData, Bundle resultExtras) {
2963 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002964 updateTrackingLocked(removeLocked(pi, intent));
2965 }
2966 }
2967
2968 /**
2969 * Timeout of a direct-call alarm delivery
2970 */
2971 public void alarmTimedOut(IBinder who) {
2972 synchronized (mLock) {
2973 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08002974 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002975 // TODO: implement ANR policy for the target
2976 if (DEBUG_LISTENER_CALLBACK) {
2977 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002978 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002979 updateTrackingLocked(inflight);
Dianne Hackborn81038902012-11-26 17:04:09 -08002980 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002981 if (DEBUG_LISTENER_CALLBACK) {
2982 Slog.i(TAG, "Spurious timeout of listener " + who);
2983 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002984 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002985 }
2986 }
2987
2988 /**
2989 * Deliver an alarm and set up the post-delivery handling appropriately
2990 */
2991 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
2992 if (alarm.operation != null) {
2993 // PendingIntent alarm
2994 try {
2995 alarm.operation.send(getContext(), 0,
2996 mBackgroundIntent.putExtra(
2997 Intent.EXTRA_ALARM_COUNT, alarm.count),
2998 mDeliveryTracker, mHandler, null,
2999 allowWhileIdle ? mIdleOptions : null);
3000 } catch (PendingIntent.CanceledException e) {
3001 if (alarm.repeatInterval > 0) {
3002 // This IntentSender is no longer valid, but this
3003 // is a repeating alarm, so toss it
3004 removeImpl(alarm.operation);
3005 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003006 // No actual delivery was possible, so the delivery tracker's
3007 // 'finished' callback won't be invoked. We also don't need
3008 // to do any wakelock or stats tracking, so we have nothing
3009 // left to do here but go on to the next thing.
3010 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003011 }
3012 } else {
3013 // Direct listener callback alarm
3014 try {
3015 if (DEBUG_LISTENER_CALLBACK) {
3016 Slog.v(TAG, "Alarm to uid=" + alarm.uid
3017 + " listener=" + alarm.listener.asBinder());
3018 }
3019 alarm.listener.doAlarm(this);
3020 mHandler.sendMessageDelayed(
3021 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
3022 alarm.listener.asBinder()),
3023 mConstants.LISTENER_TIMEOUT);
3024 } catch (Exception e) {
3025 if (DEBUG_LISTENER_CALLBACK) {
3026 Slog.i(TAG, "Alarm undeliverable to listener "
3027 + alarm.listener.asBinder(), e);
3028 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003029 // As in the PendingIntent.CanceledException case, delivery of the
3030 // alarm was not possible, so we have no wakelock or timeout or
3031 // stats management to do. It threw before we posted the delayed
3032 // timeout message, so we're done here.
3033 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003034 }
3035 }
3036
3037 // The alarm is now in flight; now arrange wakelock and stats tracking
3038 if (mBroadcastRefCount == 0) {
3039 setWakelockWorkSource(alarm.operation, alarm.workSource,
3040 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
3041 true);
3042 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003043 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003044 }
3045 final InFlight inflight = new InFlight(AlarmManagerService.this,
3046 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
3047 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
3048 mInFlight.add(inflight);
3049 mBroadcastRefCount++;
3050
3051 if (allowWhileIdle) {
3052 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
3053 mLastAllowWhileIdleDispatch.put(alarm.uid, nowELAPSED);
3054 if (RECORD_DEVICE_IDLE_ALARMS) {
3055 IdleDispatchEntry ent = new IdleDispatchEntry();
3056 ent.uid = alarm.uid;
3057 ent.pkg = alarm.packageName;
3058 ent.tag = alarm.statsTag;
3059 ent.op = "DELIVER";
3060 ent.elapsedRealtime = nowELAPSED;
3061 mAllowWhileIdleDispatches.add(ent);
3062 }
3063 }
3064
3065 final BroadcastStats bs = inflight.mBroadcastStats;
3066 bs.count++;
3067 if (bs.nesting == 0) {
3068 bs.nesting = 1;
3069 bs.startTime = nowELAPSED;
3070 } else {
3071 bs.nesting++;
3072 }
3073 final FilterStats fs = inflight.mFilterStats;
3074 fs.count++;
3075 if (fs.nesting == 0) {
3076 fs.nesting = 1;
3077 fs.startTime = nowELAPSED;
3078 } else {
3079 fs.nesting++;
3080 }
3081 if (alarm.type == ELAPSED_REALTIME_WAKEUP
3082 || alarm.type == RTC_WAKEUP) {
3083 bs.numWakeup++;
3084 fs.numWakeup++;
3085 if (alarm.workSource != null && alarm.workSource.size() > 0) {
3086 for (int wi=0; wi<alarm.workSource.size(); wi++) {
Christopher Tate0029f572016-06-14 10:16:28 -07003087 final String wsName = alarm.workSource.getName(wi);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003088 ActivityManager.noteWakeupAlarm(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003089 alarm.operation, alarm.workSource.get(wi),
Christopher Tate0029f572016-06-14 10:16:28 -07003090 (wsName != null) ? wsName : alarm.packageName,
3091 alarm.statsTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08003092 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003093 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003094 ActivityManager.noteWakeupAlarm(
Joe Onorato78bcdf92016-05-09 10:10:29 -07003095 alarm.operation, alarm.uid, alarm.packageName, alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003096 }
3097 }
3098 }
3099 }
3100}