blob: 46671729a2ef0a4eedba287c744ccb28dcf4cf44 [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;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800128 int mBroadcastRefCount = 0;
129 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700130 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700131 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
132 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800133 final AlarmHandler mHandler = new AlarmHandler();
134 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700135 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700137 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800138 PendingIntent mTimeTickSender;
139 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700140 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700141 boolean mInteractive = true;
142 long mNonInteractiveStartTime;
143 long mNonInteractiveTime;
144 long mLastAlarmDeliveryTime;
145 long mStartCurrentDelayTime;
146 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700147 long mLastTimeChangeClockTime;
148 long mLastTimeChangeRealtime;
Dianne Hackborna750a632015-06-16 17:18:23 -0700149 long mAllowWhileIdleMinTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700150 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800151
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700152 /**
153 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
154 * used to determine the earliest we can dispatch the next such alarm.
155 */
156 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
157
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700158 final static class IdleDispatchEntry {
159 int uid;
160 String pkg;
161 String tag;
162 String op;
163 long elapsedRealtime;
164 long argRealtime;
165 }
166 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
167
Dianne Hackborna750a632015-06-16 17:18:23 -0700168 /**
169 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
170 */
171 Bundle mIdleOptions;
172
Jose Lima235510e2014-08-13 12:50:01 -0700173 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
174 new SparseArray<>();
175 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
176 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200177 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
178 new SparseBooleanArray();
179 private boolean mNextAlarmClockMayChange;
180
181 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700182 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
183 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200184
Dianne Hackborna750a632015-06-16 17:18:23 -0700185 /**
186 * All times are in milliseconds. These constants are kept synchronized with the system
187 * global Settings. Any access to this class or its fields should be done while
188 * holding the AlarmManagerService.mLock lock.
189 */
190 private final class Constants extends ContentObserver {
191 // Key names stored in the settings value.
192 private static final String KEY_MIN_FUTURITY = "min_futurity";
193 private static final String KEY_MIN_INTERVAL = "min_interval";
194 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
195 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
196 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
197 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700198 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Dianne Hackborna750a632015-06-16 17:18:23 -0700199
200 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
201 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tateaa244da2015-08-27 15:57:57 -0700202 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700203 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700204 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
205
Christopher Tate14a7bb02015-10-01 10:24:31 -0700206 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
207
Dianne Hackborna750a632015-06-16 17:18:23 -0700208 // Minimum futurity of a new alarm
209 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
210
211 // Minimum alarm recurrence interval
212 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
213
214 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
215 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
216
217 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
218 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
219
220 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
221 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
222 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
223
Christopher Tate14a7bb02015-10-01 10:24:31 -0700224 // Direct alarm listener callback timeout
225 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
226
Dianne Hackborna750a632015-06-16 17:18:23 -0700227 private ContentResolver mResolver;
228 private final KeyValueListParser mParser = new KeyValueListParser(',');
229 private long mLastAllowWhileIdleWhitelistDuration = -1;
230
231 public Constants(Handler handler) {
232 super(handler);
233 updateAllowWhileIdleMinTimeLocked();
234 updateAllowWhileIdleWhitelistDurationLocked();
235 }
236
237 public void start(ContentResolver resolver) {
238 mResolver = resolver;
239 mResolver.registerContentObserver(Settings.Global.getUriFor(
240 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
241 updateConstants();
242 }
243
244 public void updateAllowWhileIdleMinTimeLocked() {
245 mAllowWhileIdleMinTime = mPendingIdleUntil != null
246 ? ALLOW_WHILE_IDLE_LONG_TIME : ALLOW_WHILE_IDLE_SHORT_TIME;
247 }
248
249 public void updateAllowWhileIdleWhitelistDurationLocked() {
250 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
251 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
252 BroadcastOptions opts = BroadcastOptions.makeBasic();
253 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
254 mIdleOptions = opts.toBundle();
255 }
256 }
257
258 @Override
259 public void onChange(boolean selfChange, Uri uri) {
260 updateConstants();
261 }
262
263 private void updateConstants() {
264 synchronized (mLock) {
265 try {
266 mParser.setString(Settings.Global.getString(mResolver,
267 Settings.Global.ALARM_MANAGER_CONSTANTS));
268 } catch (IllegalArgumentException e) {
269 // Failed to parse the settings string, log this and move on
270 // with defaults.
271 Slog.e(TAG, "Bad device idle settings", e);
272 }
273
274 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
275 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
276 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
277 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
278 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
279 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
280 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
281 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
282 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700283 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
284 DEFAULT_LISTENER_TIMEOUT);
Dianne Hackborna750a632015-06-16 17:18:23 -0700285
286 updateAllowWhileIdleMinTimeLocked();
287 updateAllowWhileIdleWhitelistDurationLocked();
288 }
289 }
290
291 void dump(PrintWriter pw) {
292 pw.println(" Settings:");
293
294 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
295 TimeUtils.formatDuration(MIN_FUTURITY, pw);
296 pw.println();
297
298 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
299 TimeUtils.formatDuration(MIN_INTERVAL, pw);
300 pw.println();
301
Christopher Tate14a7bb02015-10-01 10:24:31 -0700302 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
303 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
304 pw.println();
305
Dianne Hackborna750a632015-06-16 17:18:23 -0700306 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
307 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
308 pw.println();
309
310 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
311 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
312 pw.println();
313
314 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
315 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
316 pw.println();
317 }
318 }
319
320 final Constants mConstants;
321
Christopher Tate1590f1e2014-10-02 17:27:57 -0700322 // Alarm delivery ordering bookkeeping
323 static final int PRIO_TICK = 0;
324 static final int PRIO_WAKEUP = 1;
325 static final int PRIO_NORMAL = 2;
326
Dianne Hackborna750a632015-06-16 17:18:23 -0700327 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700328 int seq;
329 int priority;
330
331 PriorityClass() {
332 seq = mCurrentSeq - 1;
333 priority = PRIO_NORMAL;
334 }
335 }
336
Dianne Hackborna750a632015-06-16 17:18:23 -0700337 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700338 int mCurrentSeq = 0;
339
Dianne Hackborna750a632015-06-16 17:18:23 -0700340 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700341 public long when;
342 public int uid;
343 public String action;
344
345 public WakeupEvent(long theTime, int theUid, String theAction) {
346 when = theTime;
347 uid = theUid;
348 action = theAction;
349 }
350 }
351
Adam Lesinski182f73f2013-12-05 16:48:06 -0800352 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
353 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700354
Adrian Roosc42a1e12014-07-07 23:35:53 +0200355 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700356 long start; // These endpoints are always in ELAPSED
357 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700358 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700359
360 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
361
362 Batch() {
363 start = 0;
364 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700365 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700366 }
367
368 Batch(Alarm seed) {
369 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700370 end = seed.maxWhenElapsed;
371 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700372 alarms.add(seed);
373 }
374
375 int size() {
376 return alarms.size();
377 }
378
379 Alarm get(int index) {
380 return alarms.get(index);
381 }
382
383 boolean canHold(long whenElapsed, long maxWhen) {
384 return (end >= whenElapsed) && (start <= maxWhen);
385 }
386
387 boolean add(Alarm alarm) {
388 boolean newStart = false;
389 // narrows the batch if necessary; presumes that canHold(alarm) is true
390 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
391 if (index < 0) {
392 index = 0 - index - 1;
393 }
394 alarms.add(index, alarm);
395 if (DEBUG_BATCH) {
396 Slog.v(TAG, "Adding " + alarm + " to " + this);
397 }
398 if (alarm.whenElapsed > start) {
399 start = alarm.whenElapsed;
400 newStart = true;
401 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700402 if (alarm.maxWhenElapsed < end) {
403 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700404 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700405 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700406
407 if (DEBUG_BATCH) {
408 Slog.v(TAG, " => now " + this);
409 }
410 return newStart;
411 }
412
Christopher Tate14a7bb02015-10-01 10:24:31 -0700413 boolean remove(final PendingIntent operation, final IAlarmListener listener) {
414 if (operation == null && listener == null) {
415 if (localLOGV) {
416 Slog.w(TAG, "requested remove() of null operation",
417 new RuntimeException("here"));
418 }
419 return false;
420 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700421 boolean didRemove = false;
422 long newStart = 0; // recalculate endpoints as we go
423 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700424 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700425 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700426 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700427 if (alarm.matches(operation, listener)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700428 alarms.remove(i);
429 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200430 if (alarm.alarmClock != null) {
431 mNextAlarmClockMayChange = true;
432 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700433 } else {
434 if (alarm.whenElapsed > newStart) {
435 newStart = alarm.whenElapsed;
436 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700437 if (alarm.maxWhenElapsed < newEnd) {
438 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700439 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700440 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700441 i++;
442 }
443 }
444 if (didRemove) {
445 // commit the new batch bounds
446 start = newStart;
447 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700448 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700449 }
450 return didRemove;
451 }
452
453 boolean remove(final String packageName) {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700454 if (packageName == null) {
455 if (localLOGV) {
456 Slog.w(TAG, "requested remove() of null packageName",
457 new RuntimeException("here"));
458 }
459 return false;
460 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700461 boolean didRemove = false;
462 long newStart = 0; // recalculate endpoints as we go
463 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700464 int newFlags = 0;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700465 for (int i = alarms.size()-1; i >= 0; i--) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700466 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700467 if (alarm.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700468 alarms.remove(i);
469 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200470 if (alarm.alarmClock != null) {
471 mNextAlarmClockMayChange = true;
472 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700473 } else {
474 if (alarm.whenElapsed > newStart) {
475 newStart = alarm.whenElapsed;
476 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700477 if (alarm.maxWhenElapsed < newEnd) {
478 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700479 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700480 newFlags |= alarm.flags;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700481 }
482 }
483 if (didRemove) {
484 // commit the new batch bounds
485 start = newStart;
486 end = newEnd;
487 flags = newFlags;
488 }
489 return didRemove;
490 }
491
492 boolean removeForStopped(final int uid) {
493 boolean didRemove = false;
494 long newStart = 0; // recalculate endpoints as we go
495 long newEnd = Long.MAX_VALUE;
496 int newFlags = 0;
497 for (int i = alarms.size()-1; i >= 0; i--) {
498 Alarm alarm = alarms.get(i);
499 try {
500 if (alarm.uid == uid && ActivityManagerNative.getDefault().getAppStartMode(
501 uid, alarm.packageName) == ActivityManager.APP_START_MODE_DISABLED) {
502 alarms.remove(i);
503 didRemove = true;
504 if (alarm.alarmClock != null) {
505 mNextAlarmClockMayChange = true;
506 }
507 } else {
508 if (alarm.whenElapsed > newStart) {
509 newStart = alarm.whenElapsed;
510 }
511 if (alarm.maxWhenElapsed < newEnd) {
512 newEnd = alarm.maxWhenElapsed;
513 }
514 newFlags |= alarm.flags;
515 }
516 } catch (RemoteException e) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700517 }
518 }
519 if (didRemove) {
520 // commit the new batch bounds
521 start = newStart;
522 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700523 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700524 }
525 return didRemove;
526 }
527
528 boolean remove(final int userHandle) {
529 boolean didRemove = false;
530 long newStart = 0; // recalculate endpoints as we go
531 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700532 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700533 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700534 if (UserHandle.getUserId(alarm.creatorUid) == userHandle) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700535 alarms.remove(i);
536 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200537 if (alarm.alarmClock != null) {
538 mNextAlarmClockMayChange = true;
539 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700540 } else {
541 if (alarm.whenElapsed > newStart) {
542 newStart = alarm.whenElapsed;
543 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700544 if (alarm.maxWhenElapsed < newEnd) {
545 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700546 }
547 i++;
548 }
549 }
550 if (didRemove) {
551 // commit the new batch bounds
552 start = newStart;
553 end = newEnd;
554 }
555 return didRemove;
556 }
557
558 boolean hasPackage(final String packageName) {
559 final int N = alarms.size();
560 for (int i = 0; i < N; i++) {
561 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700562 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700563 return true;
564 }
565 }
566 return false;
567 }
568
569 boolean hasWakeups() {
570 final int N = alarms.size();
571 for (int i = 0; i < N; i++) {
572 Alarm a = alarms.get(i);
573 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
574 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
575 return true;
576 }
577 }
578 return false;
579 }
580
581 @Override
582 public String toString() {
583 StringBuilder b = new StringBuilder(40);
584 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
585 b.append(" num="); b.append(size());
586 b.append(" start="); b.append(start);
587 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700588 if (flags != 0) {
589 b.append(" flgs=0x");
590 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700591 }
592 b.append('}');
593 return b.toString();
594 }
595 }
596
597 static class BatchTimeOrder implements Comparator<Batch> {
598 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800599 long when1 = b1.start;
600 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800601 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700602 return 1;
603 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800604 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700605 return -1;
606 }
607 return 0;
608 }
609 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800610
611 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
612 @Override
613 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700614 // priority class trumps everything. TICK < WAKEUP < NORMAL
615 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
616 return -1;
617 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
618 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800619 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700620
621 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800622 if (lhs.whenElapsed < rhs.whenElapsed) {
623 return -1;
624 } else if (lhs.whenElapsed > rhs.whenElapsed) {
625 return 1;
626 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700627
628 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800629 return 0;
630 }
631 };
632
Christopher Tate1590f1e2014-10-02 17:27:57 -0700633 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
634 final int N = alarms.size();
635 for (int i = 0; i < N; i++) {
636 Alarm a = alarms.get(i);
637
638 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700639 if (a.operation != null
640 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700641 alarmPrio = PRIO_TICK;
642 } else if (a.wakeup) {
643 alarmPrio = PRIO_WAKEUP;
644 } else {
645 alarmPrio = PRIO_NORMAL;
646 }
647
648 PriorityClass packagePrio = a.priorityClass;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700649 String alarmPackage = (a.operation != null)
650 ? a.operation.getCreatorPackage()
651 : a.packageName;
652 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700653 if (packagePrio == null) {
654 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700655 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700656 }
657 a.priorityClass = packagePrio;
658
659 if (packagePrio.seq != mCurrentSeq) {
660 // first alarm we've seen in the current delivery generation from this package
661 packagePrio.priority = alarmPrio;
662 packagePrio.seq = mCurrentSeq;
663 } else {
664 // Multiple alarms from this package being delivered in this generation;
665 // bump the package's delivery class if it's warranted.
666 // TICK < WAKEUP < NORMAL
667 if (alarmPrio < packagePrio.priority) {
668 packagePrio.priority = alarmPrio;
669 }
670 }
671 }
672 }
673
Christopher Tatee0a22b32013-07-11 14:43:13 -0700674 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800675 static final long MIN_FUZZABLE_INTERVAL = 10000;
676 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700677 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
678
679 // set to null if in idle mode; while in this mode, any alarms we don't want
680 // to run during this time are placed in mPendingWhileIdleAlarms
681 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700682 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700683 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700684
Jeff Brownb880d882014-02-10 19:47:07 -0800685 public AlarmManagerService(Context context) {
686 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700687 mConstants = new Constants(mHandler);
Jeff Brownb880d882014-02-10 19:47:07 -0800688 }
689
Christopher Tatee0a22b32013-07-11 14:43:13 -0700690 static long convertToElapsed(long when, int type) {
691 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
692 if (isRtc) {
693 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
694 }
695 return when;
696 }
697
698 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
699 // calculate the end of our nominal delivery window for the alarm.
700 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
701 // Current heuristic: batchable window is 75% of either the recurrence interval
702 // [for a periodic alarm] or of the time from now to the desired delivery time,
703 // with a minimum delay/interval of 10 seconds, under which we will simply not
704 // defer the alarm.
705 long futurity = (interval == 0)
706 ? (triggerAtTime - now)
707 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700708 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700709 futurity = 0;
710 }
711 return triggerAtTime + (long)(.75 * futurity);
712 }
713
714 // returns true if the batch was added at the head
715 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
716 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
717 if (index < 0) {
718 index = 0 - index - 1;
719 }
720 list.add(index, newBatch);
721 return (index == 0);
722 }
723
Christopher Tate385e4982013-07-23 18:22:29 -0700724 // Return the index of the matching batch, or -1 if none found.
725 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700726 final int N = mAlarmBatches.size();
727 for (int i = 0; i < N; i++) {
728 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700729 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700730 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700731 }
732 }
Christopher Tate385e4982013-07-23 18:22:29 -0700733 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700734 }
735
736 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
737 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700738 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700739 rebatchAllAlarmsLocked(true);
740 }
741 }
742
743 void rebatchAllAlarmsLocked(boolean doValidate) {
744 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
745 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700746 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700747 final long nowElapsed = SystemClock.elapsedRealtime();
748 final int oldBatches = oldSet.size();
749 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
750 Batch batch = oldSet.get(batchNum);
751 final int N = batch.size();
752 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700753 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700754 }
755 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700756 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
757 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
758 + " to " + mPendingIdleUntil);
759 if (mPendingIdleUntil == null) {
760 // Somehow we lost this... we need to restore all of the pending alarms.
761 restorePendingWhileIdleAlarmsLocked();
762 }
763 }
764 rescheduleKernelAlarmsLocked();
765 updateNextAlarmClockLocked();
766 }
767
768 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
769 a.when = a.origWhen;
770 long whenElapsed = convertToElapsed(a.when, a.type);
771 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700772 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700773 // Exact
774 maxElapsed = whenElapsed;
775 } else {
776 // Not exact. Preserve any explicit window, otherwise recalculate
777 // the window based on the alarm's new futurity. Note that this
778 // reflects a policy of preferring timely to deferred delivery.
779 maxElapsed = (a.windowLength > 0)
780 ? (whenElapsed + a.windowLength)
781 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
782 }
783 a.whenElapsed = whenElapsed;
784 a.maxWhenElapsed = maxElapsed;
785 setImplLocked(a, true, doValidate);
786 }
787
788 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700789 if (RECORD_DEVICE_IDLE_ALARMS) {
790 IdleDispatchEntry ent = new IdleDispatchEntry();
791 ent.uid = 0;
792 ent.pkg = "FINISH IDLE";
793 ent.elapsedRealtime = SystemClock.elapsedRealtime();
794 mAllowWhileIdleDispatches.add(ent);
795 }
796
Dianne Hackborn35d54032015-04-23 10:30:43 -0700797 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700798 if (mPendingWhileIdleAlarms.size() > 0) {
799 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
800 mPendingWhileIdleAlarms = new ArrayList<>();
801 final long nowElapsed = SystemClock.elapsedRealtime();
802 for (int i=alarms.size() - 1; i >= 0; i--) {
803 Alarm a = alarms.get(i);
804 reAddAlarmLocked(a, nowElapsed, false);
805 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700806 }
Dianne Hackborn35d54032015-04-23 10:30:43 -0700807
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700808 // Make sure we are using the correct ALLOW_WHILE_IDLE min time.
Dianne Hackborna750a632015-06-16 17:18:23 -0700809 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700810
Dianne Hackborn35d54032015-04-23 10:30:43 -0700811 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700812 rescheduleKernelAlarmsLocked();
813 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -0700814
815 // And send a TIME_TICK right now, since it is important to get the UI updated.
816 try {
817 mTimeTickSender.send();
818 } catch (PendingIntent.CanceledException e) {
819 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700820 }
821
Christopher Tate14a7bb02015-10-01 10:24:31 -0700822 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -0800823 final PendingIntent mPendingIntent;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700824 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -0700825 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700826 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700827 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800828 final BroadcastStats mBroadcastStats;
829 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800830 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800831
Christopher Tate14a7bb02015-10-01 10:24:31 -0700832 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
833 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
834 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800835 mPendingIntent = pendingIntent;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700836 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -0700837 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700838 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700839 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700840 mBroadcastStats = (pendingIntent != null)
841 ? service.getStatsLocked(pendingIntent)
842 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700843 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -0800844 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700845 fs = new FilterStats(mBroadcastStats, mTag);
846 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -0800847 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700848 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -0800849 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800850 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800853
Adam Lesinski182f73f2013-12-05 16:48:06 -0800854 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -0800855 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700856 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800857
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700858 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800860 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861 int numWakeup;
862 long startTime;
863 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -0800864
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700865 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800866 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700867 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800868 }
869 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700870
Adam Lesinski182f73f2013-12-05 16:48:06 -0800871 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800872 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800873 final String mPackageName;
874
875 long aggregateTime;
876 int count;
877 int numWakeup;
878 long startTime;
879 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700880 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -0800881
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800882 BroadcastStats(int uid, String packageName) {
883 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800884 mPackageName = packageName;
885 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700887
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800888 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
889 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700890
891 int mNumDelayedAlarms = 0;
892 long mTotalDelayTime = 0;
893 long mMaxDelayTime = 0;
894
Adam Lesinski182f73f2013-12-05 16:48:06 -0800895 @Override
896 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800897 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800898 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800899
900 // We have to set current TimeZone info to kernel
901 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -0800902 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800903
Adam Lesinski182f73f2013-12-05 16:48:06 -0800904 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800905 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800906
Adam Lesinski182f73f2013-12-05 16:48:06 -0800907 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700909 Intent.FLAG_RECEIVER_REGISTERED_ONLY
910 | Intent.FLAG_RECEIVER_FOREGROUND), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700911 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800912 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
913 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800914 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700915 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916
917 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -0800918 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 mClockReceiver.scheduleTimeTickEvent();
920 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700921 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 mUninstallReceiver = new UninstallReceiver();
923
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800924 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800925 AlarmThread waitThread = new AlarmThread();
926 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800928 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800930
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700931 try {
932 ActivityManagerNative.getDefault().registerUidObserver(new UidObserver(),
933 ActivityManager.UID_OBSERVER_IDLE);
934 } catch (RemoteException e) {
935 // ignored; both services live in system_server
936 }
937
Adam Lesinski182f73f2013-12-05 16:48:06 -0800938 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800939 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800940
941 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -0700942 public void onBootPhase(int phase) {
943 if (phase == PHASE_SYSTEM_SERVICES_READY) {
944 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -0700945 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800946 mLocalDeviceIdleController
947 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackborna750a632015-06-16 17:18:23 -0700948 }
949 }
950
951 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 protected void finalize() throws Throwable {
953 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800954 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 } finally {
956 super.finalize();
957 }
958 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700959
Adam Lesinski182f73f2013-12-05 16:48:06 -0800960 void setTimeZoneImpl(String tz) {
961 if (TextUtils.isEmpty(tz)) {
962 return;
David Christieebe51fc2013-07-26 13:23:29 -0700963 }
964
Adam Lesinski182f73f2013-12-05 16:48:06 -0800965 TimeZone zone = TimeZone.getTimeZone(tz);
966 // Prevent reentrant calls from stepping on each other when writing
967 // the time zone property
968 boolean timeZoneWasChanged = false;
969 synchronized (this) {
970 String current = SystemProperties.get(TIMEZONE_PROPERTY);
971 if (current == null || !current.equals(zone.getID())) {
972 if (localLOGV) {
973 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
974 }
975 timeZoneWasChanged = true;
976 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
977 }
978
979 // Update the kernel timezone information
980 // Kernel tracks time offsets as 'minutes west of GMT'
981 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800982 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -0800983 }
984
985 TimeZone.setDefault(null);
986
987 if (timeZoneWasChanged) {
988 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
989 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
990 intent.putExtra("time-zone", zone.getID());
991 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
992 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700994
Adam Lesinski182f73f2013-12-05 16:48:06 -0800995 void removeImpl(PendingIntent operation) {
996 if (operation == null) {
997 return;
998 }
999 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001000 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001001 }
1002 }
1003
1004 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001005 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1006 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1007 int callingUid, String callingPackage) {
1008 // must be *either* PendingIntent or AlarmReceiver, but not both
1009 if ((operation == null && directReceiver == null)
1010 || (operation != null && directReceiver != null)) {
1011 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1012 // NB: previous releases failed silently here, so we are continuing to do the same
1013 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014 return;
1015 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001016
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001017 // Sanity check the window length. This will catch people mistakenly
1018 // trying to pass an end-of-window timestamp rather than a duration.
1019 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1020 Slog.w(TAG, "Window length " + windowLength
1021 + "ms suspiciously long; limiting to 1 hour");
1022 windowLength = AlarmManager.INTERVAL_HOUR;
1023 }
1024
Christopher Tate498c6cb2014-11-17 16:09:27 -08001025 // Sanity check the recurrence interval. This will catch people who supply
1026 // seconds when the API expects milliseconds.
Dianne Hackborna750a632015-06-16 17:18:23 -07001027 final long minInterval = mConstants.MIN_INTERVAL;
1028 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001029 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001030 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001031 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001032 interval = minInterval;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001033 }
1034
Christopher Tatee0a22b32013-07-11 14:43:13 -07001035 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1036 throw new IllegalArgumentException("Invalid alarm type " + type);
1037 }
1038
Christopher Tate5f221e82013-07-30 17:13:15 -07001039 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001040 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001041 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001042 + " pid=" + what);
1043 triggerAtTime = 0;
1044 }
1045
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001046 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001047 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1048 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001049 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001050 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1051
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001052 final long maxElapsed;
1053 if (windowLength == AlarmManager.WINDOW_EXACT) {
1054 maxElapsed = triggerElapsed;
1055 } else if (windowLength < 0) {
1056 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001057 // Fix this window in place, so that as time approaches we don't collapse it.
1058 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001059 } else {
1060 maxElapsed = triggerElapsed + windowLength;
1061 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001064 if (DEBUG_BATCH) {
1065 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001066 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001067 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001068 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001070 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001071 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1072 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 }
1074 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075
Christopher Tate3e04b472013-10-21 17:51:31 -07001076 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001077 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1078 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1079 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001080 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001081 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1082 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001083 try {
1084 if (ActivityManagerNative.getDefault().getAppStartMode(callingUid, callingPackage)
1085 == ActivityManager.APP_START_MODE_DISABLED) {
1086 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1087 + " -- package not allowed to start");
1088 return;
1089 }
1090 } catch (RemoteException e) {
1091 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001092 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001093 setImplLocked(a, false, doValidate);
1094 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001095
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001096 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1097 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001098 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001099 // The caller has given the time they want this to happen at, however we need
1100 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001101 // bring us out of idle at an earlier time.
1102 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001103 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001104 }
1105 // Add fuzz to make the alarm go off some time before the actual desired time.
1106 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001107 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001108 if (fuzz > 0) {
1109 if (mRandom == null) {
1110 mRandom = new Random();
1111 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001112 final int delta = mRandom.nextInt(fuzz);
1113 a.whenElapsed -= delta;
1114 if (false) {
1115 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1116 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1117 Slog.d(TAG, "Applied fuzz: " + fuzz);
1118 Slog.d(TAG, "Final delta: " + delta);
1119 Slog.d(TAG, "Final when: " + a.whenElapsed);
1120 }
1121 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001122 }
1123
1124 } else if (mPendingIdleUntil != null) {
1125 // We currently have an idle until alarm scheduled; if the new alarm has
1126 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001127 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1128 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1129 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001130 == 0) {
1131 mPendingWhileIdleAlarms.add(a);
1132 return;
1133 }
1134 }
1135
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001136 if (RECORD_DEVICE_IDLE_ALARMS) {
1137 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1138 IdleDispatchEntry ent = new IdleDispatchEntry();
1139 ent.uid = a.uid;
1140 ent.pkg = a.operation.getCreatorPackage();
1141 ent.tag = a.operation.getTag("");
1142 ent.op = "SET";
1143 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1144 ent.argRealtime = a.whenElapsed;
1145 mAllowWhileIdleDispatches.add(ent);
1146 }
1147 }
1148
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001149 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
1150 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -07001151 if (whichBatch < 0) {
1152 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001153 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 } else {
Christopher Tate385e4982013-07-23 18:22:29 -07001155 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001156 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001157 // The start time of this batch advanced, so batch ordering may
1158 // have just been broken. Move it to where it now belongs.
1159 mAlarmBatches.remove(whichBatch);
1160 addBatchLocked(mAlarmBatches, batch);
1161 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162 }
1163
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001164 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001165 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001166 }
1167
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001168 boolean needRebatch = false;
1169
1170 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001171 if (RECORD_DEVICE_IDLE_ALARMS) {
1172 if (mPendingIdleUntil == null) {
1173 IdleDispatchEntry ent = new IdleDispatchEntry();
1174 ent.uid = 0;
1175 ent.pkg = "START IDLE";
1176 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1177 mAllowWhileIdleDispatches.add(ent);
1178 }
1179 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001180 mPendingIdleUntil = a;
Dianne Hackborna750a632015-06-16 17:18:23 -07001181 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001182 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001183 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1184 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1185 mNextWakeFromIdle = a;
1186 // If this wake from idle is earlier than whatever was previously scheduled,
1187 // and we are currently idling, then we need to rebatch alarms in case the idle
1188 // until time needs to be updated.
1189 if (mPendingIdleUntil != null) {
1190 needRebatch = true;
1191 }
1192 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001193 }
1194
1195 if (!rebatching) {
1196 if (DEBUG_VALIDATE) {
1197 if (doValidate && !validateConsistencyLocked()) {
1198 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1199 + " when(hex)=" + Long.toHexString(a.when)
1200 + " whenElapsed=" + a.whenElapsed
1201 + " maxWhenElapsed=" + a.maxWhenElapsed
1202 + " interval=" + a.repeatInterval + " op=" + a.operation
1203 + " flags=0x" + Integer.toHexString(a.flags));
1204 rebatchAllAlarmsLocked(false);
1205 needRebatch = false;
1206 }
1207 }
1208
1209 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001210 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001211 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001212
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001213 rescheduleKernelAlarmsLocked();
1214 updateNextAlarmClockLocked();
1215 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001216 }
1217
Adam Lesinski182f73f2013-12-05 16:48:06 -08001218 private final IBinder mService = new IAlarmManager.Stub() {
1219 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001220 public void set(String callingPackage,
1221 int type, long triggerAtTime, long windowLength, long interval, int flags,
1222 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1223 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001224 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001225
1226 // make sure the caller is not lying about which package should be blamed for
1227 // wakelock time spent in alarm delivery
1228 mAppOps.checkPackage(callingUid, callingPackage);
1229
1230 // Repeating alarms must use PendingIntent, not direct listener
1231 if (interval != 0) {
1232 if (directReceiver != null) {
1233 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1234 }
1235 }
1236
Adam Lesinski182f73f2013-12-05 16:48:06 -08001237 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001238 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001239 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001240 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001241 }
1242
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001243 // No incoming callers can request either WAKE_FROM_IDLE or
1244 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1245 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1246 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1247
1248 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1249 // manager when to come out of idle mode, which is only for DeviceIdleController.
1250 if (callingUid != Process.SYSTEM_UID) {
1251 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1252 }
1253
1254 // If the caller is a core system component, and not calling to do work on behalf
1255 // of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED. This means we
1256 // will allow these alarms to go off as normal even while idle, with no timing
1257 // restrictions.
1258 if (callingUid < Process.FIRST_APPLICATION_UID && workSource == null) {
1259 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1260 }
1261
1262 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001263 if (windowLength == AlarmManager.WINDOW_EXACT) {
1264 flags |= AlarmManager.FLAG_STANDALONE;
1265 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001266
1267 // If this alarm is for an alarm clock, then it must be standalone and we will
1268 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001269 if (alarmClock != null) {
1270 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
1271 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001272
Christopher Tate14a7bb02015-10-01 10:24:31 -07001273 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1274 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001275 }
Christopher Tate89779822012-08-31 14:40:03 -07001276
Adam Lesinski182f73f2013-12-05 16:48:06 -08001277 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001278 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001279 getContext().enforceCallingOrSelfPermission(
1280 "android.permission.SET_TIME",
1281 "setTime");
1282
Greg Hackmann0cab8962014-02-21 16:35:52 -08001283 if (mNativeData == 0) {
1284 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1285 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001286 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001287
1288 synchronized (mLock) {
1289 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001292
1293 @Override
1294 public void setTimeZone(String tz) {
1295 getContext().enforceCallingOrSelfPermission(
1296 "android.permission.SET_TIME_ZONE",
1297 "setTimeZone");
1298
1299 final long oldId = Binder.clearCallingIdentity();
1300 try {
1301 setTimeZoneImpl(tz);
1302 } finally {
1303 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 }
1305 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001306
Adam Lesinski182f73f2013-12-05 16:48:06 -08001307 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001308 public void remove(PendingIntent operation, IAlarmListener listener) {
1309 if (operation == null && listener == null) {
1310 Slog.w(TAG, "remove() with no intent or listener");
1311 return;
1312 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001313
Christopher Tate14a7bb02015-10-01 10:24:31 -07001314 synchronized (mLock) {
1315 removeLocked(operation, listener);
1316 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001318
Adam Lesinski182f73f2013-12-05 16:48:06 -08001319 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001320 public long getNextWakeFromIdleTime() {
1321 return getNextWakeFromIdleTimeImpl();
1322 }
1323
1324 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001325 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001326 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1327 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1328 "getNextAlarmClock", null);
1329
1330 return getNextAlarmClockImpl(userId);
1331 }
1332
1333 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001334 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1335 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1336 != PackageManager.PERMISSION_GRANTED) {
1337 pw.println("Permission Denial: can't dump AlarmManager from from pid="
1338 + Binder.getCallingPid()
1339 + ", uid=" + Binder.getCallingUid());
1340 return;
Christopher Tate4cb338d2013-07-26 13:11:31 -07001341 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001342
Adam Lesinski182f73f2013-12-05 16:48:06 -08001343 dumpImpl(pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001344 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001345 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001346
Adam Lesinski182f73f2013-12-05 16:48:06 -08001347 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348 synchronized (mLock) {
1349 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001350 mConstants.dump(pw);
1351 pw.println();
1352
Christopher Tatee0a22b32013-07-11 14:43:13 -07001353 final long nowRTC = System.currentTimeMillis();
1354 final long nowELAPSED = SystemClock.elapsedRealtime();
1355 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1356
Dianne Hackborna750a632015-06-16 17:18:23 -07001357 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001358 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001359 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001360 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001361 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001362 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001363 pw.print(" mLastTimeChangeRealtime=");
Dianne Hackbornc3527222015-05-13 14:03:20 -07001364 TimeUtils.formatDuration(mLastTimeChangeRealtime, pw);
1365 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001366 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001367 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001368 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1369 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001370 pw.print(" Max wakeup delay: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001371 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1372 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001373 pw.print(" Time since last dispatch: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001374 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1375 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001376 pw.print(" Next non-wakeup delivery time: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001377 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1378 pw.println();
1379 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001380
1381 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1382 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001383 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001384 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001385 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001386 pw.print(" Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001387 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001388 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001389
John Spurlock604a5ee2015-06-01 12:27:22 -04001390 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001391 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001392 final TreeSet<Integer> users = new TreeSet<>();
1393 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1394 users.add(mNextAlarmClockForUser.keyAt(i));
1395 }
1396 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1397 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1398 }
1399 for (int user : users) {
1400 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1401 final long time = next != null ? next.getTriggerTime() : 0;
1402 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001403 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001404 pw.print(" pendingSend:"); pw.print(pendingSend);
1405 pw.print(" time:"); pw.print(time);
1406 if (time > 0) {
1407 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1408 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1409 }
1410 pw.println();
1411 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001412 if (mAlarmBatches.size() > 0) {
1413 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001414 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001415 pw.println(mAlarmBatches.size());
1416 for (Batch b : mAlarmBatches) {
1417 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001418 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001421 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001422 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001423 pw.println(" Idle mode state:");
1424 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001425 if (mPendingIdleUntil != null) {
1426 pw.println(mPendingIdleUntil);
Dianne Hackbornf3831292015-10-15 14:51:06 -07001427 mPendingIdleUntil.dump(pw, " ", nowRTC, nowELAPSED, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001428 } else {
1429 pw.println("null");
1430 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001431 pw.println(" Pending alarms:");
1432 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001433 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001434 if (mNextWakeFromIdle != null) {
1435 pw.println();
1436 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
1437 mNextWakeFromIdle.dump(pw, " ", nowRTC, nowELAPSED, sdf);
1438 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001439
1440 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001441 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001442 if (mPendingNonWakeupAlarms.size() > 0) {
1443 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001444 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001445 } else {
1446 pw.println("(none)");
1447 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001448 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001449 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1450 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001451 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001452 pw.print(", max non-interactive time: ");
1453 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1454 pw.println();
1455
1456 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001457 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001458 pw.println();
1459
Christopher Tate7f2a0352015-12-08 10:24:33 -08001460 if (mInFlight.size() > 0) {
1461 pw.println("Outstanding deliveries:");
1462 for (int i = 0; i < mInFlight.size(); i++) {
1463 pw.print(" #"); pw.print(i); pw.print(": ");
1464 pw.println(mInFlight.get(i));
1465 }
1466 pw.println();
1467 }
1468
Dianne Hackborna750a632015-06-16 17:18:23 -07001469 pw.print(" mAllowWhileIdleMinTime=");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001470 TimeUtils.formatDuration(mAllowWhileIdleMinTime, pw);
1471 pw.println();
1472 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001473 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001474 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
1475 pw.print(" UID ");
1476 UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
1477 pw.print(": ");
1478 TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i),
1479 nowELAPSED, pw);
1480 pw.println();
1481 }
1482 }
1483 pw.println();
1484
Dianne Hackborn81038902012-11-26 17:04:09 -08001485 if (mLog.dump(pw, " Recent problems", " ")) {
1486 pw.println();
1487 }
1488
1489 final FilterStats[] topFilters = new FilterStats[10];
1490 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1491 @Override
1492 public int compare(FilterStats lhs, FilterStats rhs) {
1493 if (lhs.aggregateTime < rhs.aggregateTime) {
1494 return 1;
1495 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1496 return -1;
1497 }
1498 return 0;
1499 }
1500 };
1501 int len = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001502 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1503 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1504 for (int ip=0; ip<uidStats.size(); ip++) {
1505 BroadcastStats bs = uidStats.valueAt(ip);
1506 for (int is=0; is<bs.filterStats.size(); is++) {
1507 FilterStats fs = bs.filterStats.valueAt(is);
1508 int pos = len > 0
1509 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1510 if (pos < 0) {
1511 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001512 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001513 if (pos < topFilters.length) {
1514 int copylen = topFilters.length - pos - 1;
1515 if (copylen > 0) {
1516 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1517 }
1518 topFilters[pos] = fs;
1519 if (len < topFilters.length) {
1520 len++;
1521 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001522 }
1523 }
1524 }
1525 }
1526 if (len > 0) {
1527 pw.println(" Top Alarms:");
1528 for (int i=0; i<len; i++) {
1529 FilterStats fs = topFilters[i];
1530 pw.print(" ");
1531 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1532 TimeUtils.formatDuration(fs.aggregateTime, pw);
1533 pw.print(" running, "); pw.print(fs.numWakeup);
1534 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001535 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1536 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001537 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001538 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001539 pw.println();
1540 }
1541 }
1542
1543 pw.println(" ");
1544 pw.println(" Alarm Stats:");
1545 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001546 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1547 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1548 for (int ip=0; ip<uidStats.size(); ip++) {
1549 BroadcastStats bs = uidStats.valueAt(ip);
1550 pw.print(" ");
1551 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1552 UserHandle.formatUid(pw, bs.mUid);
1553 pw.print(":");
1554 pw.print(bs.mPackageName);
1555 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1556 pw.print(" running, "); pw.print(bs.numWakeup);
1557 pw.println(" wakeups:");
1558 tmpFilters.clear();
1559 for (int is=0; is<bs.filterStats.size(); is++) {
1560 tmpFilters.add(bs.filterStats.valueAt(is));
1561 }
1562 Collections.sort(tmpFilters, comparator);
1563 for (int i=0; i<tmpFilters.size(); i++) {
1564 FilterStats fs = tmpFilters.get(i);
1565 pw.print(" ");
1566 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1567 TimeUtils.formatDuration(fs.aggregateTime, pw);
1568 pw.print(" "); pw.print(fs.numWakeup);
1569 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001570 pw.print(" alarms, last ");
1571 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1572 pw.println(":");
1573 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001574 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001575 pw.println();
1576 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 }
1578 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001579
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001580 if (RECORD_DEVICE_IDLE_ALARMS) {
1581 pw.println();
1582 pw.println(" Allow while idle dispatches:");
1583 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
1584 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
1585 pw.print(" ");
1586 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
1587 pw.print(": ");
1588 UserHandle.formatUid(pw, ent.uid);
1589 pw.print(":");
1590 pw.println(ent.pkg);
1591 if (ent.op != null) {
1592 pw.print(" ");
1593 pw.print(ent.op);
1594 pw.print(" / ");
1595 pw.print(ent.tag);
1596 if (ent.argRealtime != 0) {
1597 pw.print(" (");
1598 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
1599 pw.print(")");
1600 }
1601 pw.println();
1602 }
1603 }
1604 }
1605
Christopher Tate18a75f12013-07-01 18:18:59 -07001606 if (WAKEUP_STATS) {
1607 pw.println();
1608 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001609 long last = -1;
1610 for (WakeupEvent event : mRecentWakeups) {
1611 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1612 pw.print('|');
1613 if (last < 0) {
1614 pw.print('0');
1615 } else {
1616 pw.print(event.when - last);
1617 }
1618 last = event.when;
1619 pw.print('|'); pw.print(event.uid);
1620 pw.print('|'); pw.print(event.action);
1621 pw.println();
1622 }
1623 pw.println();
1624 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 }
1626 }
1627
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001628 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001629 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
1630 PrintWriter pw = new PrintWriter(bs);
1631 final long nowRTC = System.currentTimeMillis();
1632 final long nowELAPSED = SystemClock.elapsedRealtime();
1633 final int NZ = mAlarmBatches.size();
1634 for (int iz = 0; iz < NZ; iz++) {
1635 Batch bz = mAlarmBatches.get(iz);
1636 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001637 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001638 pw.flush();
1639 Slog.v(TAG, bs.toString());
1640 bs.reset();
1641 }
1642 }
1643
1644 private boolean validateConsistencyLocked() {
1645 if (DEBUG_VALIDATE) {
1646 long lastTime = Long.MIN_VALUE;
1647 final int N = mAlarmBatches.size();
1648 for (int i = 0; i < N; i++) {
1649 Batch b = mAlarmBatches.get(i);
1650 if (b.start >= lastTime) {
1651 // duplicate start times are okay because of standalone batches
1652 lastTime = b.start;
1653 } else {
1654 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001655 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1656 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001657 return false;
1658 }
1659 }
1660 }
1661 return true;
1662 }
1663
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001664 private Batch findFirstWakeupBatchLocked() {
1665 final int N = mAlarmBatches.size();
1666 for (int i = 0; i < N; i++) {
1667 Batch b = mAlarmBatches.get(i);
1668 if (b.hasWakeups()) {
1669 return b;
1670 }
1671 }
1672 return null;
1673 }
1674
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001675 long getNextWakeFromIdleTimeImpl() {
1676 synchronized (mLock) {
1677 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
1678 }
1679 }
1680
1681 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001682 synchronized (mLock) {
1683 return mNextAlarmClockForUser.get(userId);
1684 }
1685 }
1686
1687 /**
1688 * Recomputes the next alarm clock for all users.
1689 */
1690 private void updateNextAlarmClockLocked() {
1691 if (!mNextAlarmClockMayChange) {
1692 return;
1693 }
1694 mNextAlarmClockMayChange = false;
1695
Jose Lima235510e2014-08-13 12:50:01 -07001696 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001697 nextForUser.clear();
1698
1699 final int N = mAlarmBatches.size();
1700 for (int i = 0; i < N; i++) {
1701 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
1702 final int M = alarms.size();
1703
1704 for (int j = 0; j < M; j++) {
1705 Alarm a = alarms.get(j);
1706 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001707 final int userId = UserHandle.getUserId(a.uid);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001708
1709 if (DEBUG_ALARM_CLOCK) {
1710 Log.v(TAG, "Found AlarmClockInfo at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001711 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02001712 " for user " + userId);
1713 }
1714
1715 // Alarms and batches are sorted by time, no need to compare times here.
1716 if (nextForUser.get(userId) == null) {
1717 nextForUser.put(userId, a.alarmClock);
1718 }
1719 }
1720 }
1721 }
1722
1723 // Update mNextAlarmForUser with new values.
1724 final int NN = nextForUser.size();
1725 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07001726 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001727 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001728 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001729 if (!newAlarm.equals(currentAlarm)) {
1730 updateNextAlarmInfoForUserLocked(userId, newAlarm);
1731 }
1732 }
1733
1734 // Remove users without any alarm clocks scheduled.
1735 final int NNN = mNextAlarmClockForUser.size();
1736 for (int i = NNN - 1; i >= 0; i--) {
1737 int userId = mNextAlarmClockForUser.keyAt(i);
1738 if (nextForUser.get(userId) == null) {
1739 updateNextAlarmInfoForUserLocked(userId, null);
1740 }
1741 }
1742 }
1743
Jose Lima235510e2014-08-13 12:50:01 -07001744 private void updateNextAlarmInfoForUserLocked(int userId,
1745 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001746 if (alarmClock != null) {
1747 if (DEBUG_ALARM_CLOCK) {
1748 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001749 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02001750 }
1751 mNextAlarmClockForUser.put(userId, alarmClock);
1752 } else {
1753 if (DEBUG_ALARM_CLOCK) {
1754 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
1755 }
1756 mNextAlarmClockForUser.remove(userId);
1757 }
1758
1759 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
1760 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1761 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1762 }
1763
1764 /**
1765 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
1766 * for which alarm clocks have changed since the last call to this.
1767 *
1768 * Do not call with a lock held. Only call from mHandler's thread.
1769 *
1770 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
1771 */
1772 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07001773 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001774 pendingUsers.clear();
1775
1776 synchronized (mLock) {
1777 final int N = mPendingSendNextAlarmClockChangedForUser.size();
1778 for (int i = 0; i < N; i++) {
1779 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
1780 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
1781 }
1782 mPendingSendNextAlarmClockChangedForUser.clear();
1783 }
1784
1785 final int N = pendingUsers.size();
1786 for (int i = 0; i < N; i++) {
1787 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001788 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001789 Settings.System.putStringForUser(getContext().getContentResolver(),
1790 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01001791 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02001792 userId);
1793
1794 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
1795 new UserHandle(userId));
1796 }
1797 }
1798
1799 /**
1800 * Formats an alarm like platform/packages/apps/DeskClock used to.
1801 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01001802 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
1803 int userId) {
1804 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02001805 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
1806 return (info == null) ? "" :
1807 DateFormat.format(pattern, info.getTriggerTime()).toString();
1808 }
1809
Adam Lesinski182f73f2013-12-05 16:48:06 -08001810 void rescheduleKernelAlarmsLocked() {
1811 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
1812 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001813 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001814 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001815 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001816 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07001817 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001818 mNextWakeup = firstWakeup.start;
1819 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001820 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001821 if (firstBatch != firstWakeup) {
1822 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001823 }
1824 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001825 if (mPendingNonWakeupAlarms.size() > 0) {
1826 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
1827 nextNonWakeup = mNextNonWakeupDeliveryTime;
1828 }
1829 }
Prashant Malani753e9e02015-06-10 17:43:49 -07001830 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001831 mNextNonWakeup = nextNonWakeup;
1832 setLocked(ELAPSED_REALTIME, nextNonWakeup);
1833 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001834 }
1835
Christopher Tate14a7bb02015-10-01 10:24:31 -07001836 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001837 boolean didRemove = false;
1838 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1839 Batch b = mAlarmBatches.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -07001840 didRemove |= b.remove(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001841 if (b.size() == 0) {
1842 mAlarmBatches.remove(i);
1843 }
1844 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001845 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001846 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001847 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1848 mPendingWhileIdleAlarms.remove(i);
1849 }
1850 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001851
1852 if (didRemove) {
1853 if (DEBUG_BATCH) {
1854 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
1855 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001856 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001857 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001858 mPendingIdleUntil = null;
1859 restorePending = true;
1860 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001861 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001862 mNextWakeFromIdle = null;
1863 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001864 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001865 if (restorePending) {
1866 restorePendingWhileIdleAlarmsLocked();
1867 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001868 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001869 }
1870 }
1871
1872 void removeLocked(String packageName) {
1873 boolean didRemove = false;
1874 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1875 Batch b = mAlarmBatches.get(i);
1876 didRemove |= b.remove(packageName);
1877 if (b.size() == 0) {
1878 mAlarmBatches.remove(i);
1879 }
1880 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001881 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001882 final Alarm a = mPendingWhileIdleAlarms.get(i);
1883 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001884 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1885 mPendingWhileIdleAlarms.remove(i);
1886 }
1887 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001888
1889 if (didRemove) {
1890 if (DEBUG_BATCH) {
1891 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1892 }
1893 rebatchAllAlarmsLocked(true);
1894 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001895 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001896 }
1897 }
1898
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001899 void removeForStoppedLocked(int uid) {
1900 boolean didRemove = false;
1901 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1902 Batch b = mAlarmBatches.get(i);
1903 didRemove |= b.removeForStopped(uid);
1904 if (b.size() == 0) {
1905 mAlarmBatches.remove(i);
1906 }
1907 }
1908 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1909 final Alarm a = mPendingWhileIdleAlarms.get(i);
1910 try {
1911 if (a.uid == uid && ActivityManagerNative.getDefault().getAppStartMode(
1912 uid, a.packageName) == ActivityManager.APP_START_MODE_DISABLED) {
1913 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1914 mPendingWhileIdleAlarms.remove(i);
1915 }
1916 } catch (RemoteException e) {
1917 }
1918 }
1919
1920 if (didRemove) {
1921 if (DEBUG_BATCH) {
1922 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1923 }
1924 rebatchAllAlarmsLocked(true);
1925 rescheduleKernelAlarmsLocked();
1926 updateNextAlarmClockLocked();
1927 }
1928 }
1929
Adam Lesinski182f73f2013-12-05 16:48:06 -08001930 void removeUserLocked(int userHandle) {
1931 boolean didRemove = false;
1932 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1933 Batch b = mAlarmBatches.get(i);
1934 didRemove |= b.remove(userHandle);
1935 if (b.size() == 0) {
1936 mAlarmBatches.remove(i);
1937 }
1938 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001939 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001940 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001941 == userHandle) {
1942 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1943 mPendingWhileIdleAlarms.remove(i);
1944 }
1945 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001946 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
1947 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
1948 mLastAllowWhileIdleDispatch.removeAt(i);
1949 }
1950 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001951
1952 if (didRemove) {
1953 if (DEBUG_BATCH) {
1954 Slog.v(TAG, "remove(user) changed bounds; rebatching");
1955 }
1956 rebatchAllAlarmsLocked(true);
1957 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001958 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001959 }
1960 }
1961
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001962 void interactiveStateChangedLocked(boolean interactive) {
1963 if (mInteractive != interactive) {
1964 mInteractive = interactive;
1965 final long nowELAPSED = SystemClock.elapsedRealtime();
1966 if (interactive) {
1967 if (mPendingNonWakeupAlarms.size() > 0) {
1968 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1969 mTotalDelayTime += thisDelayTime;
1970 if (mMaxDelayTime < thisDelayTime) {
1971 mMaxDelayTime = thisDelayTime;
1972 }
1973 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
1974 mPendingNonWakeupAlarms.clear();
1975 }
1976 if (mNonInteractiveStartTime > 0) {
1977 long dur = nowELAPSED - mNonInteractiveStartTime;
1978 if (dur > mNonInteractiveTime) {
1979 mNonInteractiveTime = dur;
1980 }
1981 }
1982 } else {
1983 mNonInteractiveStartTime = nowELAPSED;
1984 }
1985 }
1986 }
1987
Adam Lesinski182f73f2013-12-05 16:48:06 -08001988 boolean lookForPackageLocked(String packageName) {
1989 for (int i = 0; i < mAlarmBatches.size(); i++) {
1990 Batch b = mAlarmBatches.get(i);
1991 if (b.hasPackage(packageName)) {
1992 return true;
1993 }
1994 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001995 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001996 final Alarm a = mPendingWhileIdleAlarms.get(i);
1997 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001998 return true;
1999 }
2000 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002001 return false;
2002 }
2003
2004 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002005 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002006 // The kernel never triggers alarms with negative wakeup times
2007 // so we ensure they are positive.
2008 long alarmSeconds, alarmNanoseconds;
2009 if (when < 0) {
2010 alarmSeconds = 0;
2011 alarmNanoseconds = 0;
2012 } else {
2013 alarmSeconds = when / 1000;
2014 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2015 }
2016
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002017 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002018 } else {
2019 Message msg = Message.obtain();
2020 msg.what = ALARM_EVENT;
2021
2022 mHandler.removeMessages(ALARM_EVENT);
2023 mHandler.sendMessageAtTime(msg, when);
2024 }
2025 }
2026
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002027 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002028 String prefix, String label, long nowRTC, long nowELAPSED, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002029 for (int i=list.size()-1; i>=0; i--) {
2030 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002031 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2032 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002033 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002034 }
2035 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002036
2037 private static final String labelForType(int type) {
2038 switch (type) {
2039 case RTC: return "RTC";
2040 case RTC_WAKEUP : return "RTC_WAKEUP";
2041 case ELAPSED_REALTIME : return "ELAPSED";
2042 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
2043 default:
2044 break;
2045 }
2046 return "--unknown--";
2047 }
2048
2049 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002050 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002051 for (int i=list.size()-1; i>=0; i--) {
2052 Alarm a = list.get(i);
2053 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002054 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2055 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002056 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002057 }
2058 }
2059
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002060 private native long init();
2061 private native void close(long nativeData);
2062 private native void set(long nativeData, int type, long seconds, long nanoseconds);
2063 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08002064 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002065 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002066
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002067 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002068 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002069 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002070 // batches are temporally sorted, so we need only pull from the
2071 // start of the list until we either empty it or hit a batch
2072 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07002073 while (mAlarmBatches.size() > 0) {
2074 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002075 if (batch.start > nowELAPSED) {
2076 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002077 break;
2078 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079
Christopher Tatee0a22b32013-07-11 14:43:13 -07002080 // We will (re)schedule some alarms now; don't let that interfere
2081 // with delivery of this current batch
2082 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002083
Christopher Tatee0a22b32013-07-11 14:43:13 -07002084 final int N = batch.size();
2085 for (int i = 0; i < N; i++) {
2086 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002087
2088 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
2089 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
2090 // schedule such alarms.
2091 long lastTime = mLastAllowWhileIdleDispatch.get(alarm.uid, 0);
2092 long minTime = lastTime + mAllowWhileIdleMinTime;
2093 if (nowELAPSED < minTime) {
2094 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
2095 // alarm went off for this app. Reschedule the alarm to be in the
2096 // correct time period.
2097 alarm.whenElapsed = minTime;
2098 if (alarm.maxWhenElapsed < minTime) {
2099 alarm.maxWhenElapsed = minTime;
2100 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002101 if (RECORD_DEVICE_IDLE_ALARMS) {
2102 IdleDispatchEntry ent = new IdleDispatchEntry();
2103 ent.uid = alarm.uid;
2104 ent.pkg = alarm.operation.getCreatorPackage();
2105 ent.tag = alarm.operation.getTag("");
2106 ent.op = "RESCHEDULE";
2107 ent.elapsedRealtime = nowELAPSED;
2108 ent.argRealtime = lastTime;
2109 mAllowWhileIdleDispatches.add(ent);
2110 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002111 setImplLocked(alarm, true, false);
2112 continue;
2113 }
2114 }
2115
Christopher Tatee0a22b32013-07-11 14:43:13 -07002116 alarm.count = 1;
2117 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002118 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
2119 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002120 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002121 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002122 if (mPendingIdleUntil == alarm) {
2123 mPendingIdleUntil = null;
2124 rebatchAllAlarmsLocked(false);
2125 restorePendingWhileIdleAlarmsLocked();
2126 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002127 if (mNextWakeFromIdle == alarm) {
2128 mNextWakeFromIdle = null;
2129 rebatchAllAlarmsLocked(false);
2130 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002131
2132 // Recurring alarms may have passed several alarm intervals while the
2133 // phone was asleep or off, so pass a trigger count when sending them.
2134 if (alarm.repeatInterval > 0) {
2135 // this adjustment will be zero if we're late by
2136 // less than one full repeat interval
2137 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
2138
2139 // Also schedule its next recurrence
2140 final long delta = alarm.count * alarm.repeatInterval;
2141 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07002142 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07002143 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07002144 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
2145 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08002146 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002147
Christopher Tate864d42e2014-12-02 11:48:53 -08002148 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002149 hasWakeup = true;
2150 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002151
2152 // We removed an alarm clock. Let the caller recompute the next alarm clock.
2153 if (alarm.alarmClock != null) {
2154 mNextAlarmClockMayChange = true;
2155 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07002156 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002157 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002158
Christopher Tate1590f1e2014-10-02 17:27:57 -07002159 // This is a new alarm delivery set; bump the sequence number to indicate that
2160 // all apps' alarm delivery classes should be recalculated.
2161 mCurrentSeq++;
2162 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002163 Collections.sort(triggerList, mAlarmDispatchComparator);
2164
2165 if (localLOGV) {
2166 for (int i=0; i<triggerList.size(); i++) {
2167 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
2168 }
2169 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002170
2171 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002172 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002173
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002174 /**
2175 * This Comparator sorts Alarms into increasing time order.
2176 */
2177 public static class IncreasingTimeOrder implements Comparator<Alarm> {
2178 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09002179 long when1 = a1.whenElapsed;
2180 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002181 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002182 return 1;
2183 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002184 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002185 return -1;
2186 }
2187 return 0;
2188 }
2189 }
2190
2191 private static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002192 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002193 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002194 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002195 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002196 public final IAlarmListener listener;
2197 public final String listenerTag;
2198 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002199 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002200 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002201 public final AlarmManager.AlarmClockInfo alarmClock;
2202 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002203 public final int creatorUid;
2204 public final String packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002205 public int count;
2206 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07002207 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002208 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002209 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002210 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07002211 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002212
Christopher Tate3e04b472013-10-21 17:51:31 -07002213 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002214 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
2215 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
2216 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002217 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002218 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002219 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
2220 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002221 when = _when;
2222 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07002223 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002224 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002225 repeatInterval = _interval;
2226 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002227 listener = _rec;
2228 listenerTag = _listenerTag;
2229 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07002230 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002231 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002232 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002233 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002234 packageName = _pkgName;
2235
2236 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002237 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002238
Christopher Tate14a7bb02015-10-01 10:24:31 -07002239 public static String makeTag(PendingIntent pi, String tag, int type) {
2240 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
2241 ? "*walarm*:" : "*alarm*:";
2242 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
2243 }
2244
2245 public WakeupEvent makeWakeupEvent(long nowRTC) {
2246 return new WakeupEvent(nowRTC, creatorUid,
2247 (operation != null)
2248 ? operation.getIntent().getAction()
2249 : ("<listener>:" + listenerTag));
2250 }
2251
2252 // Returns true if either matches
2253 public boolean matches(PendingIntent pi, IAlarmListener rec) {
2254 return (operation != null)
2255 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09002256 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07002257 }
2258
2259 public boolean matches(String packageName) {
2260 return (operation != null)
2261 ? packageName.equals(operation.getTargetPackage())
2262 : packageName.equals(this.packageName);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002263 }
2264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002265 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002266 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002267 StringBuilder sb = new StringBuilder(128);
2268 sb.append("Alarm{");
2269 sb.append(Integer.toHexString(System.identityHashCode(this)));
2270 sb.append(" type ");
2271 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002272 sb.append(" when ");
2273 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002274 sb.append(" ");
Christopher Tate14a7bb02015-10-01 10:24:31 -07002275 if (operation != null) {
2276 sb.append(operation.getTargetPackage());
2277 } else {
2278 sb.append(listener.asBinder().toString());
2279 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002280 sb.append('}');
2281 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002282 }
2283
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002284 public void dump(PrintWriter pw, String prefix, long nowRTC, long nowELAPSED,
2285 SimpleDateFormat sdf) {
2286 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002287 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002288 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002289 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
2290 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002291 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002292 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002293 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002294 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002295 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002296 }
2297 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002298 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002299 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002300 pw.print(" count="); pw.print(count);
2301 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002302 if (alarmClock != null) {
2303 pw.print(prefix); pw.println("Alarm clock:");
2304 pw.print(prefix); pw.print(" triggerTime=");
2305 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
2306 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
2307 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002308 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002309 if (listener != null) {
2310 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
2311 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002312 }
2313 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002314
Christopher Tatee0a22b32013-07-11 14:43:13 -07002315 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
2316 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002317 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
2318 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002319 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07002320 break;
2321 }
2322
Christopher Tatee0a22b32013-07-11 14:43:13 -07002323 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002324 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
2325 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002326 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07002327 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002328 }
2329 }
2330
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002331 long currentNonWakeupFuzzLocked(long nowELAPSED) {
2332 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
2333 if (timeSinceOn < 5*60*1000) {
2334 // If the screen has been off for 5 minutes, only delay by at most two minutes.
2335 return 2*60*1000;
2336 } else if (timeSinceOn < 30*60*1000) {
2337 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
2338 return 15*60*1000;
2339 } else {
2340 // Otherwise, we will delay by at most an hour.
2341 return 60*60*1000;
2342 }
2343 }
2344
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002345 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002346 if (duration < 15*60*1000) {
2347 // If the duration until the time is less than 15 minutes, the maximum fuzz
2348 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002349 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002350 } else if (duration < 90*60*1000) {
2351 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
2352 return 15*60*1000;
2353 } else {
2354 // Otherwise, we will fuzz by at most half an hour.
2355 return 30*60*1000;
2356 }
2357 }
2358
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002359 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
2360 if (mInteractive) {
2361 return false;
2362 }
2363 if (mLastAlarmDeliveryTime <= 0) {
2364 return false;
2365 }
minho.choo649acab2014-12-12 16:13:55 +09002366 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002367 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
2368 // and the next delivery time is in the past, then just deliver them all. This
2369 // avoids bugs where we get stuck in a loop trying to poll for alarms.
2370 return false;
2371 }
2372 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
2373 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
2374 }
2375
2376 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
2377 mLastAlarmDeliveryTime = nowELAPSED;
2378 for (int i=0; i<triggerList.size(); i++) {
2379 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07002380 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002381 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07002382 if (localLOGV) {
2383 Slog.v(TAG, "sending alarm " + alarm);
2384 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07002385 if (RECORD_ALARMS_IN_HISTORY) {
2386 if (alarm.workSource != null && alarm.workSource.size() > 0) {
2387 for (int wi=0; wi<alarm.workSource.size(); wi++) {
2388 ActivityManagerNative.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002389 alarm.operation, alarm.workSource.get(wi), alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002390 }
2391 } else {
2392 ActivityManagerNative.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002393 alarm.operation, alarm.uid, alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002394 }
2395 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002396 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002397 } catch (RuntimeException e) {
2398 Slog.w(TAG, "Failure sending alarm.", e);
2399 }
2400 }
2401 }
2402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002403 private class AlarmThread extends Thread
2404 {
2405 public AlarmThread()
2406 {
2407 super("AlarmManager");
2408 }
2409
2410 public void run()
2411 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002412 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002414 while (true)
2415 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002416 int result = waitForAlarm(mNativeData);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002417
2418 triggerList.clear();
2419
Dianne Hackbornc3527222015-05-13 14:03:20 -07002420 final long nowRTC = System.currentTimeMillis();
2421 final long nowELAPSED = SystemClock.elapsedRealtime();
2422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002423 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002424 // The kernel can give us spurious time change notifications due to
2425 // small adjustments it makes internally; we want to filter those out.
2426 final long lastTimeChangeClockTime;
2427 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07002428 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002429 lastTimeChangeClockTime = mLastTimeChangeClockTime;
2430 expectedClockTime = lastTimeChangeClockTime
2431 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07002432 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002433 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-500)
2434 || nowRTC > (expectedClockTime+500)) {
2435 // The change is by at least +/- 500 ms (or this is the first change),
2436 // let's do it!
2437 if (DEBUG_BATCH) {
2438 Slog.v(TAG, "Time changed notification from kernel; rebatching");
2439 }
2440 removeImpl(mTimeTickSender);
2441 rebatchAllAlarms();
2442 mClockReceiver.scheduleTimeTickEvent();
2443 synchronized (mLock) {
2444 mNumTimeChanged++;
2445 mLastTimeChangeClockTime = nowRTC;
2446 mLastTimeChangeRealtime = nowELAPSED;
2447 }
2448 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
2449 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
2450 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2451 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
2452
2453 // The world has changed on us, so we need to re-evaluate alarms
2454 // regardless of whether the kernel has told us one went off.
2455 result |= IS_WAKEUP_MASK;
2456 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002457 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002458
Dianne Hackbornc3527222015-05-13 14:03:20 -07002459 if (result != TIME_CHANGED_MASK) {
2460 // If this was anything besides just a time change, then figure what if
2461 // anything to do about alarms.
2462 synchronized (mLock) {
2463 if (localLOGV) Slog.v(
2464 TAG, "Checking for alarms... rtc=" + nowRTC
2465 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07002466
Dianne Hackbornc3527222015-05-13 14:03:20 -07002467 if (WAKEUP_STATS) {
2468 if ((result & IS_WAKEUP_MASK) != 0) {
2469 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
2470 int n = 0;
2471 for (WakeupEvent event : mRecentWakeups) {
2472 if (event.when > newEarliest) break;
2473 n++; // number of now-stale entries at the list head
2474 }
2475 for (int i = 0; i < n; i++) {
2476 mRecentWakeups.remove();
2477 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002478
Dianne Hackbornc3527222015-05-13 14:03:20 -07002479 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002480 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002481 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002482
2483 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2484 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
2485 // if there are no wakeup alarms and the screen is off, we can
2486 // delay what we have so far until the future.
2487 if (mPendingNonWakeupAlarms.size() == 0) {
2488 mStartCurrentDelayTime = nowELAPSED;
2489 mNextNonWakeupDeliveryTime = nowELAPSED
2490 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
2491 }
2492 mPendingNonWakeupAlarms.addAll(triggerList);
2493 mNumDelayedAlarms += triggerList.size();
2494 rescheduleKernelAlarmsLocked();
2495 updateNextAlarmClockLocked();
2496 } else {
2497 // now deliver the alarm intents; if there are pending non-wakeup
2498 // alarms, we need to merge them in to the list. note we don't
2499 // just deliver them first because we generally want non-wakeup
2500 // alarms delivered after wakeup alarms.
2501 rescheduleKernelAlarmsLocked();
2502 updateNextAlarmClockLocked();
2503 if (mPendingNonWakeupAlarms.size() > 0) {
2504 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
2505 triggerList.addAll(mPendingNonWakeupAlarms);
2506 Collections.sort(triggerList, mAlarmDispatchComparator);
2507 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2508 mTotalDelayTime += thisDelayTime;
2509 if (mMaxDelayTime < thisDelayTime) {
2510 mMaxDelayTime = thisDelayTime;
2511 }
2512 mPendingNonWakeupAlarms.clear();
2513 }
2514 deliverAlarmsLocked(triggerList, nowELAPSED);
2515 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 }
2517 }
2518 }
2519 }
2520 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002521
David Christieebe51fc2013-07-26 13:23:29 -07002522 /**
2523 * Attribute blame for a WakeLock.
2524 * @param pi PendingIntent to attribute blame to if ws is null.
2525 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002526 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07002527 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002528 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002529 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07002530 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002531 final boolean unimportant = pi == mTimeTickSender;
2532 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002533 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002534 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002535 } else {
2536 mWakeLock.setHistoryTag(null);
2537 }
2538 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07002539 if (ws != null) {
2540 mWakeLock.setWorkSource(ws);
2541 return;
2542 }
2543
Christopher Tate14a7bb02015-10-01 10:24:31 -07002544 final int uid = (knownUid >= 0)
2545 ? knownUid
2546 : ActivityManagerNative.getDefault().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07002547 if (uid >= 0) {
2548 mWakeLock.setWorkSource(new WorkSource(uid));
2549 return;
2550 }
2551 } catch (Exception e) {
2552 }
2553
2554 // Something went wrong; fall back to attributing the lock to the OS
2555 mWakeLock.setWorkSource(null);
2556 }
2557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002558 private class AlarmHandler extends Handler {
2559 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002560 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
2561 public static final int LISTENER_TIMEOUT = 3;
2562 public static final int REPORT_ALARMS_ACTIVE = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002563
2564 public AlarmHandler() {
2565 }
2566
2567 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002568 switch (msg.what) {
2569 case ALARM_EVENT: {
2570 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2571 synchronized (mLock) {
2572 final long nowRTC = System.currentTimeMillis();
2573 final long nowELAPSED = SystemClock.elapsedRealtime();
2574 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2575 updateNextAlarmClockLocked();
2576 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002577
Christopher Tate14a7bb02015-10-01 10:24:31 -07002578 // now trigger the alarms without the lock held
2579 for (int i=0; i<triggerList.size(); i++) {
2580 Alarm alarm = triggerList.get(i);
2581 try {
2582 alarm.operation.send();
2583 } catch (PendingIntent.CanceledException e) {
2584 if (alarm.repeatInterval > 0) {
2585 // This IntentSender is no longer valid, but this
2586 // is a repeating alarm, so toss the hoser.
2587 removeImpl(alarm.operation);
2588 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 }
2590 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002591 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002592 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002593
2594 case SEND_NEXT_ALARM_CLOCK_CHANGED:
2595 sendNextAlarmClockChanged();
2596 break;
2597
2598 case LISTENER_TIMEOUT:
2599 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
2600 break;
2601
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002602 case REPORT_ALARMS_ACTIVE:
2603 if (mLocalDeviceIdleController != null) {
2604 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
2605 }
2606 break;
2607
Christopher Tate14a7bb02015-10-01 10:24:31 -07002608 default:
2609 // nope, just ignore it
2610 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002611 }
2612 }
2613 }
2614
2615 class ClockReceiver extends BroadcastReceiver {
2616 public ClockReceiver() {
2617 IntentFilter filter = new IntentFilter();
2618 filter.addAction(Intent.ACTION_TIME_TICK);
2619 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002620 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621 }
2622
2623 @Override
2624 public void onReceive(Context context, Intent intent) {
2625 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07002626 if (DEBUG_BATCH) {
2627 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
2628 }
2629 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002630 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
2631 // Since the kernel does not keep track of DST, we need to
2632 // reset the TZ information at the beginning of each day
2633 // based off of the current Zone gmt offset + userspace tracked
2634 // daylight savings information.
2635 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02002636 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002637 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07002638 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002639 }
2640 }
2641
2642 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07002643 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09002644 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07002645
2646 // Schedule this event for the amount of time that it would take to get to
2647 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09002648 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07002649
David Christieebe51fc2013-07-26 13:23:29 -07002650 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002651 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002652 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
2653 null, Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002654 }
Christopher Tate385e4982013-07-23 18:22:29 -07002655
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002656 public void scheduleDateChangedEvent() {
2657 Calendar calendar = Calendar.getInstance();
2658 calendar.setTimeInMillis(System.currentTimeMillis());
2659 calendar.set(Calendar.HOUR, 0);
2660 calendar.set(Calendar.MINUTE, 0);
2661 calendar.set(Calendar.SECOND, 0);
2662 calendar.set(Calendar.MILLISECOND, 0);
2663 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07002664
2665 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002666 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
2667 AlarmManager.FLAG_STANDALONE, workSource, null,
2668 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002669 }
2670 }
2671
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002672 class InteractiveStateReceiver extends BroadcastReceiver {
2673 public InteractiveStateReceiver() {
2674 IntentFilter filter = new IntentFilter();
2675 filter.addAction(Intent.ACTION_SCREEN_OFF);
2676 filter.addAction(Intent.ACTION_SCREEN_ON);
2677 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
2678 getContext().registerReceiver(this, filter);
2679 }
2680
2681 @Override
2682 public void onReceive(Context context, Intent intent) {
2683 synchronized (mLock) {
2684 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
2685 }
2686 }
2687 }
2688
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002689 class UninstallReceiver extends BroadcastReceiver {
2690 public UninstallReceiver() {
2691 IntentFilter filter = new IntentFilter();
2692 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2693 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002694 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002695 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08002696 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002697 // Register for events related to sdcard installation.
2698 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08002699 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002700 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002701 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002702 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002703 }
2704
2705 @Override
2706 public void onReceive(Context context, Intent intent) {
2707 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002708 String action = intent.getAction();
2709 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002710 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
2711 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
2712 for (String packageName : pkgList) {
2713 if (lookForPackageLocked(packageName)) {
2714 setResultCode(Activity.RESULT_OK);
2715 return;
2716 }
2717 }
2718 return;
2719 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002720 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002721 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
2722 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
2723 if (userHandle >= 0) {
2724 removeUserLocked(userHandle);
2725 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002726 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
2727 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
2728 if (uid >= 0) {
2729 mLastAllowWhileIdleDispatch.delete(uid);
2730 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002731 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08002732 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
2733 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
2734 // This package is being updated; don't kill its alarms.
2735 return;
2736 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002737 Uri data = intent.getData();
2738 if (data != null) {
2739 String pkg = data.getSchemeSpecificPart();
2740 if (pkg != null) {
2741 pkgList = new String[]{pkg};
2742 }
2743 }
2744 }
2745 if (pkgList != null && (pkgList.length > 0)) {
2746 for (String pkg : pkgList) {
2747 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07002748 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002749 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
2750 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
2751 if (uidStats.remove(pkg) != null) {
2752 if (uidStats.size() <= 0) {
2753 mBroadcastStats.removeAt(i);
2754 }
2755 }
2756 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002757 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002758 }
2759 }
2760 }
2761 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002762
2763 final class UidObserver extends IUidObserver.Stub {
2764 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
2765 }
2766
2767 @Override public void onUidGone(int uid) throws RemoteException {
2768 }
2769
2770 @Override public void onUidActive(int uid) throws RemoteException {
2771 }
2772
2773 @Override public void onUidIdle(int uid) throws RemoteException {
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08002774 synchronized (mLock) {
2775 removeForStoppedLocked(uid);
2776 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002777 }
2778 };
2779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002780 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002781 String pkg = pi.getCreatorPackage();
2782 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002783 return getStatsLocked(uid, pkg);
2784 }
2785
2786 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002787 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
2788 if (uidStats == null) {
2789 uidStats = new ArrayMap<String, BroadcastStats>();
2790 mBroadcastStats.put(uid, uidStats);
2791 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002792 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002793 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002794 bs = new BroadcastStats(uid, pkgName);
2795 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796 }
2797 return bs;
2798 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002799
Christopher Tate14a7bb02015-10-01 10:24:31 -07002800 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
2801 private InFlight removeLocked(PendingIntent pi, Intent intent) {
2802 for (int i = 0; i < mInFlight.size(); i++) {
2803 if (mInFlight.get(i).mPendingIntent == pi) {
2804 return mInFlight.remove(i);
2805 }
2806 }
2807 mLog.w("No in-flight alarm for " + pi + " " + intent);
2808 return null;
2809 }
2810
2811 private InFlight removeLocked(IBinder listener) {
2812 for (int i = 0; i < mInFlight.size(); i++) {
2813 if (mInFlight.get(i).mListener == listener) {
2814 return mInFlight.remove(i);
2815 }
2816 }
2817 mLog.w("No in-flight alarm for listener " + listener);
2818 return null;
2819 }
2820
2821 private void updateStatsLocked(InFlight inflight) {
2822 final long nowELAPSED = SystemClock.elapsedRealtime();
2823 BroadcastStats bs = inflight.mBroadcastStats;
2824 bs.nesting--;
2825 if (bs.nesting <= 0) {
2826 bs.nesting = 0;
2827 bs.aggregateTime += nowELAPSED - bs.startTime;
2828 }
2829 FilterStats fs = inflight.mFilterStats;
2830 fs.nesting--;
2831 if (fs.nesting <= 0) {
2832 fs.nesting = 0;
2833 fs.aggregateTime += nowELAPSED - fs.startTime;
2834 }
2835 if (RECORD_ALARMS_IN_HISTORY) {
2836 if (inflight.mWorkSource != null && inflight.mWorkSource.size() > 0) {
2837 for (int wi=0; wi<inflight.mWorkSource.size(); wi++) {
2838 ActivityManagerNative.noteAlarmFinish(
2839 inflight.mPendingIntent, inflight.mWorkSource.get(wi), inflight.mTag);
2840 }
2841 } else {
2842 ActivityManagerNative.noteAlarmFinish(
2843 inflight.mPendingIntent, inflight.mUid, inflight.mTag);
2844 }
2845 }
2846 }
2847
2848 private void updateTrackingLocked(InFlight inflight) {
2849 if (inflight != null) {
2850 updateStatsLocked(inflight);
2851 }
2852 mBroadcastRefCount--;
2853 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002854 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002855 mWakeLock.release();
2856 if (mInFlight.size() > 0) {
2857 mLog.w("Finished all dispatches with " + mInFlight.size()
2858 + " remaining inflights");
2859 for (int i=0; i<mInFlight.size(); i++) {
2860 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
2861 }
2862 mInFlight.clear();
2863 }
2864 } else {
2865 // the next of our alarms is now in flight. reattribute the wakelock.
2866 if (mInFlight.size() > 0) {
2867 InFlight inFlight = mInFlight.get(0);
2868 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
2869 inFlight.mAlarmType, inFlight.mTag, -1, false);
2870 } else {
2871 // should never happen
2872 mLog.w("Alarm wakelock still held but sent queue empty");
2873 mWakeLock.setWorkSource(null);
2874 }
2875 }
2876 }
2877
2878 /**
2879 * Callback that arrives when a direct-call alarm reports that delivery has finished
2880 */
2881 @Override
2882 public void alarmComplete(IBinder who) {
2883 if (who == null) {
2884 Slog.w(TAG, "Invalid alarmComplete: uid=" + Binder.getCallingUid()
2885 + " pid=" + Binder.getCallingPid());
2886 return;
2887 }
2888
2889 final long ident = Binder.clearCallingIdentity();
2890 try {
2891 synchronized (mLock) {
2892 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
2893 InFlight inflight = removeLocked(who);
2894 if (inflight != null) {
2895 if (DEBUG_LISTENER_CALLBACK) {
2896 Slog.i(TAG, "alarmComplete() from " + who);
2897 }
2898 updateTrackingLocked(inflight);
2899 } else {
2900 // Delivery timed out, and the timeout handling already took care of
2901 // updating our tracking here, so we needn't do anything further.
2902 if (DEBUG_LISTENER_CALLBACK) {
2903 Slog.i(TAG, "Late alarmComplete() from " + who);
2904 }
2905 }
2906 }
2907 } finally {
2908 Binder.restoreCallingIdentity(ident);
2909 }
2910 }
2911
2912 /**
2913 * Callback that arrives when a PendingIntent alarm has finished delivery
2914 */
2915 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002916 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
2917 String resultData, Bundle resultExtras) {
2918 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002919 updateTrackingLocked(removeLocked(pi, intent));
2920 }
2921 }
2922
2923 /**
2924 * Timeout of a direct-call alarm delivery
2925 */
2926 public void alarmTimedOut(IBinder who) {
2927 synchronized (mLock) {
2928 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08002929 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002930 // TODO: implement ANR policy for the target
2931 if (DEBUG_LISTENER_CALLBACK) {
2932 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002933 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002934 updateTrackingLocked(inflight);
Dianne Hackborn81038902012-11-26 17:04:09 -08002935 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002936 if (DEBUG_LISTENER_CALLBACK) {
2937 Slog.i(TAG, "Spurious timeout of listener " + who);
2938 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002939 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002940 }
2941 }
2942
2943 /**
2944 * Deliver an alarm and set up the post-delivery handling appropriately
2945 */
2946 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
2947 if (alarm.operation != null) {
2948 // PendingIntent alarm
2949 try {
2950 alarm.operation.send(getContext(), 0,
2951 mBackgroundIntent.putExtra(
2952 Intent.EXTRA_ALARM_COUNT, alarm.count),
2953 mDeliveryTracker, mHandler, null,
2954 allowWhileIdle ? mIdleOptions : null);
2955 } catch (PendingIntent.CanceledException e) {
2956 if (alarm.repeatInterval > 0) {
2957 // This IntentSender is no longer valid, but this
2958 // is a repeating alarm, so toss it
2959 removeImpl(alarm.operation);
2960 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08002961 // No actual delivery was possible, so the delivery tracker's
2962 // 'finished' callback won't be invoked. We also don't need
2963 // to do any wakelock or stats tracking, so we have nothing
2964 // left to do here but go on to the next thing.
2965 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002966 }
2967 } else {
2968 // Direct listener callback alarm
2969 try {
2970 if (DEBUG_LISTENER_CALLBACK) {
2971 Slog.v(TAG, "Alarm to uid=" + alarm.uid
2972 + " listener=" + alarm.listener.asBinder());
2973 }
2974 alarm.listener.doAlarm(this);
2975 mHandler.sendMessageDelayed(
2976 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
2977 alarm.listener.asBinder()),
2978 mConstants.LISTENER_TIMEOUT);
2979 } catch (Exception e) {
2980 if (DEBUG_LISTENER_CALLBACK) {
2981 Slog.i(TAG, "Alarm undeliverable to listener "
2982 + alarm.listener.asBinder(), e);
2983 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08002984 // As in the PendingIntent.CanceledException case, delivery of the
2985 // alarm was not possible, so we have no wakelock or timeout or
2986 // stats management to do. It threw before we posted the delayed
2987 // timeout message, so we're done here.
2988 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002989 }
2990 }
2991
2992 // The alarm is now in flight; now arrange wakelock and stats tracking
2993 if (mBroadcastRefCount == 0) {
2994 setWakelockWorkSource(alarm.operation, alarm.workSource,
2995 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
2996 true);
2997 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002998 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002999 }
3000 final InFlight inflight = new InFlight(AlarmManagerService.this,
3001 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
3002 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
3003 mInFlight.add(inflight);
3004 mBroadcastRefCount++;
3005
3006 if (allowWhileIdle) {
3007 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
3008 mLastAllowWhileIdleDispatch.put(alarm.uid, nowELAPSED);
3009 if (RECORD_DEVICE_IDLE_ALARMS) {
3010 IdleDispatchEntry ent = new IdleDispatchEntry();
3011 ent.uid = alarm.uid;
3012 ent.pkg = alarm.packageName;
3013 ent.tag = alarm.statsTag;
3014 ent.op = "DELIVER";
3015 ent.elapsedRealtime = nowELAPSED;
3016 mAllowWhileIdleDispatches.add(ent);
3017 }
3018 }
3019
3020 final BroadcastStats bs = inflight.mBroadcastStats;
3021 bs.count++;
3022 if (bs.nesting == 0) {
3023 bs.nesting = 1;
3024 bs.startTime = nowELAPSED;
3025 } else {
3026 bs.nesting++;
3027 }
3028 final FilterStats fs = inflight.mFilterStats;
3029 fs.count++;
3030 if (fs.nesting == 0) {
3031 fs.nesting = 1;
3032 fs.startTime = nowELAPSED;
3033 } else {
3034 fs.nesting++;
3035 }
3036 if (alarm.type == ELAPSED_REALTIME_WAKEUP
3037 || alarm.type == RTC_WAKEUP) {
3038 bs.numWakeup++;
3039 fs.numWakeup++;
3040 if (alarm.workSource != null && alarm.workSource.size() > 0) {
3041 for (int wi=0; wi<alarm.workSource.size(); wi++) {
3042 ActivityManagerNative.noteWakeupAlarm(
3043 alarm.operation, alarm.workSource.get(wi),
3044 alarm.workSource.getName(wi), alarm.statsTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08003045 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003046 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003047 ActivityManagerNative.noteWakeupAlarm(
3048 alarm.operation, -1, alarm.packageName, alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003049 }
3050 }
3051 }
3052 }
3053}