blob: 4dd88b20fb7f1e9a036ed9f56965143d4ae13c0f [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import android.app.ActivityManagerNative;
Christopher Tate57ceaaa2013-07-19 16:30:43 -070022import android.app.AlarmManager;
Christopher Tate14a7bb02015-10-01 10:24:31 -070023import android.app.AppOpsManager;
Dianne Hackborna750a632015-06-16 17:18:23 -070024import android.app.BroadcastOptions;
Christopher Tate14a7bb02015-10-01 10:24:31 -070025import android.app.IAlarmCompleteListener;
26import android.app.IAlarmListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.app.IAlarmManager;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070028import android.app.IUidObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.app.PendingIntent;
30import android.content.BroadcastReceiver;
Dianne Hackborna750a632015-06-16 17:18:23 -070031import android.content.ContentResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.content.Context;
33import android.content.Intent;
34import android.content.IntentFilter;
35import android.content.pm.PackageManager;
Dianne Hackborna750a632015-06-16 17:18:23 -070036import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.net.Uri;
38import android.os.Binder;
39import android.os.Bundle;
40import android.os.Handler;
Adam Lesinski182f73f2013-12-05 16:48:06 -080041import android.os.IBinder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.os.Message;
43import android.os.PowerManager;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070044import android.os.Process;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070045import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.os.SystemClock;
47import android.os.SystemProperties;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070048import android.os.UserHandle;
Christopher Tatec4a07d12012-04-06 14:19:13 -070049import android.os.WorkSource;
Adrian Roosc42a1e12014-07-07 23:35:53 +020050import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.text.TextUtils;
Adrian Roosc42a1e12014-07-07 23:35:53 +020052import android.text.format.DateFormat;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080053import android.util.ArrayMap;
Dianne Hackborna750a632015-06-16 17:18:23 -070054import android.util.KeyValueListParser;
Adrian Roosc42a1e12014-07-07 23:35:53 +020055import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080056import android.util.Slog;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080057import android.util.SparseArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +020058import android.util.SparseBooleanArray;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -070059import android.util.SparseLongArray;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070060import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061
Christopher Tate4cb338d2013-07-26 13:11:31 -070062import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import java.io.FileDescriptor;
64import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070065import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -080067import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import java.util.Calendar;
69import java.util.Collections;
70import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -050071import java.util.Date;
Christopher Tate1590f1e2014-10-02 17:27:57 -070072import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -070073import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +020074import java.util.Locale;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070075import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import java.util.TimeZone;
John Spurlock604a5ee2015-06-01 12:27:22 -040077import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078
Christopher Tatee0a22b32013-07-11 14:43:13 -070079import static android.app.AlarmManager.RTC_WAKEUP;
80import static android.app.AlarmManager.RTC;
81import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
82import static android.app.AlarmManager.ELAPSED_REALTIME;
83
Dianne Hackborn81038902012-11-26 17:04:09 -080084import com.android.internal.util.LocalLog;
85
Adam Lesinski182f73f2013-12-05 16:48:06 -080086class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -070087 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
88 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -080089 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -070090 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -080091 static final int TIME_CHANGED_MASK = 1 << 16;
92 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -080093
Christopher Tatee0a22b32013-07-11 14:43:13 -070094 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -080095 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -080096
Adam Lesinski182f73f2013-12-05 16:48:06 -080097 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -080098 static final boolean localLOGV = false;
99 static final boolean DEBUG_BATCH = localLOGV || false;
100 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200101 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700102 static final boolean DEBUG_LISTENER_CALLBACK = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700103 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700104 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800105 static final int ALARM_EVENT = 1;
106 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200107
Christopher Tate14a7bb02015-10-01 10:24:31 -0700108 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800110 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111
Adam Lesinski182f73f2013-12-05 16:48:06 -0800112 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700113
Christopher Tate24cd46f2016-02-02 14:28:01 -0800114 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT =
115 new Intent(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED)
116 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Adrian Roosc42a1e12014-07-07 23:35:53 +0200117
Adam Lesinski182f73f2013-12-05 16:48:06 -0800118 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800119
Christopher Tate14a7bb02015-10-01 10:24:31 -0700120 AppOpsManager mAppOps;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800121 DeviceIdleController.LocalService mLocalDeviceIdleController;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700122
Adam Lesinski182f73f2013-12-05 16:48:06 -0800123 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800124
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800125 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800126 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700127 private long mNextNonWakeup;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -0700128 private long mLastWakeupSet;
129 private long mLastWakeup;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800130 int mBroadcastRefCount = 0;
131 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700132 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700133 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
134 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800135 final AlarmHandler mHandler = new AlarmHandler();
136 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700137 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700139 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800140 PendingIntent mTimeTickSender;
141 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700142 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700143 boolean mInteractive = true;
144 long mNonInteractiveStartTime;
145 long mNonInteractiveTime;
146 long mLastAlarmDeliveryTime;
147 long mStartCurrentDelayTime;
148 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700149 long mLastTimeChangeClockTime;
150 long mLastTimeChangeRealtime;
Dianne Hackborna750a632015-06-16 17:18:23 -0700151 long mAllowWhileIdleMinTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700152 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800153
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700154 /**
Dianne Hackborn262ae5c2016-02-10 16:28:29 -0800155 * The current set of user whitelisted apps for device idle mode, meaning these are allowed
156 * to freely schedule alarms.
157 */
158 int[] mDeviceIdleUserWhitelist = new int[0];
159
160 /**
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700161 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
162 * used to determine the earliest we can dispatch the next such alarm.
163 */
164 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
165
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700166 final static class IdleDispatchEntry {
167 int uid;
168 String pkg;
169 String tag;
170 String op;
171 long elapsedRealtime;
172 long argRealtime;
173 }
174 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
175
Dianne Hackborna750a632015-06-16 17:18:23 -0700176 /**
177 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
178 */
179 Bundle mIdleOptions;
180
Jose Lima235510e2014-08-13 12:50:01 -0700181 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
182 new SparseArray<>();
183 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
184 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200185 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
186 new SparseBooleanArray();
187 private boolean mNextAlarmClockMayChange;
188
189 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700190 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
191 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200192
Dianne Hackborna750a632015-06-16 17:18:23 -0700193 /**
194 * All times are in milliseconds. These constants are kept synchronized with the system
195 * global Settings. Any access to this class or its fields should be done while
196 * holding the AlarmManagerService.mLock lock.
197 */
198 private final class Constants extends ContentObserver {
199 // Key names stored in the settings value.
200 private static final String KEY_MIN_FUTURITY = "min_futurity";
201 private static final String KEY_MIN_INTERVAL = "min_interval";
202 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
203 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
204 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
205 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700206 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Dianne Hackborna750a632015-06-16 17:18:23 -0700207
208 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
209 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tateaa244da2015-08-27 15:57:57 -0700210 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700211 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700212 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
213
Christopher Tate14a7bb02015-10-01 10:24:31 -0700214 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
215
Dianne Hackborna750a632015-06-16 17:18:23 -0700216 // Minimum futurity of a new alarm
217 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
218
219 // Minimum alarm recurrence interval
220 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
221
222 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
223 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
224
225 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
226 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
227
228 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
229 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
230 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
231
Christopher Tate14a7bb02015-10-01 10:24:31 -0700232 // Direct alarm listener callback timeout
233 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
234
Dianne Hackborna750a632015-06-16 17:18:23 -0700235 private ContentResolver mResolver;
236 private final KeyValueListParser mParser = new KeyValueListParser(',');
237 private long mLastAllowWhileIdleWhitelistDuration = -1;
238
239 public Constants(Handler handler) {
240 super(handler);
241 updateAllowWhileIdleMinTimeLocked();
242 updateAllowWhileIdleWhitelistDurationLocked();
243 }
244
245 public void start(ContentResolver resolver) {
246 mResolver = resolver;
247 mResolver.registerContentObserver(Settings.Global.getUriFor(
248 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
249 updateConstants();
250 }
251
252 public void updateAllowWhileIdleMinTimeLocked() {
253 mAllowWhileIdleMinTime = mPendingIdleUntil != null
254 ? ALLOW_WHILE_IDLE_LONG_TIME : ALLOW_WHILE_IDLE_SHORT_TIME;
255 }
256
257 public void updateAllowWhileIdleWhitelistDurationLocked() {
258 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
259 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
260 BroadcastOptions opts = BroadcastOptions.makeBasic();
261 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
262 mIdleOptions = opts.toBundle();
263 }
264 }
265
266 @Override
267 public void onChange(boolean selfChange, Uri uri) {
268 updateConstants();
269 }
270
271 private void updateConstants() {
272 synchronized (mLock) {
273 try {
274 mParser.setString(Settings.Global.getString(mResolver,
275 Settings.Global.ALARM_MANAGER_CONSTANTS));
276 } catch (IllegalArgumentException e) {
277 // Failed to parse the settings string, log this and move on
278 // with defaults.
279 Slog.e(TAG, "Bad device idle settings", e);
280 }
281
282 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
283 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
284 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
285 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
286 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
287 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
288 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
289 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
290 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700291 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
292 DEFAULT_LISTENER_TIMEOUT);
Dianne Hackborna750a632015-06-16 17:18:23 -0700293
294 updateAllowWhileIdleMinTimeLocked();
295 updateAllowWhileIdleWhitelistDurationLocked();
296 }
297 }
298
299 void dump(PrintWriter pw) {
300 pw.println(" Settings:");
301
302 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
303 TimeUtils.formatDuration(MIN_FUTURITY, pw);
304 pw.println();
305
306 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
307 TimeUtils.formatDuration(MIN_INTERVAL, pw);
308 pw.println();
309
Christopher Tate14a7bb02015-10-01 10:24:31 -0700310 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
311 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
312 pw.println();
313
Dianne Hackborna750a632015-06-16 17:18:23 -0700314 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
315 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
316 pw.println();
317
318 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
319 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
320 pw.println();
321
322 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
323 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
324 pw.println();
325 }
326 }
327
328 final Constants mConstants;
329
Christopher Tate1590f1e2014-10-02 17:27:57 -0700330 // Alarm delivery ordering bookkeeping
331 static final int PRIO_TICK = 0;
332 static final int PRIO_WAKEUP = 1;
333 static final int PRIO_NORMAL = 2;
334
Dianne Hackborna750a632015-06-16 17:18:23 -0700335 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700336 int seq;
337 int priority;
338
339 PriorityClass() {
340 seq = mCurrentSeq - 1;
341 priority = PRIO_NORMAL;
342 }
343 }
344
Dianne Hackborna750a632015-06-16 17:18:23 -0700345 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700346 int mCurrentSeq = 0;
347
Dianne Hackborna750a632015-06-16 17:18:23 -0700348 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700349 public long when;
350 public int uid;
351 public String action;
352
353 public WakeupEvent(long theTime, int theUid, String theAction) {
354 when = theTime;
355 uid = theUid;
356 action = theAction;
357 }
358 }
359
Adam Lesinski182f73f2013-12-05 16:48:06 -0800360 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
361 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700362
Adrian Roosc42a1e12014-07-07 23:35:53 +0200363 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700364 long start; // These endpoints are always in ELAPSED
365 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700366 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700367
368 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
369
370 Batch() {
371 start = 0;
372 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700373 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700374 }
375
376 Batch(Alarm seed) {
377 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700378 end = seed.maxWhenElapsed;
379 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700380 alarms.add(seed);
381 }
382
383 int size() {
384 return alarms.size();
385 }
386
387 Alarm get(int index) {
388 return alarms.get(index);
389 }
390
391 boolean canHold(long whenElapsed, long maxWhen) {
392 return (end >= whenElapsed) && (start <= maxWhen);
393 }
394
395 boolean add(Alarm alarm) {
396 boolean newStart = false;
397 // narrows the batch if necessary; presumes that canHold(alarm) is true
398 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
399 if (index < 0) {
400 index = 0 - index - 1;
401 }
402 alarms.add(index, alarm);
403 if (DEBUG_BATCH) {
404 Slog.v(TAG, "Adding " + alarm + " to " + this);
405 }
406 if (alarm.whenElapsed > start) {
407 start = alarm.whenElapsed;
408 newStart = true;
409 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700410 if (alarm.maxWhenElapsed < end) {
411 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700412 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700413 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700414
415 if (DEBUG_BATCH) {
416 Slog.v(TAG, " => now " + this);
417 }
418 return newStart;
419 }
420
Christopher Tate14a7bb02015-10-01 10:24:31 -0700421 boolean remove(final PendingIntent operation, final IAlarmListener listener) {
422 if (operation == null && listener == null) {
423 if (localLOGV) {
424 Slog.w(TAG, "requested remove() of null operation",
425 new RuntimeException("here"));
426 }
427 return false;
428 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700429 boolean didRemove = false;
430 long newStart = 0; // recalculate endpoints as we go
431 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700432 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700433 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700434 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700435 if (alarm.matches(operation, listener)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700436 alarms.remove(i);
437 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200438 if (alarm.alarmClock != null) {
439 mNextAlarmClockMayChange = true;
440 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700441 } else {
442 if (alarm.whenElapsed > newStart) {
443 newStart = alarm.whenElapsed;
444 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700445 if (alarm.maxWhenElapsed < newEnd) {
446 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700447 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700448 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700449 i++;
450 }
451 }
452 if (didRemove) {
453 // commit the new batch bounds
454 start = newStart;
455 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700456 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700457 }
458 return didRemove;
459 }
460
461 boolean remove(final String packageName) {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700462 if (packageName == null) {
463 if (localLOGV) {
464 Slog.w(TAG, "requested remove() of null packageName",
465 new RuntimeException("here"));
466 }
467 return false;
468 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700469 boolean didRemove = false;
470 long newStart = 0; // recalculate endpoints as we go
471 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700472 int newFlags = 0;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700473 for (int i = alarms.size()-1; i >= 0; i--) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700474 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700475 if (alarm.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700476 alarms.remove(i);
477 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200478 if (alarm.alarmClock != null) {
479 mNextAlarmClockMayChange = true;
480 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700481 } else {
482 if (alarm.whenElapsed > newStart) {
483 newStart = alarm.whenElapsed;
484 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700485 if (alarm.maxWhenElapsed < newEnd) {
486 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700487 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700488 newFlags |= alarm.flags;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700489 }
490 }
491 if (didRemove) {
492 // commit the new batch bounds
493 start = newStart;
494 end = newEnd;
495 flags = newFlags;
496 }
497 return didRemove;
498 }
499
500 boolean removeForStopped(final int uid) {
501 boolean didRemove = false;
502 long newStart = 0; // recalculate endpoints as we go
503 long newEnd = Long.MAX_VALUE;
504 int newFlags = 0;
505 for (int i = alarms.size()-1; i >= 0; i--) {
506 Alarm alarm = alarms.get(i);
507 try {
508 if (alarm.uid == uid && ActivityManagerNative.getDefault().getAppStartMode(
509 uid, alarm.packageName) == ActivityManager.APP_START_MODE_DISABLED) {
510 alarms.remove(i);
511 didRemove = true;
512 if (alarm.alarmClock != null) {
513 mNextAlarmClockMayChange = true;
514 }
515 } else {
516 if (alarm.whenElapsed > newStart) {
517 newStart = alarm.whenElapsed;
518 }
519 if (alarm.maxWhenElapsed < newEnd) {
520 newEnd = alarm.maxWhenElapsed;
521 }
522 newFlags |= alarm.flags;
523 }
524 } catch (RemoteException e) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700525 }
526 }
527 if (didRemove) {
528 // commit the new batch bounds
529 start = newStart;
530 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700531 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700532 }
533 return didRemove;
534 }
535
536 boolean remove(final int userHandle) {
537 boolean didRemove = false;
538 long newStart = 0; // recalculate endpoints as we go
539 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700540 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700541 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700542 if (UserHandle.getUserId(alarm.creatorUid) == userHandle) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700543 alarms.remove(i);
544 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200545 if (alarm.alarmClock != null) {
546 mNextAlarmClockMayChange = true;
547 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700548 } else {
549 if (alarm.whenElapsed > newStart) {
550 newStart = alarm.whenElapsed;
551 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700552 if (alarm.maxWhenElapsed < newEnd) {
553 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700554 }
555 i++;
556 }
557 }
558 if (didRemove) {
559 // commit the new batch bounds
560 start = newStart;
561 end = newEnd;
562 }
563 return didRemove;
564 }
565
566 boolean hasPackage(final String packageName) {
567 final int N = alarms.size();
568 for (int i = 0; i < N; i++) {
569 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700570 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700571 return true;
572 }
573 }
574 return false;
575 }
576
577 boolean hasWakeups() {
578 final int N = alarms.size();
579 for (int i = 0; i < N; i++) {
580 Alarm a = alarms.get(i);
581 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
582 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
583 return true;
584 }
585 }
586 return false;
587 }
588
589 @Override
590 public String toString() {
591 StringBuilder b = new StringBuilder(40);
592 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
593 b.append(" num="); b.append(size());
594 b.append(" start="); b.append(start);
595 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700596 if (flags != 0) {
597 b.append(" flgs=0x");
598 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700599 }
600 b.append('}');
601 return b.toString();
602 }
603 }
604
605 static class BatchTimeOrder implements Comparator<Batch> {
606 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800607 long when1 = b1.start;
608 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800609 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700610 return 1;
611 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800612 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700613 return -1;
614 }
615 return 0;
616 }
617 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800618
619 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
620 @Override
621 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700622 // priority class trumps everything. TICK < WAKEUP < NORMAL
623 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
624 return -1;
625 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
626 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800627 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700628
629 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800630 if (lhs.whenElapsed < rhs.whenElapsed) {
631 return -1;
632 } else if (lhs.whenElapsed > rhs.whenElapsed) {
633 return 1;
634 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700635
636 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800637 return 0;
638 }
639 };
640
Christopher Tate1590f1e2014-10-02 17:27:57 -0700641 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
642 final int N = alarms.size();
643 for (int i = 0; i < N; i++) {
644 Alarm a = alarms.get(i);
645
646 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700647 if (a.operation != null
648 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700649 alarmPrio = PRIO_TICK;
650 } else if (a.wakeup) {
651 alarmPrio = PRIO_WAKEUP;
652 } else {
653 alarmPrio = PRIO_NORMAL;
654 }
655
656 PriorityClass packagePrio = a.priorityClass;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700657 String alarmPackage = (a.operation != null)
658 ? a.operation.getCreatorPackage()
659 : a.packageName;
660 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700661 if (packagePrio == null) {
662 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700663 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700664 }
665 a.priorityClass = packagePrio;
666
667 if (packagePrio.seq != mCurrentSeq) {
668 // first alarm we've seen in the current delivery generation from this package
669 packagePrio.priority = alarmPrio;
670 packagePrio.seq = mCurrentSeq;
671 } else {
672 // Multiple alarms from this package being delivered in this generation;
673 // bump the package's delivery class if it's warranted.
674 // TICK < WAKEUP < NORMAL
675 if (alarmPrio < packagePrio.priority) {
676 packagePrio.priority = alarmPrio;
677 }
678 }
679 }
680 }
681
Christopher Tatee0a22b32013-07-11 14:43:13 -0700682 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800683 static final long MIN_FUZZABLE_INTERVAL = 10000;
684 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700685 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
686
687 // set to null if in idle mode; while in this mode, any alarms we don't want
688 // to run during this time are placed in mPendingWhileIdleAlarms
689 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700690 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700691 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700692
Jeff Brownb880d882014-02-10 19:47:07 -0800693 public AlarmManagerService(Context context) {
694 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700695 mConstants = new Constants(mHandler);
Jeff Brownb880d882014-02-10 19:47:07 -0800696 }
697
Christopher Tatee0a22b32013-07-11 14:43:13 -0700698 static long convertToElapsed(long when, int type) {
699 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
700 if (isRtc) {
701 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
702 }
703 return when;
704 }
705
706 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
707 // calculate the end of our nominal delivery window for the alarm.
708 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
709 // Current heuristic: batchable window is 75% of either the recurrence interval
710 // [for a periodic alarm] or of the time from now to the desired delivery time,
711 // with a minimum delay/interval of 10 seconds, under which we will simply not
712 // defer the alarm.
713 long futurity = (interval == 0)
714 ? (triggerAtTime - now)
715 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700716 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700717 futurity = 0;
718 }
719 return triggerAtTime + (long)(.75 * futurity);
720 }
721
722 // returns true if the batch was added at the head
723 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
724 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
725 if (index < 0) {
726 index = 0 - index - 1;
727 }
728 list.add(index, newBatch);
729 return (index == 0);
730 }
731
Christopher Tate385e4982013-07-23 18:22:29 -0700732 // Return the index of the matching batch, or -1 if none found.
733 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700734 final int N = mAlarmBatches.size();
735 for (int i = 0; i < N; i++) {
736 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700737 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700738 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700739 }
740 }
Christopher Tate385e4982013-07-23 18:22:29 -0700741 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700742 }
743
744 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
745 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700746 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700747 rebatchAllAlarmsLocked(true);
748 }
749 }
750
751 void rebatchAllAlarmsLocked(boolean doValidate) {
752 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
753 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700754 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700755 final long nowElapsed = SystemClock.elapsedRealtime();
756 final int oldBatches = oldSet.size();
757 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
758 Batch batch = oldSet.get(batchNum);
759 final int N = batch.size();
760 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700761 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700762 }
763 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700764 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
765 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
766 + " to " + mPendingIdleUntil);
767 if (mPendingIdleUntil == null) {
768 // Somehow we lost this... we need to restore all of the pending alarms.
769 restorePendingWhileIdleAlarmsLocked();
770 }
771 }
772 rescheduleKernelAlarmsLocked();
773 updateNextAlarmClockLocked();
774 }
775
776 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
777 a.when = a.origWhen;
778 long whenElapsed = convertToElapsed(a.when, a.type);
779 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700780 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700781 // Exact
782 maxElapsed = whenElapsed;
783 } else {
784 // Not exact. Preserve any explicit window, otherwise recalculate
785 // the window based on the alarm's new futurity. Note that this
786 // reflects a policy of preferring timely to deferred delivery.
787 maxElapsed = (a.windowLength > 0)
788 ? (whenElapsed + a.windowLength)
789 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
790 }
791 a.whenElapsed = whenElapsed;
792 a.maxWhenElapsed = maxElapsed;
793 setImplLocked(a, true, doValidate);
794 }
795
796 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700797 if (RECORD_DEVICE_IDLE_ALARMS) {
798 IdleDispatchEntry ent = new IdleDispatchEntry();
799 ent.uid = 0;
800 ent.pkg = "FINISH IDLE";
801 ent.elapsedRealtime = SystemClock.elapsedRealtime();
802 mAllowWhileIdleDispatches.add(ent);
803 }
804
Dianne Hackborn35d54032015-04-23 10:30:43 -0700805 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700806 if (mPendingWhileIdleAlarms.size() > 0) {
807 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
808 mPendingWhileIdleAlarms = new ArrayList<>();
809 final long nowElapsed = SystemClock.elapsedRealtime();
810 for (int i=alarms.size() - 1; i >= 0; i--) {
811 Alarm a = alarms.get(i);
812 reAddAlarmLocked(a, nowElapsed, false);
813 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700814 }
Dianne Hackborn35d54032015-04-23 10:30:43 -0700815
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700816 // Make sure we are using the correct ALLOW_WHILE_IDLE min time.
Dianne Hackborna750a632015-06-16 17:18:23 -0700817 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700818
Dianne Hackborn35d54032015-04-23 10:30:43 -0700819 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700820 rescheduleKernelAlarmsLocked();
821 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -0700822
823 // And send a TIME_TICK right now, since it is important to get the UI updated.
824 try {
825 mTimeTickSender.send();
826 } catch (PendingIntent.CanceledException e) {
827 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700828 }
829
Christopher Tate14a7bb02015-10-01 10:24:31 -0700830 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -0800831 final PendingIntent mPendingIntent;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700832 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -0700833 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700834 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700835 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800836 final BroadcastStats mBroadcastStats;
837 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800838 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800839
Christopher Tate14a7bb02015-10-01 10:24:31 -0700840 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
841 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
842 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800843 mPendingIntent = pendingIntent;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700844 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -0700845 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700846 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700847 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700848 mBroadcastStats = (pendingIntent != null)
849 ? service.getStatsLocked(pendingIntent)
850 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700851 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -0800852 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700853 fs = new FilterStats(mBroadcastStats, mTag);
854 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -0800855 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700856 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -0800857 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800858 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800859 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800861
Adam Lesinski182f73f2013-12-05 16:48:06 -0800862 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -0800863 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700864 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800865
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700866 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800868 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 int numWakeup;
870 long startTime;
871 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -0800872
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700873 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800874 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700875 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800876 }
877 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700878
Adam Lesinski182f73f2013-12-05 16:48:06 -0800879 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800880 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800881 final String mPackageName;
882
883 long aggregateTime;
884 int count;
885 int numWakeup;
886 long startTime;
887 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700888 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -0800889
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800890 BroadcastStats(int uid, String packageName) {
891 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800892 mPackageName = packageName;
893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700895
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800896 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
897 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700898
899 int mNumDelayedAlarms = 0;
900 long mTotalDelayTime = 0;
901 long mMaxDelayTime = 0;
902
Adam Lesinski182f73f2013-12-05 16:48:06 -0800903 @Override
904 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800905 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800906 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800907
908 // We have to set current TimeZone info to kernel
909 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -0800910 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800911
Adam Lesinski182f73f2013-12-05 16:48:06 -0800912 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800913 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800914
Adam Lesinski182f73f2013-12-05 16:48:06 -0800915 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700917 Intent.FLAG_RECEIVER_REGISTERED_ONLY
918 | Intent.FLAG_RECEIVER_FOREGROUND), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700919 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800920 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
921 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800922 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700923 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924
925 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -0800926 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 mClockReceiver.scheduleTimeTickEvent();
928 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700929 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 mUninstallReceiver = new UninstallReceiver();
931
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800932 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800933 AlarmThread waitThread = new AlarmThread();
934 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800936 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800938
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700939 try {
940 ActivityManagerNative.getDefault().registerUidObserver(new UidObserver(),
941 ActivityManager.UID_OBSERVER_IDLE);
942 } catch (RemoteException e) {
943 // ignored; both services live in system_server
944 }
945
Adam Lesinski182f73f2013-12-05 16:48:06 -0800946 publishBinderService(Context.ALARM_SERVICE, mService);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -0800947 publishLocalService(LocalService.class, new LocalService());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800949
950 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -0700951 public void onBootPhase(int phase) {
952 if (phase == PHASE_SYSTEM_SERVICES_READY) {
953 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -0700954 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800955 mLocalDeviceIdleController
956 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackborna750a632015-06-16 17:18:23 -0700957 }
958 }
959
960 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800961 protected void finalize() throws Throwable {
962 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800963 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 } finally {
965 super.finalize();
966 }
967 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700968
Adam Lesinski182f73f2013-12-05 16:48:06 -0800969 void setTimeZoneImpl(String tz) {
970 if (TextUtils.isEmpty(tz)) {
971 return;
David Christieebe51fc2013-07-26 13:23:29 -0700972 }
973
Adam Lesinski182f73f2013-12-05 16:48:06 -0800974 TimeZone zone = TimeZone.getTimeZone(tz);
975 // Prevent reentrant calls from stepping on each other when writing
976 // the time zone property
977 boolean timeZoneWasChanged = false;
978 synchronized (this) {
979 String current = SystemProperties.get(TIMEZONE_PROPERTY);
980 if (current == null || !current.equals(zone.getID())) {
981 if (localLOGV) {
982 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
983 }
984 timeZoneWasChanged = true;
985 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
986 }
987
988 // Update the kernel timezone information
989 // Kernel tracks time offsets as 'minutes west of GMT'
990 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800991 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -0800992 }
993
994 TimeZone.setDefault(null);
995
996 if (timeZoneWasChanged) {
997 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
998 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
999 intent.putExtra("time-zone", zone.getID());
1000 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1001 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001003
Adam Lesinski182f73f2013-12-05 16:48:06 -08001004 void removeImpl(PendingIntent operation) {
1005 if (operation == null) {
1006 return;
1007 }
1008 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001009 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001010 }
1011 }
1012
1013 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001014 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1015 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1016 int callingUid, String callingPackage) {
1017 // must be *either* PendingIntent or AlarmReceiver, but not both
1018 if ((operation == null && directReceiver == null)
1019 || (operation != null && directReceiver != null)) {
1020 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1021 // NB: previous releases failed silently here, so we are continuing to do the same
1022 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001023 return;
1024 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001025
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001026 // Sanity check the window length. This will catch people mistakenly
1027 // trying to pass an end-of-window timestamp rather than a duration.
1028 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1029 Slog.w(TAG, "Window length " + windowLength
1030 + "ms suspiciously long; limiting to 1 hour");
1031 windowLength = AlarmManager.INTERVAL_HOUR;
1032 }
1033
Christopher Tate498c6cb2014-11-17 16:09:27 -08001034 // Sanity check the recurrence interval. This will catch people who supply
1035 // seconds when the API expects milliseconds.
Dianne Hackborna750a632015-06-16 17:18:23 -07001036 final long minInterval = mConstants.MIN_INTERVAL;
1037 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001038 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001039 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001040 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001041 interval = minInterval;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001042 }
1043
Christopher Tatee0a22b32013-07-11 14:43:13 -07001044 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1045 throw new IllegalArgumentException("Invalid alarm type " + type);
1046 }
1047
Christopher Tate5f221e82013-07-30 17:13:15 -07001048 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001049 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001050 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001051 + " pid=" + what);
1052 triggerAtTime = 0;
1053 }
1054
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001055 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001056 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1057 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001058 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001059 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1060
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001061 final long maxElapsed;
1062 if (windowLength == AlarmManager.WINDOW_EXACT) {
1063 maxElapsed = triggerElapsed;
1064 } else if (windowLength < 0) {
1065 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001066 // Fix this window in place, so that as time approaches we don't collapse it.
1067 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001068 } else {
1069 maxElapsed = triggerElapsed + windowLength;
1070 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001073 if (DEBUG_BATCH) {
1074 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001075 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001076 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001077 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001079 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001080 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1081 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 }
1083 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084
Christopher Tate3e04b472013-10-21 17:51:31 -07001085 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001086 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1087 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1088 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001089 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001090 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1091 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001092 try {
1093 if (ActivityManagerNative.getDefault().getAppStartMode(callingUid, callingPackage)
1094 == ActivityManager.APP_START_MODE_DISABLED) {
1095 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1096 + " -- package not allowed to start");
1097 return;
1098 }
1099 } catch (RemoteException e) {
1100 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001101 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001102 setImplLocked(a, false, doValidate);
1103 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001104
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001105 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1106 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001107 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001108 // The caller has given the time they want this to happen at, however we need
1109 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001110 // bring us out of idle at an earlier time.
1111 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001112 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001113 }
1114 // Add fuzz to make the alarm go off some time before the actual desired time.
1115 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001116 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001117 if (fuzz > 0) {
1118 if (mRandom == null) {
1119 mRandom = new Random();
1120 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001121 final int delta = mRandom.nextInt(fuzz);
1122 a.whenElapsed -= delta;
1123 if (false) {
1124 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1125 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1126 Slog.d(TAG, "Applied fuzz: " + fuzz);
1127 Slog.d(TAG, "Final delta: " + delta);
1128 Slog.d(TAG, "Final when: " + a.whenElapsed);
1129 }
1130 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001131 }
1132
1133 } else if (mPendingIdleUntil != null) {
1134 // We currently have an idle until alarm scheduled; if the new alarm has
1135 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001136 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1137 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1138 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001139 == 0) {
1140 mPendingWhileIdleAlarms.add(a);
1141 return;
1142 }
1143 }
1144
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001145 if (RECORD_DEVICE_IDLE_ALARMS) {
1146 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1147 IdleDispatchEntry ent = new IdleDispatchEntry();
1148 ent.uid = a.uid;
1149 ent.pkg = a.operation.getCreatorPackage();
1150 ent.tag = a.operation.getTag("");
1151 ent.op = "SET";
1152 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1153 ent.argRealtime = a.whenElapsed;
1154 mAllowWhileIdleDispatches.add(ent);
1155 }
1156 }
1157
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001158 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
1159 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -07001160 if (whichBatch < 0) {
1161 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001162 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 } else {
Christopher Tate385e4982013-07-23 18:22:29 -07001164 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001165 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001166 // The start time of this batch advanced, so batch ordering may
1167 // have just been broken. Move it to where it now belongs.
1168 mAlarmBatches.remove(whichBatch);
1169 addBatchLocked(mAlarmBatches, batch);
1170 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171 }
1172
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001173 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001174 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001175 }
1176
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001177 boolean needRebatch = false;
1178
1179 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001180 if (RECORD_DEVICE_IDLE_ALARMS) {
1181 if (mPendingIdleUntil == null) {
1182 IdleDispatchEntry ent = new IdleDispatchEntry();
1183 ent.uid = 0;
1184 ent.pkg = "START IDLE";
1185 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1186 mAllowWhileIdleDispatches.add(ent);
1187 }
1188 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001189 mPendingIdleUntil = a;
Dianne Hackborna750a632015-06-16 17:18:23 -07001190 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001191 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001192 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1193 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1194 mNextWakeFromIdle = a;
1195 // If this wake from idle is earlier than whatever was previously scheduled,
1196 // and we are currently idling, then we need to rebatch alarms in case the idle
1197 // until time needs to be updated.
1198 if (mPendingIdleUntil != null) {
1199 needRebatch = true;
1200 }
1201 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001202 }
1203
1204 if (!rebatching) {
1205 if (DEBUG_VALIDATE) {
1206 if (doValidate && !validateConsistencyLocked()) {
1207 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1208 + " when(hex)=" + Long.toHexString(a.when)
1209 + " whenElapsed=" + a.whenElapsed
1210 + " maxWhenElapsed=" + a.maxWhenElapsed
1211 + " interval=" + a.repeatInterval + " op=" + a.operation
1212 + " flags=0x" + Integer.toHexString(a.flags));
1213 rebatchAllAlarmsLocked(false);
1214 needRebatch = false;
1215 }
1216 }
1217
1218 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001219 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001220 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001221
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001222 rescheduleKernelAlarmsLocked();
1223 updateNextAlarmClockLocked();
1224 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001225 }
1226
Adam Lesinski182f73f2013-12-05 16:48:06 -08001227 private final IBinder mService = new IAlarmManager.Stub() {
1228 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001229 public void set(String callingPackage,
1230 int type, long triggerAtTime, long windowLength, long interval, int flags,
1231 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1232 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001233 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001234
1235 // make sure the caller is not lying about which package should be blamed for
1236 // wakelock time spent in alarm delivery
1237 mAppOps.checkPackage(callingUid, callingPackage);
1238
1239 // Repeating alarms must use PendingIntent, not direct listener
1240 if (interval != 0) {
1241 if (directReceiver != null) {
1242 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1243 }
1244 }
1245
Adam Lesinski182f73f2013-12-05 16:48:06 -08001246 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001247 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001248 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001249 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001250 }
1251
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001252 // No incoming callers can request either WAKE_FROM_IDLE or
1253 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1254 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1255 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1256
1257 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1258 // manager when to come out of idle mode, which is only for DeviceIdleController.
1259 if (callingUid != Process.SYSTEM_UID) {
1260 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1261 }
1262
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001263 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001264 if (windowLength == AlarmManager.WINDOW_EXACT) {
1265 flags |= AlarmManager.FLAG_STANDALONE;
1266 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001267
1268 // If this alarm is for an alarm clock, then it must be standalone and we will
1269 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001270 if (alarmClock != null) {
1271 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001272
1273 // If the caller is a core system component or on the user's whitelist, and not calling
1274 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1275 // This means we will allow these alarms to go off as normal even while idle, with no
1276 // timing restrictions.
1277 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
1278 || Arrays.binarySearch(mDeviceIdleUserWhitelist,
1279 UserHandle.getAppId(callingUid)) >= 0)) {
1280 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1281 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001282 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001283
Christopher Tate14a7bb02015-10-01 10:24:31 -07001284 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1285 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001286 }
Christopher Tate89779822012-08-31 14:40:03 -07001287
Adam Lesinski182f73f2013-12-05 16:48:06 -08001288 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001289 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001290 getContext().enforceCallingOrSelfPermission(
1291 "android.permission.SET_TIME",
1292 "setTime");
1293
Greg Hackmann0cab8962014-02-21 16:35:52 -08001294 if (mNativeData == 0) {
1295 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1296 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001297 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001298
1299 synchronized (mLock) {
1300 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001303
1304 @Override
1305 public void setTimeZone(String tz) {
1306 getContext().enforceCallingOrSelfPermission(
1307 "android.permission.SET_TIME_ZONE",
1308 "setTimeZone");
1309
1310 final long oldId = Binder.clearCallingIdentity();
1311 try {
1312 setTimeZoneImpl(tz);
1313 } finally {
1314 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 }
1316 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001317
Adam Lesinski182f73f2013-12-05 16:48:06 -08001318 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001319 public void remove(PendingIntent operation, IAlarmListener listener) {
1320 if (operation == null && listener == null) {
1321 Slog.w(TAG, "remove() with no intent or listener");
1322 return;
1323 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001324
Christopher Tate14a7bb02015-10-01 10:24:31 -07001325 synchronized (mLock) {
1326 removeLocked(operation, listener);
1327 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001329
Adam Lesinski182f73f2013-12-05 16:48:06 -08001330 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001331 public long getNextWakeFromIdleTime() {
1332 return getNextWakeFromIdleTimeImpl();
1333 }
1334
1335 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001336 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001337 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1338 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1339 "getNextAlarmClock", null);
1340
1341 return getNextAlarmClockImpl(userId);
1342 }
1343
1344 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001345 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1346 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1347 != PackageManager.PERMISSION_GRANTED) {
1348 pw.println("Permission Denial: can't dump AlarmManager from from pid="
1349 + Binder.getCallingPid()
1350 + ", uid=" + Binder.getCallingUid());
1351 return;
Christopher Tate4cb338d2013-07-26 13:11:31 -07001352 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001353
Adam Lesinski182f73f2013-12-05 16:48:06 -08001354 dumpImpl(pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001355 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001356 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001357
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001358 public final class LocalService {
1359 public void setDeviceIdleUserWhitelist(int[] appids) {
1360 setDeviceIdleUserWhitelistImpl(appids);
1361 }
1362 }
1363
Adam Lesinski182f73f2013-12-05 16:48:06 -08001364 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 synchronized (mLock) {
1366 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001367 mConstants.dump(pw);
1368 pw.println();
1369
Christopher Tatee0a22b32013-07-11 14:43:13 -07001370 final long nowRTC = System.currentTimeMillis();
1371 final long nowELAPSED = SystemClock.elapsedRealtime();
1372 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1373
Dianne Hackborna750a632015-06-16 17:18:23 -07001374 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001375 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001376 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001377 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001378 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001379 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001380 pw.print(" mLastTimeChangeRealtime=");
Dianne Hackbornc3527222015-05-13 14:03:20 -07001381 TimeUtils.formatDuration(mLastTimeChangeRealtime, pw);
1382 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001383 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001384 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001385 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1386 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001387 pw.print(" Max wakeup delay: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001388 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1389 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001390 pw.print(" Time since last dispatch: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001391 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1392 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001393 pw.print(" Next non-wakeup delivery time: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001394 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1395 pw.println();
1396 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001397
1398 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1399 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001400 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001401 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001402 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001403 pw.print(" Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001404 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001405 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
1406 pw.print(" set at "); TimeUtils.formatDuration(mLastWakeupSet, nowELAPSED, pw);
1407 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001408 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001409 pw.println(" mDeviceIdleUserWhitelist=" + Arrays.toString(mDeviceIdleUserWhitelist));
Christopher Tatee0a22b32013-07-11 14:43:13 -07001410
John Spurlock604a5ee2015-06-01 12:27:22 -04001411 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001412 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001413 final TreeSet<Integer> users = new TreeSet<>();
1414 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1415 users.add(mNextAlarmClockForUser.keyAt(i));
1416 }
1417 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1418 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1419 }
1420 for (int user : users) {
1421 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1422 final long time = next != null ? next.getTriggerTime() : 0;
1423 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001424 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001425 pw.print(" pendingSend:"); pw.print(pendingSend);
1426 pw.print(" time:"); pw.print(time);
1427 if (time > 0) {
1428 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1429 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1430 }
1431 pw.println();
1432 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001433 if (mAlarmBatches.size() > 0) {
1434 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001435 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001436 pw.println(mAlarmBatches.size());
1437 for (Batch b : mAlarmBatches) {
1438 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001439 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001440 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001442 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001443 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001444 pw.println(" Idle mode state:");
1445 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001446 if (mPendingIdleUntil != null) {
1447 pw.println(mPendingIdleUntil);
Dianne Hackbornf3831292015-10-15 14:51:06 -07001448 mPendingIdleUntil.dump(pw, " ", nowRTC, nowELAPSED, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001449 } else {
1450 pw.println("null");
1451 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001452 pw.println(" Pending alarms:");
1453 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001454 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001455 if (mNextWakeFromIdle != null) {
1456 pw.println();
1457 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
1458 mNextWakeFromIdle.dump(pw, " ", nowRTC, nowELAPSED, sdf);
1459 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001460
1461 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001462 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001463 if (mPendingNonWakeupAlarms.size() > 0) {
1464 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001465 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001466 } else {
1467 pw.println("(none)");
1468 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001469 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001470 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1471 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001472 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001473 pw.print(", max non-interactive time: ");
1474 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1475 pw.println();
1476
1477 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001478 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001479 pw.println();
1480
Christopher Tate7f2a0352015-12-08 10:24:33 -08001481 if (mInFlight.size() > 0) {
1482 pw.println("Outstanding deliveries:");
1483 for (int i = 0; i < mInFlight.size(); i++) {
1484 pw.print(" #"); pw.print(i); pw.print(": ");
1485 pw.println(mInFlight.get(i));
1486 }
1487 pw.println();
1488 }
1489
Dianne Hackborna750a632015-06-16 17:18:23 -07001490 pw.print(" mAllowWhileIdleMinTime=");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001491 TimeUtils.formatDuration(mAllowWhileIdleMinTime, pw);
1492 pw.println();
1493 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001494 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001495 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
1496 pw.print(" UID ");
1497 UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
1498 pw.print(": ");
1499 TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i),
1500 nowELAPSED, pw);
1501 pw.println();
1502 }
1503 }
1504 pw.println();
1505
Dianne Hackborn81038902012-11-26 17:04:09 -08001506 if (mLog.dump(pw, " Recent problems", " ")) {
1507 pw.println();
1508 }
1509
1510 final FilterStats[] topFilters = new FilterStats[10];
1511 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1512 @Override
1513 public int compare(FilterStats lhs, FilterStats rhs) {
1514 if (lhs.aggregateTime < rhs.aggregateTime) {
1515 return 1;
1516 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1517 return -1;
1518 }
1519 return 0;
1520 }
1521 };
1522 int len = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001523 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1524 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1525 for (int ip=0; ip<uidStats.size(); ip++) {
1526 BroadcastStats bs = uidStats.valueAt(ip);
1527 for (int is=0; is<bs.filterStats.size(); is++) {
1528 FilterStats fs = bs.filterStats.valueAt(is);
1529 int pos = len > 0
1530 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1531 if (pos < 0) {
1532 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001533 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001534 if (pos < topFilters.length) {
1535 int copylen = topFilters.length - pos - 1;
1536 if (copylen > 0) {
1537 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1538 }
1539 topFilters[pos] = fs;
1540 if (len < topFilters.length) {
1541 len++;
1542 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001543 }
1544 }
1545 }
1546 }
1547 if (len > 0) {
1548 pw.println(" Top Alarms:");
1549 for (int i=0; i<len; i++) {
1550 FilterStats fs = topFilters[i];
1551 pw.print(" ");
1552 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1553 TimeUtils.formatDuration(fs.aggregateTime, pw);
1554 pw.print(" running, "); pw.print(fs.numWakeup);
1555 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001556 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1557 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001558 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001559 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001560 pw.println();
1561 }
1562 }
1563
1564 pw.println(" ");
1565 pw.println(" Alarm Stats:");
1566 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001567 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1568 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1569 for (int ip=0; ip<uidStats.size(); ip++) {
1570 BroadcastStats bs = uidStats.valueAt(ip);
1571 pw.print(" ");
1572 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1573 UserHandle.formatUid(pw, bs.mUid);
1574 pw.print(":");
1575 pw.print(bs.mPackageName);
1576 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1577 pw.print(" running, "); pw.print(bs.numWakeup);
1578 pw.println(" wakeups:");
1579 tmpFilters.clear();
1580 for (int is=0; is<bs.filterStats.size(); is++) {
1581 tmpFilters.add(bs.filterStats.valueAt(is));
1582 }
1583 Collections.sort(tmpFilters, comparator);
1584 for (int i=0; i<tmpFilters.size(); i++) {
1585 FilterStats fs = tmpFilters.get(i);
1586 pw.print(" ");
1587 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1588 TimeUtils.formatDuration(fs.aggregateTime, pw);
1589 pw.print(" "); pw.print(fs.numWakeup);
1590 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001591 pw.print(" alarms, last ");
1592 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1593 pw.println(":");
1594 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001595 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001596 pw.println();
1597 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001598 }
1599 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001600
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001601 if (RECORD_DEVICE_IDLE_ALARMS) {
1602 pw.println();
1603 pw.println(" Allow while idle dispatches:");
1604 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
1605 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
1606 pw.print(" ");
1607 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
1608 pw.print(": ");
1609 UserHandle.formatUid(pw, ent.uid);
1610 pw.print(":");
1611 pw.println(ent.pkg);
1612 if (ent.op != null) {
1613 pw.print(" ");
1614 pw.print(ent.op);
1615 pw.print(" / ");
1616 pw.print(ent.tag);
1617 if (ent.argRealtime != 0) {
1618 pw.print(" (");
1619 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
1620 pw.print(")");
1621 }
1622 pw.println();
1623 }
1624 }
1625 }
1626
Christopher Tate18a75f12013-07-01 18:18:59 -07001627 if (WAKEUP_STATS) {
1628 pw.println();
1629 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001630 long last = -1;
1631 for (WakeupEvent event : mRecentWakeups) {
1632 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1633 pw.print('|');
1634 if (last < 0) {
1635 pw.print('0');
1636 } else {
1637 pw.print(event.when - last);
1638 }
1639 last = event.when;
1640 pw.print('|'); pw.print(event.uid);
1641 pw.print('|'); pw.print(event.action);
1642 pw.println();
1643 }
1644 pw.println();
1645 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 }
1647 }
1648
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001649 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001650 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
1651 PrintWriter pw = new PrintWriter(bs);
1652 final long nowRTC = System.currentTimeMillis();
1653 final long nowELAPSED = SystemClock.elapsedRealtime();
1654 final int NZ = mAlarmBatches.size();
1655 for (int iz = 0; iz < NZ; iz++) {
1656 Batch bz = mAlarmBatches.get(iz);
1657 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001658 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001659 pw.flush();
1660 Slog.v(TAG, bs.toString());
1661 bs.reset();
1662 }
1663 }
1664
1665 private boolean validateConsistencyLocked() {
1666 if (DEBUG_VALIDATE) {
1667 long lastTime = Long.MIN_VALUE;
1668 final int N = mAlarmBatches.size();
1669 for (int i = 0; i < N; i++) {
1670 Batch b = mAlarmBatches.get(i);
1671 if (b.start >= lastTime) {
1672 // duplicate start times are okay because of standalone batches
1673 lastTime = b.start;
1674 } else {
1675 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001676 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1677 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001678 return false;
1679 }
1680 }
1681 }
1682 return true;
1683 }
1684
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001685 private Batch findFirstWakeupBatchLocked() {
1686 final int N = mAlarmBatches.size();
1687 for (int i = 0; i < N; i++) {
1688 Batch b = mAlarmBatches.get(i);
1689 if (b.hasWakeups()) {
1690 return b;
1691 }
1692 }
1693 return null;
1694 }
1695
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001696 long getNextWakeFromIdleTimeImpl() {
1697 synchronized (mLock) {
1698 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
1699 }
1700 }
1701
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001702 void setDeviceIdleUserWhitelistImpl(int[] appids) {
1703 synchronized (mLock) {
1704 mDeviceIdleUserWhitelist = appids;
1705 }
1706 }
1707
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001708 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001709 synchronized (mLock) {
1710 return mNextAlarmClockForUser.get(userId);
1711 }
1712 }
1713
1714 /**
1715 * Recomputes the next alarm clock for all users.
1716 */
1717 private void updateNextAlarmClockLocked() {
1718 if (!mNextAlarmClockMayChange) {
1719 return;
1720 }
1721 mNextAlarmClockMayChange = false;
1722
Jose Lima235510e2014-08-13 12:50:01 -07001723 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001724 nextForUser.clear();
1725
1726 final int N = mAlarmBatches.size();
1727 for (int i = 0; i < N; i++) {
1728 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
1729 final int M = alarms.size();
1730
1731 for (int j = 0; j < M; j++) {
1732 Alarm a = alarms.get(j);
1733 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001734 final int userId = UserHandle.getUserId(a.uid);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001735
1736 if (DEBUG_ALARM_CLOCK) {
1737 Log.v(TAG, "Found AlarmClockInfo 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);
1745 }
1746 }
1747 }
1748 }
1749
1750 // Update mNextAlarmForUser with new values.
1751 final int NN = nextForUser.size();
1752 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07001753 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001754 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001755 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001756 if (!newAlarm.equals(currentAlarm)) {
1757 updateNextAlarmInfoForUserLocked(userId, newAlarm);
1758 }
1759 }
1760
1761 // Remove users without any alarm clocks scheduled.
1762 final int NNN = mNextAlarmClockForUser.size();
1763 for (int i = NNN - 1; i >= 0; i--) {
1764 int userId = mNextAlarmClockForUser.keyAt(i);
1765 if (nextForUser.get(userId) == null) {
1766 updateNextAlarmInfoForUserLocked(userId, null);
1767 }
1768 }
1769 }
1770
Jose Lima235510e2014-08-13 12:50:01 -07001771 private void updateNextAlarmInfoForUserLocked(int userId,
1772 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001773 if (alarmClock != null) {
1774 if (DEBUG_ALARM_CLOCK) {
1775 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001776 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02001777 }
1778 mNextAlarmClockForUser.put(userId, alarmClock);
1779 } else {
1780 if (DEBUG_ALARM_CLOCK) {
1781 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
1782 }
1783 mNextAlarmClockForUser.remove(userId);
1784 }
1785
1786 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
1787 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1788 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1789 }
1790
1791 /**
1792 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
1793 * for which alarm clocks have changed since the last call to this.
1794 *
1795 * Do not call with a lock held. Only call from mHandler's thread.
1796 *
1797 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
1798 */
1799 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07001800 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001801 pendingUsers.clear();
1802
1803 synchronized (mLock) {
1804 final int N = mPendingSendNextAlarmClockChangedForUser.size();
1805 for (int i = 0; i < N; i++) {
1806 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
1807 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
1808 }
1809 mPendingSendNextAlarmClockChangedForUser.clear();
1810 }
1811
1812 final int N = pendingUsers.size();
1813 for (int i = 0; i < N; i++) {
1814 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001815 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001816 Settings.System.putStringForUser(getContext().getContentResolver(),
1817 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01001818 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02001819 userId);
1820
1821 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
1822 new UserHandle(userId));
1823 }
1824 }
1825
1826 /**
1827 * Formats an alarm like platform/packages/apps/DeskClock used to.
1828 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01001829 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
1830 int userId) {
1831 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02001832 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
1833 return (info == null) ? "" :
1834 DateFormat.format(pattern, info.getTriggerTime()).toString();
1835 }
1836
Adam Lesinski182f73f2013-12-05 16:48:06 -08001837 void rescheduleKernelAlarmsLocked() {
1838 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
1839 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001840 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001841 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001842 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001843 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07001844 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001845 mNextWakeup = firstWakeup.start;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001846 mLastWakeupSet = SystemClock.elapsedRealtime();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001847 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001848 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001849 if (firstBatch != firstWakeup) {
1850 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001851 }
1852 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001853 if (mPendingNonWakeupAlarms.size() > 0) {
1854 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
1855 nextNonWakeup = mNextNonWakeupDeliveryTime;
1856 }
1857 }
Prashant Malani753e9e02015-06-10 17:43:49 -07001858 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001859 mNextNonWakeup = nextNonWakeup;
1860 setLocked(ELAPSED_REALTIME, nextNonWakeup);
1861 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001862 }
1863
Christopher Tate14a7bb02015-10-01 10:24:31 -07001864 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001865 boolean didRemove = false;
1866 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1867 Batch b = mAlarmBatches.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -07001868 didRemove |= b.remove(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001869 if (b.size() == 0) {
1870 mAlarmBatches.remove(i);
1871 }
1872 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001873 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001874 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001875 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1876 mPendingWhileIdleAlarms.remove(i);
1877 }
1878 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001879
1880 if (didRemove) {
1881 if (DEBUG_BATCH) {
1882 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
1883 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001884 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001885 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001886 mPendingIdleUntil = null;
1887 restorePending = true;
1888 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001889 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001890 mNextWakeFromIdle = null;
1891 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001892 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001893 if (restorePending) {
1894 restorePendingWhileIdleAlarmsLocked();
1895 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001896 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001897 }
1898 }
1899
1900 void removeLocked(String packageName) {
1901 boolean didRemove = false;
1902 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1903 Batch b = mAlarmBatches.get(i);
1904 didRemove |= b.remove(packageName);
1905 if (b.size() == 0) {
1906 mAlarmBatches.remove(i);
1907 }
1908 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001909 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001910 final Alarm a = mPendingWhileIdleAlarms.get(i);
1911 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001912 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1913 mPendingWhileIdleAlarms.remove(i);
1914 }
1915 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001916
1917 if (didRemove) {
1918 if (DEBUG_BATCH) {
1919 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1920 }
1921 rebatchAllAlarmsLocked(true);
1922 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001923 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001924 }
1925 }
1926
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001927 void removeForStoppedLocked(int uid) {
1928 boolean didRemove = false;
1929 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1930 Batch b = mAlarmBatches.get(i);
1931 didRemove |= b.removeForStopped(uid);
1932 if (b.size() == 0) {
1933 mAlarmBatches.remove(i);
1934 }
1935 }
1936 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1937 final Alarm a = mPendingWhileIdleAlarms.get(i);
1938 try {
1939 if (a.uid == uid && ActivityManagerNative.getDefault().getAppStartMode(
1940 uid, a.packageName) == ActivityManager.APP_START_MODE_DISABLED) {
1941 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1942 mPendingWhileIdleAlarms.remove(i);
1943 }
1944 } catch (RemoteException e) {
1945 }
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++) {
2416 ActivityManagerNative.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 {
2420 ActivityManagerNative.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);
2470 rebatchAllAlarms();
2471 mClockReceiver.scheduleTimeTickEvent();
2472 synchronized (mLock) {
2473 mNumTimeChanged++;
2474 mLastTimeChangeClockTime = nowRTC;
2475 mLastTimeChangeRealtime = nowELAPSED;
2476 }
2477 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
2478 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
2479 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2480 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
2481
2482 // The world has changed on us, so we need to re-evaluate alarms
2483 // regardless of whether the kernel has told us one went off.
2484 result |= IS_WAKEUP_MASK;
2485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002486 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002487
Dianne Hackbornc3527222015-05-13 14:03:20 -07002488 if (result != TIME_CHANGED_MASK) {
2489 // If this was anything besides just a time change, then figure what if
2490 // anything to do about alarms.
2491 synchronized (mLock) {
2492 if (localLOGV) Slog.v(
2493 TAG, "Checking for alarms... rtc=" + nowRTC
2494 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07002495
Dianne Hackbornc3527222015-05-13 14:03:20 -07002496 if (WAKEUP_STATS) {
2497 if ((result & IS_WAKEUP_MASK) != 0) {
2498 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
2499 int n = 0;
2500 for (WakeupEvent event : mRecentWakeups) {
2501 if (event.when > newEarliest) break;
2502 n++; // number of now-stale entries at the list head
2503 }
2504 for (int i = 0; i < n; i++) {
2505 mRecentWakeups.remove();
2506 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002507
Dianne Hackbornc3527222015-05-13 14:03:20 -07002508 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002509 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002510 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002511
2512 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2513 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
2514 // if there are no wakeup alarms and the screen is off, we can
2515 // delay what we have so far until the future.
2516 if (mPendingNonWakeupAlarms.size() == 0) {
2517 mStartCurrentDelayTime = nowELAPSED;
2518 mNextNonWakeupDeliveryTime = nowELAPSED
2519 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
2520 }
2521 mPendingNonWakeupAlarms.addAll(triggerList);
2522 mNumDelayedAlarms += triggerList.size();
2523 rescheduleKernelAlarmsLocked();
2524 updateNextAlarmClockLocked();
2525 } else {
2526 // now deliver the alarm intents; if there are pending non-wakeup
2527 // alarms, we need to merge them in to the list. note we don't
2528 // just deliver them first because we generally want non-wakeup
2529 // alarms delivered after wakeup alarms.
2530 rescheduleKernelAlarmsLocked();
2531 updateNextAlarmClockLocked();
2532 if (mPendingNonWakeupAlarms.size() > 0) {
2533 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
2534 triggerList.addAll(mPendingNonWakeupAlarms);
2535 Collections.sort(triggerList, mAlarmDispatchComparator);
2536 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2537 mTotalDelayTime += thisDelayTime;
2538 if (mMaxDelayTime < thisDelayTime) {
2539 mMaxDelayTime = thisDelayTime;
2540 }
2541 mPendingNonWakeupAlarms.clear();
2542 }
2543 deliverAlarmsLocked(triggerList, nowELAPSED);
2544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002546
2547 } else {
2548 // Just in case -- even though no wakeup flag was set, make sure
2549 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07002550 synchronized (mLock) {
2551 rescheduleKernelAlarmsLocked();
2552 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002553 }
2554 }
2555 }
2556 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002557
David Christieebe51fc2013-07-26 13:23:29 -07002558 /**
2559 * Attribute blame for a WakeLock.
2560 * @param pi PendingIntent to attribute blame to if ws is null.
2561 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002562 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07002563 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002564 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002565 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07002566 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002567 final boolean unimportant = pi == mTimeTickSender;
2568 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002569 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002570 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002571 } else {
2572 mWakeLock.setHistoryTag(null);
2573 }
2574 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07002575 if (ws != null) {
2576 mWakeLock.setWorkSource(ws);
2577 return;
2578 }
2579
Christopher Tate14a7bb02015-10-01 10:24:31 -07002580 final int uid = (knownUid >= 0)
2581 ? knownUid
2582 : ActivityManagerNative.getDefault().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07002583 if (uid >= 0) {
2584 mWakeLock.setWorkSource(new WorkSource(uid));
2585 return;
2586 }
2587 } catch (Exception e) {
2588 }
2589
2590 // Something went wrong; fall back to attributing the lock to the OS
2591 mWakeLock.setWorkSource(null);
2592 }
2593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002594 private class AlarmHandler extends Handler {
2595 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002596 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
2597 public static final int LISTENER_TIMEOUT = 3;
2598 public static final int REPORT_ALARMS_ACTIVE = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002599
2600 public AlarmHandler() {
2601 }
2602
2603 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002604 switch (msg.what) {
2605 case ALARM_EVENT: {
2606 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2607 synchronized (mLock) {
2608 final long nowRTC = System.currentTimeMillis();
2609 final long nowELAPSED = SystemClock.elapsedRealtime();
2610 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2611 updateNextAlarmClockLocked();
2612 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002613
Christopher Tate14a7bb02015-10-01 10:24:31 -07002614 // now trigger the alarms without the lock held
2615 for (int i=0; i<triggerList.size(); i++) {
2616 Alarm alarm = triggerList.get(i);
2617 try {
2618 alarm.operation.send();
2619 } catch (PendingIntent.CanceledException e) {
2620 if (alarm.repeatInterval > 0) {
2621 // This IntentSender is no longer valid, but this
2622 // is a repeating alarm, so toss the hoser.
2623 removeImpl(alarm.operation);
2624 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002625 }
2626 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002627 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002628 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002629
2630 case SEND_NEXT_ALARM_CLOCK_CHANGED:
2631 sendNextAlarmClockChanged();
2632 break;
2633
2634 case LISTENER_TIMEOUT:
2635 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
2636 break;
2637
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002638 case REPORT_ALARMS_ACTIVE:
2639 if (mLocalDeviceIdleController != null) {
2640 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
2641 }
2642 break;
2643
Christopher Tate14a7bb02015-10-01 10:24:31 -07002644 default:
2645 // nope, just ignore it
2646 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002647 }
2648 }
2649 }
2650
2651 class ClockReceiver extends BroadcastReceiver {
2652 public ClockReceiver() {
2653 IntentFilter filter = new IntentFilter();
2654 filter.addAction(Intent.ACTION_TIME_TICK);
2655 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002656 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002657 }
2658
2659 @Override
2660 public void onReceive(Context context, Intent intent) {
2661 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07002662 if (DEBUG_BATCH) {
2663 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
2664 }
2665 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002666 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
2667 // Since the kernel does not keep track of DST, we need to
2668 // reset the TZ information at the beginning of each day
2669 // based off of the current Zone gmt offset + userspace tracked
2670 // daylight savings information.
2671 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02002672 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002673 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07002674 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002675 }
2676 }
2677
2678 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07002679 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09002680 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07002681
2682 // Schedule this event for the amount of time that it would take to get to
2683 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09002684 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07002685
David Christieebe51fc2013-07-26 13:23:29 -07002686 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002687 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002688 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
2689 null, Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002690 }
Christopher Tate385e4982013-07-23 18:22:29 -07002691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002692 public void scheduleDateChangedEvent() {
2693 Calendar calendar = Calendar.getInstance();
2694 calendar.setTimeInMillis(System.currentTimeMillis());
2695 calendar.set(Calendar.HOUR, 0);
2696 calendar.set(Calendar.MINUTE, 0);
2697 calendar.set(Calendar.SECOND, 0);
2698 calendar.set(Calendar.MILLISECOND, 0);
2699 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07002700
2701 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002702 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
2703 AlarmManager.FLAG_STANDALONE, workSource, null,
2704 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002705 }
2706 }
2707
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002708 class InteractiveStateReceiver extends BroadcastReceiver {
2709 public InteractiveStateReceiver() {
2710 IntentFilter filter = new IntentFilter();
2711 filter.addAction(Intent.ACTION_SCREEN_OFF);
2712 filter.addAction(Intent.ACTION_SCREEN_ON);
2713 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
2714 getContext().registerReceiver(this, filter);
2715 }
2716
2717 @Override
2718 public void onReceive(Context context, Intent intent) {
2719 synchronized (mLock) {
2720 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
2721 }
2722 }
2723 }
2724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002725 class UninstallReceiver extends BroadcastReceiver {
2726 public UninstallReceiver() {
2727 IntentFilter filter = new IntentFilter();
2728 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2729 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002730 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002731 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08002732 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002733 // Register for events related to sdcard installation.
2734 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08002735 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002736 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002737 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002738 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002739 }
2740
2741 @Override
2742 public void onReceive(Context context, Intent intent) {
2743 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002744 String action = intent.getAction();
2745 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002746 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
2747 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
2748 for (String packageName : pkgList) {
2749 if (lookForPackageLocked(packageName)) {
2750 setResultCode(Activity.RESULT_OK);
2751 return;
2752 }
2753 }
2754 return;
2755 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002756 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002757 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
2758 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
2759 if (userHandle >= 0) {
2760 removeUserLocked(userHandle);
2761 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002762 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
2763 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
2764 if (uid >= 0) {
2765 mLastAllowWhileIdleDispatch.delete(uid);
2766 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002767 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08002768 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
2769 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
2770 // This package is being updated; don't kill its alarms.
2771 return;
2772 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002773 Uri data = intent.getData();
2774 if (data != null) {
2775 String pkg = data.getSchemeSpecificPart();
2776 if (pkg != null) {
2777 pkgList = new String[]{pkg};
2778 }
2779 }
2780 }
2781 if (pkgList != null && (pkgList.length > 0)) {
2782 for (String pkg : pkgList) {
2783 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07002784 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002785 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
2786 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
2787 if (uidStats.remove(pkg) != null) {
2788 if (uidStats.size() <= 0) {
2789 mBroadcastStats.removeAt(i);
2790 }
2791 }
2792 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002793 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002794 }
2795 }
2796 }
2797 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002798
2799 final class UidObserver extends IUidObserver.Stub {
2800 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
2801 }
2802
2803 @Override public void onUidGone(int uid) throws RemoteException {
2804 }
2805
2806 @Override public void onUidActive(int uid) throws RemoteException {
2807 }
2808
2809 @Override public void onUidIdle(int uid) throws RemoteException {
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08002810 synchronized (mLock) {
2811 removeForStoppedLocked(uid);
2812 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002813 }
2814 };
2815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002816 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002817 String pkg = pi.getCreatorPackage();
2818 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002819 return getStatsLocked(uid, pkg);
2820 }
2821
2822 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002823 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
2824 if (uidStats == null) {
2825 uidStats = new ArrayMap<String, BroadcastStats>();
2826 mBroadcastStats.put(uid, uidStats);
2827 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002828 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002829 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002830 bs = new BroadcastStats(uid, pkgName);
2831 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002832 }
2833 return bs;
2834 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002835
Christopher Tate14a7bb02015-10-01 10:24:31 -07002836 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
2837 private InFlight removeLocked(PendingIntent pi, Intent intent) {
2838 for (int i = 0; i < mInFlight.size(); i++) {
2839 if (mInFlight.get(i).mPendingIntent == pi) {
2840 return mInFlight.remove(i);
2841 }
2842 }
2843 mLog.w("No in-flight alarm for " + pi + " " + intent);
2844 return null;
2845 }
2846
2847 private InFlight removeLocked(IBinder listener) {
2848 for (int i = 0; i < mInFlight.size(); i++) {
2849 if (mInFlight.get(i).mListener == listener) {
2850 return mInFlight.remove(i);
2851 }
2852 }
2853 mLog.w("No in-flight alarm for listener " + listener);
2854 return null;
2855 }
2856
2857 private void updateStatsLocked(InFlight inflight) {
2858 final long nowELAPSED = SystemClock.elapsedRealtime();
2859 BroadcastStats bs = inflight.mBroadcastStats;
2860 bs.nesting--;
2861 if (bs.nesting <= 0) {
2862 bs.nesting = 0;
2863 bs.aggregateTime += nowELAPSED - bs.startTime;
2864 }
2865 FilterStats fs = inflight.mFilterStats;
2866 fs.nesting--;
2867 if (fs.nesting <= 0) {
2868 fs.nesting = 0;
2869 fs.aggregateTime += nowELAPSED - fs.startTime;
2870 }
2871 if (RECORD_ALARMS_IN_HISTORY) {
2872 if (inflight.mWorkSource != null && inflight.mWorkSource.size() > 0) {
2873 for (int wi=0; wi<inflight.mWorkSource.size(); wi++) {
2874 ActivityManagerNative.noteAlarmFinish(
2875 inflight.mPendingIntent, inflight.mWorkSource.get(wi), inflight.mTag);
2876 }
2877 } else {
2878 ActivityManagerNative.noteAlarmFinish(
2879 inflight.mPendingIntent, inflight.mUid, inflight.mTag);
2880 }
2881 }
2882 }
2883
2884 private void updateTrackingLocked(InFlight inflight) {
2885 if (inflight != null) {
2886 updateStatsLocked(inflight);
2887 }
2888 mBroadcastRefCount--;
2889 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002890 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002891 mWakeLock.release();
2892 if (mInFlight.size() > 0) {
2893 mLog.w("Finished all dispatches with " + mInFlight.size()
2894 + " remaining inflights");
2895 for (int i=0; i<mInFlight.size(); i++) {
2896 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
2897 }
2898 mInFlight.clear();
2899 }
2900 } else {
2901 // the next of our alarms is now in flight. reattribute the wakelock.
2902 if (mInFlight.size() > 0) {
2903 InFlight inFlight = mInFlight.get(0);
2904 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
2905 inFlight.mAlarmType, inFlight.mTag, -1, false);
2906 } else {
2907 // should never happen
2908 mLog.w("Alarm wakelock still held but sent queue empty");
2909 mWakeLock.setWorkSource(null);
2910 }
2911 }
2912 }
2913
2914 /**
2915 * Callback that arrives when a direct-call alarm reports that delivery has finished
2916 */
2917 @Override
2918 public void alarmComplete(IBinder who) {
2919 if (who == null) {
2920 Slog.w(TAG, "Invalid alarmComplete: uid=" + Binder.getCallingUid()
2921 + " pid=" + Binder.getCallingPid());
2922 return;
2923 }
2924
2925 final long ident = Binder.clearCallingIdentity();
2926 try {
2927 synchronized (mLock) {
2928 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
2929 InFlight inflight = removeLocked(who);
2930 if (inflight != null) {
2931 if (DEBUG_LISTENER_CALLBACK) {
2932 Slog.i(TAG, "alarmComplete() from " + who);
2933 }
2934 updateTrackingLocked(inflight);
2935 } else {
2936 // Delivery timed out, and the timeout handling already took care of
2937 // updating our tracking here, so we needn't do anything further.
2938 if (DEBUG_LISTENER_CALLBACK) {
2939 Slog.i(TAG, "Late alarmComplete() from " + who);
2940 }
2941 }
2942 }
2943 } finally {
2944 Binder.restoreCallingIdentity(ident);
2945 }
2946 }
2947
2948 /**
2949 * Callback that arrives when a PendingIntent alarm has finished delivery
2950 */
2951 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002952 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
2953 String resultData, Bundle resultExtras) {
2954 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002955 updateTrackingLocked(removeLocked(pi, intent));
2956 }
2957 }
2958
2959 /**
2960 * Timeout of a direct-call alarm delivery
2961 */
2962 public void alarmTimedOut(IBinder who) {
2963 synchronized (mLock) {
2964 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08002965 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002966 // TODO: implement ANR policy for the target
2967 if (DEBUG_LISTENER_CALLBACK) {
2968 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002969 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002970 updateTrackingLocked(inflight);
Dianne Hackborn81038902012-11-26 17:04:09 -08002971 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002972 if (DEBUG_LISTENER_CALLBACK) {
2973 Slog.i(TAG, "Spurious timeout of listener " + who);
2974 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002975 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002976 }
2977 }
2978
2979 /**
2980 * Deliver an alarm and set up the post-delivery handling appropriately
2981 */
2982 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
2983 if (alarm.operation != null) {
2984 // PendingIntent alarm
2985 try {
2986 alarm.operation.send(getContext(), 0,
2987 mBackgroundIntent.putExtra(
2988 Intent.EXTRA_ALARM_COUNT, alarm.count),
2989 mDeliveryTracker, mHandler, null,
2990 allowWhileIdle ? mIdleOptions : null);
2991 } catch (PendingIntent.CanceledException e) {
2992 if (alarm.repeatInterval > 0) {
2993 // This IntentSender is no longer valid, but this
2994 // is a repeating alarm, so toss it
2995 removeImpl(alarm.operation);
2996 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08002997 // No actual delivery was possible, so the delivery tracker's
2998 // 'finished' callback won't be invoked. We also don't need
2999 // to do any wakelock or stats tracking, so we have nothing
3000 // left to do here but go on to the next thing.
3001 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003002 }
3003 } else {
3004 // Direct listener callback alarm
3005 try {
3006 if (DEBUG_LISTENER_CALLBACK) {
3007 Slog.v(TAG, "Alarm to uid=" + alarm.uid
3008 + " listener=" + alarm.listener.asBinder());
3009 }
3010 alarm.listener.doAlarm(this);
3011 mHandler.sendMessageDelayed(
3012 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
3013 alarm.listener.asBinder()),
3014 mConstants.LISTENER_TIMEOUT);
3015 } catch (Exception e) {
3016 if (DEBUG_LISTENER_CALLBACK) {
3017 Slog.i(TAG, "Alarm undeliverable to listener "
3018 + alarm.listener.asBinder(), e);
3019 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003020 // As in the PendingIntent.CanceledException case, delivery of the
3021 // alarm was not possible, so we have no wakelock or timeout or
3022 // stats management to do. It threw before we posted the delayed
3023 // timeout message, so we're done here.
3024 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003025 }
3026 }
3027
3028 // The alarm is now in flight; now arrange wakelock and stats tracking
3029 if (mBroadcastRefCount == 0) {
3030 setWakelockWorkSource(alarm.operation, alarm.workSource,
3031 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
3032 true);
3033 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003034 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003035 }
3036 final InFlight inflight = new InFlight(AlarmManagerService.this,
3037 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
3038 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
3039 mInFlight.add(inflight);
3040 mBroadcastRefCount++;
3041
3042 if (allowWhileIdle) {
3043 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
3044 mLastAllowWhileIdleDispatch.put(alarm.uid, nowELAPSED);
3045 if (RECORD_DEVICE_IDLE_ALARMS) {
3046 IdleDispatchEntry ent = new IdleDispatchEntry();
3047 ent.uid = alarm.uid;
3048 ent.pkg = alarm.packageName;
3049 ent.tag = alarm.statsTag;
3050 ent.op = "DELIVER";
3051 ent.elapsedRealtime = nowELAPSED;
3052 mAllowWhileIdleDispatches.add(ent);
3053 }
3054 }
3055
3056 final BroadcastStats bs = inflight.mBroadcastStats;
3057 bs.count++;
3058 if (bs.nesting == 0) {
3059 bs.nesting = 1;
3060 bs.startTime = nowELAPSED;
3061 } else {
3062 bs.nesting++;
3063 }
3064 final FilterStats fs = inflight.mFilterStats;
3065 fs.count++;
3066 if (fs.nesting == 0) {
3067 fs.nesting = 1;
3068 fs.startTime = nowELAPSED;
3069 } else {
3070 fs.nesting++;
3071 }
3072 if (alarm.type == ELAPSED_REALTIME_WAKEUP
3073 || alarm.type == RTC_WAKEUP) {
3074 bs.numWakeup++;
3075 fs.numWakeup++;
3076 if (alarm.workSource != null && alarm.workSource.size() > 0) {
3077 for (int wi=0; wi<alarm.workSource.size(); wi++) {
Christopher Tate0029f572016-06-14 10:16:28 -07003078 final String wsName = alarm.workSource.getName(wi);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003079 ActivityManagerNative.noteWakeupAlarm(
3080 alarm.operation, alarm.workSource.get(wi),
Christopher Tate0029f572016-06-14 10:16:28 -07003081 (wsName != null) ? wsName : alarm.packageName,
3082 alarm.statsTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08003083 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003084 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003085 ActivityManagerNative.noteWakeupAlarm(
Joe Onorato78bcdf92016-05-09 10:10:29 -07003086 alarm.operation, alarm.uid, alarm.packageName, alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003087 }
3088 }
3089 }
3090 }
3091}