blob: 5f57a7632db9ac0db605f97a0be2498aacf5c4fe [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
Adrian Roosc42a1e12014-07-07 23:35:53 +0200114 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT = new Intent(
115 AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED);
116
Adam Lesinski182f73f2013-12-05 16:48:06 -0800117 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800118
Christopher Tate14a7bb02015-10-01 10:24:31 -0700119 AppOpsManager mAppOps;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800120 DeviceIdleController.LocalService mLocalDeviceIdleController;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700121
Adam Lesinski182f73f2013-12-05 16:48:06 -0800122 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800123
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800124 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800125 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700126 private long mNextNonWakeup;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800127 int mBroadcastRefCount = 0;
128 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700129 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700130 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
131 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800132 final AlarmHandler mHandler = new AlarmHandler();
133 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700134 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700136 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800137 PendingIntent mTimeTickSender;
138 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700139 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700140 boolean mInteractive = true;
141 long mNonInteractiveStartTime;
142 long mNonInteractiveTime;
143 long mLastAlarmDeliveryTime;
144 long mStartCurrentDelayTime;
145 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700146 long mLastTimeChangeClockTime;
147 long mLastTimeChangeRealtime;
Dianne Hackborna750a632015-06-16 17:18:23 -0700148 long mAllowWhileIdleMinTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700149 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800150
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700151 /**
152 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
153 * used to determine the earliest we can dispatch the next such alarm.
154 */
155 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
156
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700157 final static class IdleDispatchEntry {
158 int uid;
159 String pkg;
160 String tag;
161 String op;
162 long elapsedRealtime;
163 long argRealtime;
164 }
165 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
166
Dianne Hackborna750a632015-06-16 17:18:23 -0700167 /**
168 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
169 */
170 Bundle mIdleOptions;
171
Jose Lima235510e2014-08-13 12:50:01 -0700172 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
173 new SparseArray<>();
174 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
175 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200176 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
177 new SparseBooleanArray();
178 private boolean mNextAlarmClockMayChange;
179
180 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700181 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
182 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200183
Dianne Hackborna750a632015-06-16 17:18:23 -0700184 /**
185 * All times are in milliseconds. These constants are kept synchronized with the system
186 * global Settings. Any access to this class or its fields should be done while
187 * holding the AlarmManagerService.mLock lock.
188 */
189 private final class Constants extends ContentObserver {
190 // Key names stored in the settings value.
191 private static final String KEY_MIN_FUTURITY = "min_futurity";
192 private static final String KEY_MIN_INTERVAL = "min_interval";
193 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
194 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
195 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
196 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700197 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Dianne Hackborna750a632015-06-16 17:18:23 -0700198
199 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
200 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tateaa244da2015-08-27 15:57:57 -0700201 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700202 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700203 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
204
Christopher Tate14a7bb02015-10-01 10:24:31 -0700205 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
206
Dianne Hackborna750a632015-06-16 17:18:23 -0700207 // Minimum futurity of a new alarm
208 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
209
210 // Minimum alarm recurrence interval
211 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
212
213 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
214 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
215
216 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
217 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
218
219 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
220 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
221 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
222
Christopher Tate14a7bb02015-10-01 10:24:31 -0700223 // Direct alarm listener callback timeout
224 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
225
Dianne Hackborna750a632015-06-16 17:18:23 -0700226 private ContentResolver mResolver;
227 private final KeyValueListParser mParser = new KeyValueListParser(',');
228 private long mLastAllowWhileIdleWhitelistDuration = -1;
229
230 public Constants(Handler handler) {
231 super(handler);
232 updateAllowWhileIdleMinTimeLocked();
233 updateAllowWhileIdleWhitelistDurationLocked();
234 }
235
236 public void start(ContentResolver resolver) {
237 mResolver = resolver;
238 mResolver.registerContentObserver(Settings.Global.getUriFor(
239 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
240 updateConstants();
241 }
242
243 public void updateAllowWhileIdleMinTimeLocked() {
244 mAllowWhileIdleMinTime = mPendingIdleUntil != null
245 ? ALLOW_WHILE_IDLE_LONG_TIME : ALLOW_WHILE_IDLE_SHORT_TIME;
246 }
247
248 public void updateAllowWhileIdleWhitelistDurationLocked() {
249 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
250 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
251 BroadcastOptions opts = BroadcastOptions.makeBasic();
252 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
253 mIdleOptions = opts.toBundle();
254 }
255 }
256
257 @Override
258 public void onChange(boolean selfChange, Uri uri) {
259 updateConstants();
260 }
261
262 private void updateConstants() {
263 synchronized (mLock) {
264 try {
265 mParser.setString(Settings.Global.getString(mResolver,
266 Settings.Global.ALARM_MANAGER_CONSTANTS));
267 } catch (IllegalArgumentException e) {
268 // Failed to parse the settings string, log this and move on
269 // with defaults.
270 Slog.e(TAG, "Bad device idle settings", e);
271 }
272
273 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
274 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
275 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
276 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
277 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
278 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
279 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
280 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
281 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700282 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
283 DEFAULT_LISTENER_TIMEOUT);
Dianne Hackborna750a632015-06-16 17:18:23 -0700284
285 updateAllowWhileIdleMinTimeLocked();
286 updateAllowWhileIdleWhitelistDurationLocked();
287 }
288 }
289
290 void dump(PrintWriter pw) {
291 pw.println(" Settings:");
292
293 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
294 TimeUtils.formatDuration(MIN_FUTURITY, pw);
295 pw.println();
296
297 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
298 TimeUtils.formatDuration(MIN_INTERVAL, pw);
299 pw.println();
300
Christopher Tate14a7bb02015-10-01 10:24:31 -0700301 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
302 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
303 pw.println();
304
Dianne Hackborna750a632015-06-16 17:18:23 -0700305 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
306 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
307 pw.println();
308
309 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
310 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
311 pw.println();
312
313 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
314 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
315 pw.println();
316 }
317 }
318
319 final Constants mConstants;
320
Christopher Tate1590f1e2014-10-02 17:27:57 -0700321 // Alarm delivery ordering bookkeeping
322 static final int PRIO_TICK = 0;
323 static final int PRIO_WAKEUP = 1;
324 static final int PRIO_NORMAL = 2;
325
Dianne Hackborna750a632015-06-16 17:18:23 -0700326 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700327 int seq;
328 int priority;
329
330 PriorityClass() {
331 seq = mCurrentSeq - 1;
332 priority = PRIO_NORMAL;
333 }
334 }
335
Dianne Hackborna750a632015-06-16 17:18:23 -0700336 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700337 int mCurrentSeq = 0;
338
Dianne Hackborna750a632015-06-16 17:18:23 -0700339 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700340 public long when;
341 public int uid;
342 public String action;
343
344 public WakeupEvent(long theTime, int theUid, String theAction) {
345 when = theTime;
346 uid = theUid;
347 action = theAction;
348 }
349 }
350
Adam Lesinski182f73f2013-12-05 16:48:06 -0800351 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
352 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700353
Adrian Roosc42a1e12014-07-07 23:35:53 +0200354 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700355 long start; // These endpoints are always in ELAPSED
356 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700357 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700358
359 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
360
361 Batch() {
362 start = 0;
363 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700364 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700365 }
366
367 Batch(Alarm seed) {
368 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700369 end = seed.maxWhenElapsed;
370 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700371 alarms.add(seed);
372 }
373
374 int size() {
375 return alarms.size();
376 }
377
378 Alarm get(int index) {
379 return alarms.get(index);
380 }
381
382 boolean canHold(long whenElapsed, long maxWhen) {
383 return (end >= whenElapsed) && (start <= maxWhen);
384 }
385
386 boolean add(Alarm alarm) {
387 boolean newStart = false;
388 // narrows the batch if necessary; presumes that canHold(alarm) is true
389 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
390 if (index < 0) {
391 index = 0 - index - 1;
392 }
393 alarms.add(index, alarm);
394 if (DEBUG_BATCH) {
395 Slog.v(TAG, "Adding " + alarm + " to " + this);
396 }
397 if (alarm.whenElapsed > start) {
398 start = alarm.whenElapsed;
399 newStart = true;
400 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700401 if (alarm.maxWhenElapsed < end) {
402 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700403 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700404 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700405
406 if (DEBUG_BATCH) {
407 Slog.v(TAG, " => now " + this);
408 }
409 return newStart;
410 }
411
Christopher Tate14a7bb02015-10-01 10:24:31 -0700412 boolean remove(final PendingIntent operation, final IAlarmListener listener) {
413 if (operation == null && listener == null) {
414 if (localLOGV) {
415 Slog.w(TAG, "requested remove() of null operation",
416 new RuntimeException("here"));
417 }
418 return false;
419 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700420 boolean didRemove = false;
421 long newStart = 0; // recalculate endpoints as we go
422 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700423 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700424 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700425 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700426 if (alarm.matches(operation, listener)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700427 alarms.remove(i);
428 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200429 if (alarm.alarmClock != null) {
430 mNextAlarmClockMayChange = true;
431 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700432 } else {
433 if (alarm.whenElapsed > newStart) {
434 newStart = alarm.whenElapsed;
435 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700436 if (alarm.maxWhenElapsed < newEnd) {
437 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700438 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700439 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700440 i++;
441 }
442 }
443 if (didRemove) {
444 // commit the new batch bounds
445 start = newStart;
446 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700447 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700448 }
449 return didRemove;
450 }
451
452 boolean remove(final String packageName) {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700453 if (packageName == null) {
454 if (localLOGV) {
455 Slog.w(TAG, "requested remove() of null packageName",
456 new RuntimeException("here"));
457 }
458 return false;
459 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700460 boolean didRemove = false;
461 long newStart = 0; // recalculate endpoints as we go
462 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700463 int newFlags = 0;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700464 for (int i = alarms.size()-1; i >= 0; i--) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700465 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700466 if (alarm.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700467 alarms.remove(i);
468 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200469 if (alarm.alarmClock != null) {
470 mNextAlarmClockMayChange = true;
471 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700472 } else {
473 if (alarm.whenElapsed > newStart) {
474 newStart = alarm.whenElapsed;
475 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700476 if (alarm.maxWhenElapsed < newEnd) {
477 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700478 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700479 newFlags |= alarm.flags;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700480 }
481 }
482 if (didRemove) {
483 // commit the new batch bounds
484 start = newStart;
485 end = newEnd;
486 flags = newFlags;
487 }
488 return didRemove;
489 }
490
491 boolean removeForStopped(final int uid) {
492 boolean didRemove = false;
493 long newStart = 0; // recalculate endpoints as we go
494 long newEnd = Long.MAX_VALUE;
495 int newFlags = 0;
496 for (int i = alarms.size()-1; i >= 0; i--) {
497 Alarm alarm = alarms.get(i);
498 try {
499 if (alarm.uid == uid && ActivityManagerNative.getDefault().getAppStartMode(
500 uid, alarm.packageName) == ActivityManager.APP_START_MODE_DISABLED) {
501 alarms.remove(i);
502 didRemove = true;
503 if (alarm.alarmClock != null) {
504 mNextAlarmClockMayChange = true;
505 }
506 } else {
507 if (alarm.whenElapsed > newStart) {
508 newStart = alarm.whenElapsed;
509 }
510 if (alarm.maxWhenElapsed < newEnd) {
511 newEnd = alarm.maxWhenElapsed;
512 }
513 newFlags |= alarm.flags;
514 }
515 } catch (RemoteException e) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700516 }
517 }
518 if (didRemove) {
519 // commit the new batch bounds
520 start = newStart;
521 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700522 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700523 }
524 return didRemove;
525 }
526
527 boolean remove(final int userHandle) {
528 boolean didRemove = false;
529 long newStart = 0; // recalculate endpoints as we go
530 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700531 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700532 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700533 if (UserHandle.getUserId(alarm.creatorUid) == userHandle) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700534 alarms.remove(i);
535 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200536 if (alarm.alarmClock != null) {
537 mNextAlarmClockMayChange = true;
538 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700539 } else {
540 if (alarm.whenElapsed > newStart) {
541 newStart = alarm.whenElapsed;
542 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700543 if (alarm.maxWhenElapsed < newEnd) {
544 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700545 }
546 i++;
547 }
548 }
549 if (didRemove) {
550 // commit the new batch bounds
551 start = newStart;
552 end = newEnd;
553 }
554 return didRemove;
555 }
556
557 boolean hasPackage(final String packageName) {
558 final int N = alarms.size();
559 for (int i = 0; i < N; i++) {
560 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700561 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700562 return true;
563 }
564 }
565 return false;
566 }
567
568 boolean hasWakeups() {
569 final int N = alarms.size();
570 for (int i = 0; i < N; i++) {
571 Alarm a = alarms.get(i);
572 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
573 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
574 return true;
575 }
576 }
577 return false;
578 }
579
580 @Override
581 public String toString() {
582 StringBuilder b = new StringBuilder(40);
583 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
584 b.append(" num="); b.append(size());
585 b.append(" start="); b.append(start);
586 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700587 if (flags != 0) {
588 b.append(" flgs=0x");
589 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700590 }
591 b.append('}');
592 return b.toString();
593 }
594 }
595
596 static class BatchTimeOrder implements Comparator<Batch> {
597 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800598 long when1 = b1.start;
599 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800600 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700601 return 1;
602 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800603 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700604 return -1;
605 }
606 return 0;
607 }
608 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800609
610 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
611 @Override
612 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700613 // priority class trumps everything. TICK < WAKEUP < NORMAL
614 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
615 return -1;
616 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
617 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800618 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700619
620 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800621 if (lhs.whenElapsed < rhs.whenElapsed) {
622 return -1;
623 } else if (lhs.whenElapsed > rhs.whenElapsed) {
624 return 1;
625 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700626
627 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800628 return 0;
629 }
630 };
631
Christopher Tate1590f1e2014-10-02 17:27:57 -0700632 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
633 final int N = alarms.size();
634 for (int i = 0; i < N; i++) {
635 Alarm a = alarms.get(i);
636
637 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700638 if (a.operation != null
639 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700640 alarmPrio = PRIO_TICK;
641 } else if (a.wakeup) {
642 alarmPrio = PRIO_WAKEUP;
643 } else {
644 alarmPrio = PRIO_NORMAL;
645 }
646
647 PriorityClass packagePrio = a.priorityClass;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700648 String alarmPackage = (a.operation != null)
649 ? a.operation.getCreatorPackage()
650 : a.packageName;
651 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700652 if (packagePrio == null) {
653 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700654 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700655 }
656 a.priorityClass = packagePrio;
657
658 if (packagePrio.seq != mCurrentSeq) {
659 // first alarm we've seen in the current delivery generation from this package
660 packagePrio.priority = alarmPrio;
661 packagePrio.seq = mCurrentSeq;
662 } else {
663 // Multiple alarms from this package being delivered in this generation;
664 // bump the package's delivery class if it's warranted.
665 // TICK < WAKEUP < NORMAL
666 if (alarmPrio < packagePrio.priority) {
667 packagePrio.priority = alarmPrio;
668 }
669 }
670 }
671 }
672
Christopher Tatee0a22b32013-07-11 14:43:13 -0700673 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800674 static final long MIN_FUZZABLE_INTERVAL = 10000;
675 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700676 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
677
678 // set to null if in idle mode; while in this mode, any alarms we don't want
679 // to run during this time are placed in mPendingWhileIdleAlarms
680 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700681 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700682 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700683
Jeff Brownb880d882014-02-10 19:47:07 -0800684 public AlarmManagerService(Context context) {
685 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700686 mConstants = new Constants(mHandler);
Jeff Brownb880d882014-02-10 19:47:07 -0800687 }
688
Christopher Tatee0a22b32013-07-11 14:43:13 -0700689 static long convertToElapsed(long when, int type) {
690 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
691 if (isRtc) {
692 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
693 }
694 return when;
695 }
696
697 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
698 // calculate the end of our nominal delivery window for the alarm.
699 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
700 // Current heuristic: batchable window is 75% of either the recurrence interval
701 // [for a periodic alarm] or of the time from now to the desired delivery time,
702 // with a minimum delay/interval of 10 seconds, under which we will simply not
703 // defer the alarm.
704 long futurity = (interval == 0)
705 ? (triggerAtTime - now)
706 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700707 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700708 futurity = 0;
709 }
710 return triggerAtTime + (long)(.75 * futurity);
711 }
712
713 // returns true if the batch was added at the head
714 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
715 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
716 if (index < 0) {
717 index = 0 - index - 1;
718 }
719 list.add(index, newBatch);
720 return (index == 0);
721 }
722
Christopher Tate385e4982013-07-23 18:22:29 -0700723 // Return the index of the matching batch, or -1 if none found.
724 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700725 final int N = mAlarmBatches.size();
726 for (int i = 0; i < N; i++) {
727 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700728 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700729 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700730 }
731 }
Christopher Tate385e4982013-07-23 18:22:29 -0700732 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700733 }
734
735 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
736 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700737 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700738 rebatchAllAlarmsLocked(true);
739 }
740 }
741
742 void rebatchAllAlarmsLocked(boolean doValidate) {
743 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
744 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700745 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700746 final long nowElapsed = SystemClock.elapsedRealtime();
747 final int oldBatches = oldSet.size();
748 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
749 Batch batch = oldSet.get(batchNum);
750 final int N = batch.size();
751 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700752 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700753 }
754 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700755 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
756 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
757 + " to " + mPendingIdleUntil);
758 if (mPendingIdleUntil == null) {
759 // Somehow we lost this... we need to restore all of the pending alarms.
760 restorePendingWhileIdleAlarmsLocked();
761 }
762 }
763 rescheduleKernelAlarmsLocked();
764 updateNextAlarmClockLocked();
765 }
766
767 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
768 a.when = a.origWhen;
769 long whenElapsed = convertToElapsed(a.when, a.type);
770 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700771 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700772 // Exact
773 maxElapsed = whenElapsed;
774 } else {
775 // Not exact. Preserve any explicit window, otherwise recalculate
776 // the window based on the alarm's new futurity. Note that this
777 // reflects a policy of preferring timely to deferred delivery.
778 maxElapsed = (a.windowLength > 0)
779 ? (whenElapsed + a.windowLength)
780 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
781 }
782 a.whenElapsed = whenElapsed;
783 a.maxWhenElapsed = maxElapsed;
784 setImplLocked(a, true, doValidate);
785 }
786
787 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700788 if (RECORD_DEVICE_IDLE_ALARMS) {
789 IdleDispatchEntry ent = new IdleDispatchEntry();
790 ent.uid = 0;
791 ent.pkg = "FINISH IDLE";
792 ent.elapsedRealtime = SystemClock.elapsedRealtime();
793 mAllowWhileIdleDispatches.add(ent);
794 }
795
Dianne Hackborn35d54032015-04-23 10:30:43 -0700796 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700797 if (mPendingWhileIdleAlarms.size() > 0) {
798 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
799 mPendingWhileIdleAlarms = new ArrayList<>();
800 final long nowElapsed = SystemClock.elapsedRealtime();
801 for (int i=alarms.size() - 1; i >= 0; i--) {
802 Alarm a = alarms.get(i);
803 reAddAlarmLocked(a, nowElapsed, false);
804 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700805 }
Dianne Hackborn35d54032015-04-23 10:30:43 -0700806
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700807 // Make sure we are using the correct ALLOW_WHILE_IDLE min time.
Dianne Hackborna750a632015-06-16 17:18:23 -0700808 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700809
Dianne Hackborn35d54032015-04-23 10:30:43 -0700810 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700811 rescheduleKernelAlarmsLocked();
812 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -0700813
814 // And send a TIME_TICK right now, since it is important to get the UI updated.
815 try {
816 mTimeTickSender.send();
817 } catch (PendingIntent.CanceledException e) {
818 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700819 }
820
Christopher Tate14a7bb02015-10-01 10:24:31 -0700821 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -0800822 final PendingIntent mPendingIntent;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700823 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -0700824 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700825 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700826 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800827 final BroadcastStats mBroadcastStats;
828 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800829 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800830
Christopher Tate14a7bb02015-10-01 10:24:31 -0700831 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
832 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
833 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800834 mPendingIntent = pendingIntent;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700835 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -0700836 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700837 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700838 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700839 mBroadcastStats = (pendingIntent != null)
840 ? service.getStatsLocked(pendingIntent)
841 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700842 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -0800843 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700844 fs = new FilterStats(mBroadcastStats, mTag);
845 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -0800846 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700847 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -0800848 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800849 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800850 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800852
Adam Lesinski182f73f2013-12-05 16:48:06 -0800853 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -0800854 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700855 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800856
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700857 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800859 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 int numWakeup;
861 long startTime;
862 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -0800863
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700864 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800865 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700866 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800867 }
868 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700869
Adam Lesinski182f73f2013-12-05 16:48:06 -0800870 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800871 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800872 final String mPackageName;
873
874 long aggregateTime;
875 int count;
876 int numWakeup;
877 long startTime;
878 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700879 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -0800880
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800881 BroadcastStats(int uid, String packageName) {
882 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800883 mPackageName = packageName;
884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700886
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800887 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
888 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700889
890 int mNumDelayedAlarms = 0;
891 long mTotalDelayTime = 0;
892 long mMaxDelayTime = 0;
893
Adam Lesinski182f73f2013-12-05 16:48:06 -0800894 @Override
895 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800896 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800897 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800898
899 // We have to set current TimeZone info to kernel
900 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -0800901 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800902
Adam Lesinski182f73f2013-12-05 16:48:06 -0800903 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800904 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800905
Adam Lesinski182f73f2013-12-05 16:48:06 -0800906 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700908 Intent.FLAG_RECEIVER_REGISTERED_ONLY
909 | Intent.FLAG_RECEIVER_FOREGROUND), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700910 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800911 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
912 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800913 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700914 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915
916 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -0800917 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 mClockReceiver.scheduleTimeTickEvent();
919 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700920 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 mUninstallReceiver = new UninstallReceiver();
922
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800923 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800924 AlarmThread waitThread = new AlarmThread();
925 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800926 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800927 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800929
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700930 try {
931 ActivityManagerNative.getDefault().registerUidObserver(new UidObserver(),
932 ActivityManager.UID_OBSERVER_IDLE);
933 } catch (RemoteException e) {
934 // ignored; both services live in system_server
935 }
936
Adam Lesinski182f73f2013-12-05 16:48:06 -0800937 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800938 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800939
940 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -0700941 public void onBootPhase(int phase) {
942 if (phase == PHASE_SYSTEM_SERVICES_READY) {
943 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -0700944 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800945 mLocalDeviceIdleController
946 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackborna750a632015-06-16 17:18:23 -0700947 }
948 }
949
950 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800951 protected void finalize() throws Throwable {
952 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800953 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 } finally {
955 super.finalize();
956 }
957 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700958
Adam Lesinski182f73f2013-12-05 16:48:06 -0800959 void setTimeZoneImpl(String tz) {
960 if (TextUtils.isEmpty(tz)) {
961 return;
David Christieebe51fc2013-07-26 13:23:29 -0700962 }
963
Adam Lesinski182f73f2013-12-05 16:48:06 -0800964 TimeZone zone = TimeZone.getTimeZone(tz);
965 // Prevent reentrant calls from stepping on each other when writing
966 // the time zone property
967 boolean timeZoneWasChanged = false;
968 synchronized (this) {
969 String current = SystemProperties.get(TIMEZONE_PROPERTY);
970 if (current == null || !current.equals(zone.getID())) {
971 if (localLOGV) {
972 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
973 }
974 timeZoneWasChanged = true;
975 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
976 }
977
978 // Update the kernel timezone information
979 // Kernel tracks time offsets as 'minutes west of GMT'
980 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800981 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -0800982 }
983
984 TimeZone.setDefault(null);
985
986 if (timeZoneWasChanged) {
987 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
988 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
989 intent.putExtra("time-zone", zone.getID());
990 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
991 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700993
Adam Lesinski182f73f2013-12-05 16:48:06 -0800994 void removeImpl(PendingIntent operation) {
995 if (operation == null) {
996 return;
997 }
998 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700999 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001000 }
1001 }
1002
1003 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001004 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1005 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1006 int callingUid, String callingPackage) {
1007 // must be *either* PendingIntent or AlarmReceiver, but not both
1008 if ((operation == null && directReceiver == null)
1009 || (operation != null && directReceiver != null)) {
1010 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1011 // NB: previous releases failed silently here, so we are continuing to do the same
1012 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 return;
1014 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001015
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001016 // Sanity check the window length. This will catch people mistakenly
1017 // trying to pass an end-of-window timestamp rather than a duration.
1018 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1019 Slog.w(TAG, "Window length " + windowLength
1020 + "ms suspiciously long; limiting to 1 hour");
1021 windowLength = AlarmManager.INTERVAL_HOUR;
1022 }
1023
Christopher Tate498c6cb2014-11-17 16:09:27 -08001024 // Sanity check the recurrence interval. This will catch people who supply
1025 // seconds when the API expects milliseconds.
Dianne Hackborna750a632015-06-16 17:18:23 -07001026 final long minInterval = mConstants.MIN_INTERVAL;
1027 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001028 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001029 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001030 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001031 interval = minInterval;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001032 }
1033
Christopher Tatee0a22b32013-07-11 14:43:13 -07001034 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1035 throw new IllegalArgumentException("Invalid alarm type " + type);
1036 }
1037
Christopher Tate5f221e82013-07-30 17:13:15 -07001038 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001039 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001040 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001041 + " pid=" + what);
1042 triggerAtTime = 0;
1043 }
1044
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001045 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001046 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1047 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001048 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001049 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1050
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001051 final long maxElapsed;
1052 if (windowLength == AlarmManager.WINDOW_EXACT) {
1053 maxElapsed = triggerElapsed;
1054 } else if (windowLength < 0) {
1055 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001056 // Fix this window in place, so that as time approaches we don't collapse it.
1057 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001058 } else {
1059 maxElapsed = triggerElapsed + windowLength;
1060 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001061
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001063 if (DEBUG_BATCH) {
1064 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001065 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001066 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001067 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001069 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001070 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1071 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072 }
1073 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074
Christopher Tate3e04b472013-10-21 17:51:31 -07001075 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001076 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1077 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1078 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001079 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001080 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1081 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001082 try {
1083 if (ActivityManagerNative.getDefault().getAppStartMode(callingUid, callingPackage)
1084 == ActivityManager.APP_START_MODE_DISABLED) {
1085 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1086 + " -- package not allowed to start");
1087 return;
1088 }
1089 } catch (RemoteException e) {
1090 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001091 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001092 setImplLocked(a, false, doValidate);
1093 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001094
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001095 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1096 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001097 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001098 // The caller has given the time they want this to happen at, however we need
1099 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001100 // bring us out of idle at an earlier time.
1101 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001102 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001103 }
1104 // Add fuzz to make the alarm go off some time before the actual desired time.
1105 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001106 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001107 if (fuzz > 0) {
1108 if (mRandom == null) {
1109 mRandom = new Random();
1110 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001111 final int delta = mRandom.nextInt(fuzz);
1112 a.whenElapsed -= delta;
1113 if (false) {
1114 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1115 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1116 Slog.d(TAG, "Applied fuzz: " + fuzz);
1117 Slog.d(TAG, "Final delta: " + delta);
1118 Slog.d(TAG, "Final when: " + a.whenElapsed);
1119 }
1120 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001121 }
1122
1123 } else if (mPendingIdleUntil != null) {
1124 // We currently have an idle until alarm scheduled; if the new alarm has
1125 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001126 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1127 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1128 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001129 == 0) {
1130 mPendingWhileIdleAlarms.add(a);
1131 return;
1132 }
1133 }
1134
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001135 if (RECORD_DEVICE_IDLE_ALARMS) {
1136 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1137 IdleDispatchEntry ent = new IdleDispatchEntry();
1138 ent.uid = a.uid;
1139 ent.pkg = a.operation.getCreatorPackage();
1140 ent.tag = a.operation.getTag("");
1141 ent.op = "SET";
1142 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1143 ent.argRealtime = a.whenElapsed;
1144 mAllowWhileIdleDispatches.add(ent);
1145 }
1146 }
1147
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001148 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
1149 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -07001150 if (whichBatch < 0) {
1151 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001152 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 } else {
Christopher Tate385e4982013-07-23 18:22:29 -07001154 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001155 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001156 // The start time of this batch advanced, so batch ordering may
1157 // have just been broken. Move it to where it now belongs.
1158 mAlarmBatches.remove(whichBatch);
1159 addBatchLocked(mAlarmBatches, batch);
1160 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 }
1162
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001163 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001164 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001165 }
1166
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001167 boolean needRebatch = false;
1168
1169 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001170 if (RECORD_DEVICE_IDLE_ALARMS) {
1171 if (mPendingIdleUntil == null) {
1172 IdleDispatchEntry ent = new IdleDispatchEntry();
1173 ent.uid = 0;
1174 ent.pkg = "START IDLE";
1175 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1176 mAllowWhileIdleDispatches.add(ent);
1177 }
1178 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001179 mPendingIdleUntil = a;
Dianne Hackborna750a632015-06-16 17:18:23 -07001180 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001181 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001182 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1183 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1184 mNextWakeFromIdle = a;
1185 // If this wake from idle is earlier than whatever was previously scheduled,
1186 // and we are currently idling, then we need to rebatch alarms in case the idle
1187 // until time needs to be updated.
1188 if (mPendingIdleUntil != null) {
1189 needRebatch = true;
1190 }
1191 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001192 }
1193
1194 if (!rebatching) {
1195 if (DEBUG_VALIDATE) {
1196 if (doValidate && !validateConsistencyLocked()) {
1197 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1198 + " when(hex)=" + Long.toHexString(a.when)
1199 + " whenElapsed=" + a.whenElapsed
1200 + " maxWhenElapsed=" + a.maxWhenElapsed
1201 + " interval=" + a.repeatInterval + " op=" + a.operation
1202 + " flags=0x" + Integer.toHexString(a.flags));
1203 rebatchAllAlarmsLocked(false);
1204 needRebatch = false;
1205 }
1206 }
1207
1208 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001209 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001210 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001211
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001212 rescheduleKernelAlarmsLocked();
1213 updateNextAlarmClockLocked();
1214 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001215 }
1216
Adam Lesinski182f73f2013-12-05 16:48:06 -08001217 private final IBinder mService = new IAlarmManager.Stub() {
1218 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001219 public void set(String callingPackage,
1220 int type, long triggerAtTime, long windowLength, long interval, int flags,
1221 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1222 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001223 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001224
1225 // make sure the caller is not lying about which package should be blamed for
1226 // wakelock time spent in alarm delivery
1227 mAppOps.checkPackage(callingUid, callingPackage);
1228
1229 // Repeating alarms must use PendingIntent, not direct listener
1230 if (interval != 0) {
1231 if (directReceiver != null) {
1232 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1233 }
1234 }
1235
Adam Lesinski182f73f2013-12-05 16:48:06 -08001236 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001237 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001238 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001239 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001240 }
1241
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001242 // No incoming callers can request either WAKE_FROM_IDLE or
1243 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1244 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1245 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1246
1247 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1248 // manager when to come out of idle mode, which is only for DeviceIdleController.
1249 if (callingUid != Process.SYSTEM_UID) {
1250 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1251 }
1252
1253 // If the caller is a core system component, and not calling to do work on behalf
1254 // of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED. This means we
1255 // will allow these alarms to go off as normal even while idle, with no timing
1256 // restrictions.
1257 if (callingUid < Process.FIRST_APPLICATION_UID && workSource == null) {
1258 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1259 }
1260
1261 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001262 if (windowLength == AlarmManager.WINDOW_EXACT) {
1263 flags |= AlarmManager.FLAG_STANDALONE;
1264 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001265
1266 // If this alarm is for an alarm clock, then it must be standalone and we will
1267 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001268 if (alarmClock != null) {
1269 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
1270 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001271
Christopher Tate14a7bb02015-10-01 10:24:31 -07001272 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1273 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001274 }
Christopher Tate89779822012-08-31 14:40:03 -07001275
Adam Lesinski182f73f2013-12-05 16:48:06 -08001276 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001277 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001278 getContext().enforceCallingOrSelfPermission(
1279 "android.permission.SET_TIME",
1280 "setTime");
1281
Greg Hackmann0cab8962014-02-21 16:35:52 -08001282 if (mNativeData == 0) {
1283 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1284 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001285 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001286
1287 synchronized (mLock) {
1288 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001289 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001291
1292 @Override
1293 public void setTimeZone(String tz) {
1294 getContext().enforceCallingOrSelfPermission(
1295 "android.permission.SET_TIME_ZONE",
1296 "setTimeZone");
1297
1298 final long oldId = Binder.clearCallingIdentity();
1299 try {
1300 setTimeZoneImpl(tz);
1301 } finally {
1302 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001303 }
1304 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001305
Adam Lesinski182f73f2013-12-05 16:48:06 -08001306 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001307 public void remove(PendingIntent operation, IAlarmListener listener) {
1308 if (operation == null && listener == null) {
1309 Slog.w(TAG, "remove() with no intent or listener");
1310 return;
1311 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001312
Christopher Tate14a7bb02015-10-01 10:24:31 -07001313 synchronized (mLock) {
1314 removeLocked(operation, listener);
1315 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001317
Adam Lesinski182f73f2013-12-05 16:48:06 -08001318 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001319 public long getNextWakeFromIdleTime() {
1320 return getNextWakeFromIdleTimeImpl();
1321 }
1322
1323 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001324 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001325 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1326 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1327 "getNextAlarmClock", null);
1328
1329 return getNextAlarmClockImpl(userId);
1330 }
1331
1332 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001333 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1334 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1335 != PackageManager.PERMISSION_GRANTED) {
1336 pw.println("Permission Denial: can't dump AlarmManager from from pid="
1337 + Binder.getCallingPid()
1338 + ", uid=" + Binder.getCallingUid());
1339 return;
Christopher Tate4cb338d2013-07-26 13:11:31 -07001340 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001341
Adam Lesinski182f73f2013-12-05 16:48:06 -08001342 dumpImpl(pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001343 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001344 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001345
Adam Lesinski182f73f2013-12-05 16:48:06 -08001346 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347 synchronized (mLock) {
1348 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001349 mConstants.dump(pw);
1350 pw.println();
1351
Christopher Tatee0a22b32013-07-11 14:43:13 -07001352 final long nowRTC = System.currentTimeMillis();
1353 final long nowELAPSED = SystemClock.elapsedRealtime();
1354 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1355
Dianne Hackborna750a632015-06-16 17:18:23 -07001356 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001357 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001358 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001359 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001360 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001361 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001362 pw.print(" mLastTimeChangeRealtime=");
Dianne Hackbornc3527222015-05-13 14:03:20 -07001363 TimeUtils.formatDuration(mLastTimeChangeRealtime, pw);
1364 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001365 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001366 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001367 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1368 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001369 pw.print(" Max wakeup delay: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001370 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1371 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001372 pw.print(" Time since last dispatch: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001373 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1374 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001375 pw.print(" Next non-wakeup delivery time: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001376 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1377 pw.println();
1378 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001379
1380 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1381 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001382 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001383 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001384 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001385 pw.print(" Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001386 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001387 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001388
John Spurlock604a5ee2015-06-01 12:27:22 -04001389 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001390 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001391 final TreeSet<Integer> users = new TreeSet<>();
1392 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1393 users.add(mNextAlarmClockForUser.keyAt(i));
1394 }
1395 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1396 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1397 }
1398 for (int user : users) {
1399 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1400 final long time = next != null ? next.getTriggerTime() : 0;
1401 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001402 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001403 pw.print(" pendingSend:"); pw.print(pendingSend);
1404 pw.print(" time:"); pw.print(time);
1405 if (time > 0) {
1406 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1407 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1408 }
1409 pw.println();
1410 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001411 if (mAlarmBatches.size() > 0) {
1412 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001413 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001414 pw.println(mAlarmBatches.size());
1415 for (Batch b : mAlarmBatches) {
1416 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001417 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001418 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001420 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001421 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001422 pw.println(" Idle mode state:");
1423 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001424 if (mPendingIdleUntil != null) {
1425 pw.println(mPendingIdleUntil);
Dianne Hackbornf3831292015-10-15 14:51:06 -07001426 mPendingIdleUntil.dump(pw, " ", nowRTC, nowELAPSED, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001427 } else {
1428 pw.println("null");
1429 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001430 pw.println(" Pending alarms:");
1431 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001432 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001433 if (mNextWakeFromIdle != null) {
1434 pw.println();
1435 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
1436 mNextWakeFromIdle.dump(pw, " ", nowRTC, nowELAPSED, sdf);
1437 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001438
1439 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001440 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001441 if (mPendingNonWakeupAlarms.size() > 0) {
1442 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001443 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001444 } else {
1445 pw.println("(none)");
1446 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001447 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001448 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1449 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001450 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001451 pw.print(", max non-interactive time: ");
1452 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1453 pw.println();
1454
1455 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001456 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001457 pw.println();
1458
Christopher Tate7f2a0352015-12-08 10:24:33 -08001459 if (mInFlight.size() > 0) {
1460 pw.println("Outstanding deliveries:");
1461 for (int i = 0; i < mInFlight.size(); i++) {
1462 pw.print(" #"); pw.print(i); pw.print(": ");
1463 pw.println(mInFlight.get(i));
1464 }
1465 pw.println();
1466 }
1467
Dianne Hackborna750a632015-06-16 17:18:23 -07001468 pw.print(" mAllowWhileIdleMinTime=");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001469 TimeUtils.formatDuration(mAllowWhileIdleMinTime, pw);
1470 pw.println();
1471 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001472 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001473 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
1474 pw.print(" UID ");
1475 UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
1476 pw.print(": ");
1477 TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i),
1478 nowELAPSED, pw);
1479 pw.println();
1480 }
1481 }
1482 pw.println();
1483
Dianne Hackborn81038902012-11-26 17:04:09 -08001484 if (mLog.dump(pw, " Recent problems", " ")) {
1485 pw.println();
1486 }
1487
1488 final FilterStats[] topFilters = new FilterStats[10];
1489 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1490 @Override
1491 public int compare(FilterStats lhs, FilterStats rhs) {
1492 if (lhs.aggregateTime < rhs.aggregateTime) {
1493 return 1;
1494 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1495 return -1;
1496 }
1497 return 0;
1498 }
1499 };
1500 int len = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001501 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1502 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1503 for (int ip=0; ip<uidStats.size(); ip++) {
1504 BroadcastStats bs = uidStats.valueAt(ip);
1505 for (int is=0; is<bs.filterStats.size(); is++) {
1506 FilterStats fs = bs.filterStats.valueAt(is);
1507 int pos = len > 0
1508 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1509 if (pos < 0) {
1510 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001511 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001512 if (pos < topFilters.length) {
1513 int copylen = topFilters.length - pos - 1;
1514 if (copylen > 0) {
1515 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1516 }
1517 topFilters[pos] = fs;
1518 if (len < topFilters.length) {
1519 len++;
1520 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001521 }
1522 }
1523 }
1524 }
1525 if (len > 0) {
1526 pw.println(" Top Alarms:");
1527 for (int i=0; i<len; i++) {
1528 FilterStats fs = topFilters[i];
1529 pw.print(" ");
1530 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1531 TimeUtils.formatDuration(fs.aggregateTime, pw);
1532 pw.print(" running, "); pw.print(fs.numWakeup);
1533 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001534 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1535 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001536 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001537 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001538 pw.println();
1539 }
1540 }
1541
1542 pw.println(" ");
1543 pw.println(" Alarm Stats:");
1544 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001545 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1546 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1547 for (int ip=0; ip<uidStats.size(); ip++) {
1548 BroadcastStats bs = uidStats.valueAt(ip);
1549 pw.print(" ");
1550 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1551 UserHandle.formatUid(pw, bs.mUid);
1552 pw.print(":");
1553 pw.print(bs.mPackageName);
1554 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1555 pw.print(" running, "); pw.print(bs.numWakeup);
1556 pw.println(" wakeups:");
1557 tmpFilters.clear();
1558 for (int is=0; is<bs.filterStats.size(); is++) {
1559 tmpFilters.add(bs.filterStats.valueAt(is));
1560 }
1561 Collections.sort(tmpFilters, comparator);
1562 for (int i=0; i<tmpFilters.size(); i++) {
1563 FilterStats fs = tmpFilters.get(i);
1564 pw.print(" ");
1565 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1566 TimeUtils.formatDuration(fs.aggregateTime, pw);
1567 pw.print(" "); pw.print(fs.numWakeup);
1568 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001569 pw.print(" alarms, last ");
1570 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1571 pw.println(":");
1572 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001573 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001574 pw.println();
1575 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 }
1577 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001578
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001579 if (RECORD_DEVICE_IDLE_ALARMS) {
1580 pw.println();
1581 pw.println(" Allow while idle dispatches:");
1582 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
1583 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
1584 pw.print(" ");
1585 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
1586 pw.print(": ");
1587 UserHandle.formatUid(pw, ent.uid);
1588 pw.print(":");
1589 pw.println(ent.pkg);
1590 if (ent.op != null) {
1591 pw.print(" ");
1592 pw.print(ent.op);
1593 pw.print(" / ");
1594 pw.print(ent.tag);
1595 if (ent.argRealtime != 0) {
1596 pw.print(" (");
1597 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
1598 pw.print(")");
1599 }
1600 pw.println();
1601 }
1602 }
1603 }
1604
Christopher Tate18a75f12013-07-01 18:18:59 -07001605 if (WAKEUP_STATS) {
1606 pw.println();
1607 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001608 long last = -1;
1609 for (WakeupEvent event : mRecentWakeups) {
1610 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1611 pw.print('|');
1612 if (last < 0) {
1613 pw.print('0');
1614 } else {
1615 pw.print(event.when - last);
1616 }
1617 last = event.when;
1618 pw.print('|'); pw.print(event.uid);
1619 pw.print('|'); pw.print(event.action);
1620 pw.println();
1621 }
1622 pw.println();
1623 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 }
1625 }
1626
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001627 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001628 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
1629 PrintWriter pw = new PrintWriter(bs);
1630 final long nowRTC = System.currentTimeMillis();
1631 final long nowELAPSED = SystemClock.elapsedRealtime();
1632 final int NZ = mAlarmBatches.size();
1633 for (int iz = 0; iz < NZ; iz++) {
1634 Batch bz = mAlarmBatches.get(iz);
1635 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001636 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001637 pw.flush();
1638 Slog.v(TAG, bs.toString());
1639 bs.reset();
1640 }
1641 }
1642
1643 private boolean validateConsistencyLocked() {
1644 if (DEBUG_VALIDATE) {
1645 long lastTime = Long.MIN_VALUE;
1646 final int N = mAlarmBatches.size();
1647 for (int i = 0; i < N; i++) {
1648 Batch b = mAlarmBatches.get(i);
1649 if (b.start >= lastTime) {
1650 // duplicate start times are okay because of standalone batches
1651 lastTime = b.start;
1652 } else {
1653 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001654 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1655 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001656 return false;
1657 }
1658 }
1659 }
1660 return true;
1661 }
1662
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001663 private Batch findFirstWakeupBatchLocked() {
1664 final int N = mAlarmBatches.size();
1665 for (int i = 0; i < N; i++) {
1666 Batch b = mAlarmBatches.get(i);
1667 if (b.hasWakeups()) {
1668 return b;
1669 }
1670 }
1671 return null;
1672 }
1673
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001674 long getNextWakeFromIdleTimeImpl() {
1675 synchronized (mLock) {
1676 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
1677 }
1678 }
1679
1680 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001681 synchronized (mLock) {
1682 return mNextAlarmClockForUser.get(userId);
1683 }
1684 }
1685
1686 /**
1687 * Recomputes the next alarm clock for all users.
1688 */
1689 private void updateNextAlarmClockLocked() {
1690 if (!mNextAlarmClockMayChange) {
1691 return;
1692 }
1693 mNextAlarmClockMayChange = false;
1694
Jose Lima235510e2014-08-13 12:50:01 -07001695 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001696 nextForUser.clear();
1697
1698 final int N = mAlarmBatches.size();
1699 for (int i = 0; i < N; i++) {
1700 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
1701 final int M = alarms.size();
1702
1703 for (int j = 0; j < M; j++) {
1704 Alarm a = alarms.get(j);
1705 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001706 final int userId = UserHandle.getUserId(a.uid);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001707
1708 if (DEBUG_ALARM_CLOCK) {
1709 Log.v(TAG, "Found AlarmClockInfo at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001710 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02001711 " for user " + userId);
1712 }
1713
1714 // Alarms and batches are sorted by time, no need to compare times here.
1715 if (nextForUser.get(userId) == null) {
1716 nextForUser.put(userId, a.alarmClock);
1717 }
1718 }
1719 }
1720 }
1721
1722 // Update mNextAlarmForUser with new values.
1723 final int NN = nextForUser.size();
1724 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07001725 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001726 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001727 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001728 if (!newAlarm.equals(currentAlarm)) {
1729 updateNextAlarmInfoForUserLocked(userId, newAlarm);
1730 }
1731 }
1732
1733 // Remove users without any alarm clocks scheduled.
1734 final int NNN = mNextAlarmClockForUser.size();
1735 for (int i = NNN - 1; i >= 0; i--) {
1736 int userId = mNextAlarmClockForUser.keyAt(i);
1737 if (nextForUser.get(userId) == null) {
1738 updateNextAlarmInfoForUserLocked(userId, null);
1739 }
1740 }
1741 }
1742
Jose Lima235510e2014-08-13 12:50:01 -07001743 private void updateNextAlarmInfoForUserLocked(int userId,
1744 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001745 if (alarmClock != null) {
1746 if (DEBUG_ALARM_CLOCK) {
1747 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001748 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02001749 }
1750 mNextAlarmClockForUser.put(userId, alarmClock);
1751 } else {
1752 if (DEBUG_ALARM_CLOCK) {
1753 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
1754 }
1755 mNextAlarmClockForUser.remove(userId);
1756 }
1757
1758 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
1759 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1760 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1761 }
1762
1763 /**
1764 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
1765 * for which alarm clocks have changed since the last call to this.
1766 *
1767 * Do not call with a lock held. Only call from mHandler's thread.
1768 *
1769 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
1770 */
1771 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07001772 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001773 pendingUsers.clear();
1774
1775 synchronized (mLock) {
1776 final int N = mPendingSendNextAlarmClockChangedForUser.size();
1777 for (int i = 0; i < N; i++) {
1778 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
1779 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
1780 }
1781 mPendingSendNextAlarmClockChangedForUser.clear();
1782 }
1783
1784 final int N = pendingUsers.size();
1785 for (int i = 0; i < N; i++) {
1786 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001787 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001788 Settings.System.putStringForUser(getContext().getContentResolver(),
1789 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01001790 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02001791 userId);
1792
1793 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
1794 new UserHandle(userId));
1795 }
1796 }
1797
1798 /**
1799 * Formats an alarm like platform/packages/apps/DeskClock used to.
1800 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01001801 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
1802 int userId) {
1803 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02001804 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
1805 return (info == null) ? "" :
1806 DateFormat.format(pattern, info.getTriggerTime()).toString();
1807 }
1808
Adam Lesinski182f73f2013-12-05 16:48:06 -08001809 void rescheduleKernelAlarmsLocked() {
1810 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
1811 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001812 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001813 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001814 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001815 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07001816 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001817 mNextWakeup = firstWakeup.start;
1818 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001819 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001820 if (firstBatch != firstWakeup) {
1821 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001822 }
1823 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001824 if (mPendingNonWakeupAlarms.size() > 0) {
1825 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
1826 nextNonWakeup = mNextNonWakeupDeliveryTime;
1827 }
1828 }
Prashant Malani753e9e02015-06-10 17:43:49 -07001829 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001830 mNextNonWakeup = nextNonWakeup;
1831 setLocked(ELAPSED_REALTIME, nextNonWakeup);
1832 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001833 }
1834
Christopher Tate14a7bb02015-10-01 10:24:31 -07001835 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001836 boolean didRemove = false;
1837 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1838 Batch b = mAlarmBatches.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -07001839 didRemove |= b.remove(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001840 if (b.size() == 0) {
1841 mAlarmBatches.remove(i);
1842 }
1843 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001844 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001845 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001846 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1847 mPendingWhileIdleAlarms.remove(i);
1848 }
1849 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001850
1851 if (didRemove) {
1852 if (DEBUG_BATCH) {
1853 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
1854 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001855 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001856 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001857 mPendingIdleUntil = null;
1858 restorePending = true;
1859 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001860 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001861 mNextWakeFromIdle = null;
1862 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001863 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001864 if (restorePending) {
1865 restorePendingWhileIdleAlarmsLocked();
1866 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001867 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001868 }
1869 }
1870
1871 void removeLocked(String packageName) {
1872 boolean didRemove = false;
1873 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1874 Batch b = mAlarmBatches.get(i);
1875 didRemove |= b.remove(packageName);
1876 if (b.size() == 0) {
1877 mAlarmBatches.remove(i);
1878 }
1879 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001880 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001881 final Alarm a = mPendingWhileIdleAlarms.get(i);
1882 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001883 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1884 mPendingWhileIdleAlarms.remove(i);
1885 }
1886 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001887
1888 if (didRemove) {
1889 if (DEBUG_BATCH) {
1890 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1891 }
1892 rebatchAllAlarmsLocked(true);
1893 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001894 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001895 }
1896 }
1897
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001898 void removeForStoppedLocked(int uid) {
1899 boolean didRemove = false;
1900 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1901 Batch b = mAlarmBatches.get(i);
1902 didRemove |= b.removeForStopped(uid);
1903 if (b.size() == 0) {
1904 mAlarmBatches.remove(i);
1905 }
1906 }
1907 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1908 final Alarm a = mPendingWhileIdleAlarms.get(i);
1909 try {
1910 if (a.uid == uid && ActivityManagerNative.getDefault().getAppStartMode(
1911 uid, a.packageName) == ActivityManager.APP_START_MODE_DISABLED) {
1912 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1913 mPendingWhileIdleAlarms.remove(i);
1914 }
1915 } catch (RemoteException e) {
1916 }
1917 }
1918
1919 if (didRemove) {
1920 if (DEBUG_BATCH) {
1921 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1922 }
1923 rebatchAllAlarmsLocked(true);
1924 rescheduleKernelAlarmsLocked();
1925 updateNextAlarmClockLocked();
1926 }
1927 }
1928
Adam Lesinski182f73f2013-12-05 16:48:06 -08001929 void removeUserLocked(int userHandle) {
1930 boolean didRemove = false;
1931 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1932 Batch b = mAlarmBatches.get(i);
1933 didRemove |= b.remove(userHandle);
1934 if (b.size() == 0) {
1935 mAlarmBatches.remove(i);
1936 }
1937 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001938 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001939 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001940 == userHandle) {
1941 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1942 mPendingWhileIdleAlarms.remove(i);
1943 }
1944 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001945 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
1946 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
1947 mLastAllowWhileIdleDispatch.removeAt(i);
1948 }
1949 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001950
1951 if (didRemove) {
1952 if (DEBUG_BATCH) {
1953 Slog.v(TAG, "remove(user) changed bounds; rebatching");
1954 }
1955 rebatchAllAlarmsLocked(true);
1956 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001957 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001958 }
1959 }
1960
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001961 void interactiveStateChangedLocked(boolean interactive) {
1962 if (mInteractive != interactive) {
1963 mInteractive = interactive;
1964 final long nowELAPSED = SystemClock.elapsedRealtime();
1965 if (interactive) {
1966 if (mPendingNonWakeupAlarms.size() > 0) {
1967 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1968 mTotalDelayTime += thisDelayTime;
1969 if (mMaxDelayTime < thisDelayTime) {
1970 mMaxDelayTime = thisDelayTime;
1971 }
1972 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
1973 mPendingNonWakeupAlarms.clear();
1974 }
1975 if (mNonInteractiveStartTime > 0) {
1976 long dur = nowELAPSED - mNonInteractiveStartTime;
1977 if (dur > mNonInteractiveTime) {
1978 mNonInteractiveTime = dur;
1979 }
1980 }
1981 } else {
1982 mNonInteractiveStartTime = nowELAPSED;
1983 }
1984 }
1985 }
1986
Adam Lesinski182f73f2013-12-05 16:48:06 -08001987 boolean lookForPackageLocked(String packageName) {
1988 for (int i = 0; i < mAlarmBatches.size(); i++) {
1989 Batch b = mAlarmBatches.get(i);
1990 if (b.hasPackage(packageName)) {
1991 return true;
1992 }
1993 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001994 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001995 final Alarm a = mPendingWhileIdleAlarms.get(i);
1996 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001997 return true;
1998 }
1999 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002000 return false;
2001 }
2002
2003 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002004 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002005 // The kernel never triggers alarms with negative wakeup times
2006 // so we ensure they are positive.
2007 long alarmSeconds, alarmNanoseconds;
2008 if (when < 0) {
2009 alarmSeconds = 0;
2010 alarmNanoseconds = 0;
2011 } else {
2012 alarmSeconds = when / 1000;
2013 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2014 }
2015
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002016 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002017 } else {
2018 Message msg = Message.obtain();
2019 msg.what = ALARM_EVENT;
2020
2021 mHandler.removeMessages(ALARM_EVENT);
2022 mHandler.sendMessageAtTime(msg, when);
2023 }
2024 }
2025
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002026 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002027 String prefix, String label, long nowRTC, long nowELAPSED, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002028 for (int i=list.size()-1; i>=0; i--) {
2029 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002030 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2031 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002032 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002033 }
2034 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002035
2036 private static final String labelForType(int type) {
2037 switch (type) {
2038 case RTC: return "RTC";
2039 case RTC_WAKEUP : return "RTC_WAKEUP";
2040 case ELAPSED_REALTIME : return "ELAPSED";
2041 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
2042 default:
2043 break;
2044 }
2045 return "--unknown--";
2046 }
2047
2048 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002049 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002050 for (int i=list.size()-1; i>=0; i--) {
2051 Alarm a = list.get(i);
2052 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002053 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2054 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002055 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002056 }
2057 }
2058
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002059 private native long init();
2060 private native void close(long nativeData);
2061 private native void set(long nativeData, int type, long seconds, long nanoseconds);
2062 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08002063 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002064 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002065
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002066 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002067 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002068 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002069 // batches are temporally sorted, so we need only pull from the
2070 // start of the list until we either empty it or hit a batch
2071 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07002072 while (mAlarmBatches.size() > 0) {
2073 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002074 if (batch.start > nowELAPSED) {
2075 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002076 break;
2077 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002078
Christopher Tatee0a22b32013-07-11 14:43:13 -07002079 // We will (re)schedule some alarms now; don't let that interfere
2080 // with delivery of this current batch
2081 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002082
Christopher Tatee0a22b32013-07-11 14:43:13 -07002083 final int N = batch.size();
2084 for (int i = 0; i < N; i++) {
2085 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002086
2087 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
2088 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
2089 // schedule such alarms.
2090 long lastTime = mLastAllowWhileIdleDispatch.get(alarm.uid, 0);
2091 long minTime = lastTime + mAllowWhileIdleMinTime;
2092 if (nowELAPSED < minTime) {
2093 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
2094 // alarm went off for this app. Reschedule the alarm to be in the
2095 // correct time period.
2096 alarm.whenElapsed = minTime;
2097 if (alarm.maxWhenElapsed < minTime) {
2098 alarm.maxWhenElapsed = minTime;
2099 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002100 if (RECORD_DEVICE_IDLE_ALARMS) {
2101 IdleDispatchEntry ent = new IdleDispatchEntry();
2102 ent.uid = alarm.uid;
2103 ent.pkg = alarm.operation.getCreatorPackage();
2104 ent.tag = alarm.operation.getTag("");
2105 ent.op = "RESCHEDULE";
2106 ent.elapsedRealtime = nowELAPSED;
2107 ent.argRealtime = lastTime;
2108 mAllowWhileIdleDispatches.add(ent);
2109 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002110 setImplLocked(alarm, true, false);
2111 continue;
2112 }
2113 }
2114
Christopher Tatee0a22b32013-07-11 14:43:13 -07002115 alarm.count = 1;
2116 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002117 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
2118 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002119 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002120 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002121 if (mPendingIdleUntil == alarm) {
2122 mPendingIdleUntil = null;
2123 rebatchAllAlarmsLocked(false);
2124 restorePendingWhileIdleAlarmsLocked();
2125 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002126 if (mNextWakeFromIdle == alarm) {
2127 mNextWakeFromIdle = null;
2128 rebatchAllAlarmsLocked(false);
2129 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002130
2131 // Recurring alarms may have passed several alarm intervals while the
2132 // phone was asleep or off, so pass a trigger count when sending them.
2133 if (alarm.repeatInterval > 0) {
2134 // this adjustment will be zero if we're late by
2135 // less than one full repeat interval
2136 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
2137
2138 // Also schedule its next recurrence
2139 final long delta = alarm.count * alarm.repeatInterval;
2140 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07002141 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07002142 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07002143 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
2144 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08002145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002146
Christopher Tate864d42e2014-12-02 11:48:53 -08002147 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002148 hasWakeup = true;
2149 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002150
2151 // We removed an alarm clock. Let the caller recompute the next alarm clock.
2152 if (alarm.alarmClock != null) {
2153 mNextAlarmClockMayChange = true;
2154 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07002155 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002156 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002157
Christopher Tate1590f1e2014-10-02 17:27:57 -07002158 // This is a new alarm delivery set; bump the sequence number to indicate that
2159 // all apps' alarm delivery classes should be recalculated.
2160 mCurrentSeq++;
2161 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002162 Collections.sort(triggerList, mAlarmDispatchComparator);
2163
2164 if (localLOGV) {
2165 for (int i=0; i<triggerList.size(); i++) {
2166 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
2167 }
2168 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002169
2170 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002171 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002172
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002173 /**
2174 * This Comparator sorts Alarms into increasing time order.
2175 */
2176 public static class IncreasingTimeOrder implements Comparator<Alarm> {
2177 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09002178 long when1 = a1.whenElapsed;
2179 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002180 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002181 return 1;
2182 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002183 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002184 return -1;
2185 }
2186 return 0;
2187 }
2188 }
2189
2190 private static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002191 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002192 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002193 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002194 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002195 public final IAlarmListener listener;
2196 public final String listenerTag;
2197 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002198 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002199 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002200 public final AlarmManager.AlarmClockInfo alarmClock;
2201 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002202 public final int creatorUid;
2203 public final String packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002204 public int count;
2205 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07002206 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002207 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002208 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002209 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07002210 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002211
Christopher Tate3e04b472013-10-21 17:51:31 -07002212 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002213 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
2214 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
2215 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002216 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002217 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002218 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
2219 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002220 when = _when;
2221 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07002222 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002223 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002224 repeatInterval = _interval;
2225 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002226 listener = _rec;
2227 listenerTag = _listenerTag;
2228 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07002229 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002230 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002231 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002232 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002233 packageName = _pkgName;
2234
2235 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002236 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002237
Christopher Tate14a7bb02015-10-01 10:24:31 -07002238 public static String makeTag(PendingIntent pi, String tag, int type) {
2239 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
2240 ? "*walarm*:" : "*alarm*:";
2241 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
2242 }
2243
2244 public WakeupEvent makeWakeupEvent(long nowRTC) {
2245 return new WakeupEvent(nowRTC, creatorUid,
2246 (operation != null)
2247 ? operation.getIntent().getAction()
2248 : ("<listener>:" + listenerTag));
2249 }
2250
2251 // Returns true if either matches
2252 public boolean matches(PendingIntent pi, IAlarmListener rec) {
2253 return (operation != null)
2254 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09002255 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07002256 }
2257
2258 public boolean matches(String packageName) {
2259 return (operation != null)
2260 ? packageName.equals(operation.getTargetPackage())
2261 : packageName.equals(this.packageName);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002262 }
2263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002264 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002265 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002266 StringBuilder sb = new StringBuilder(128);
2267 sb.append("Alarm{");
2268 sb.append(Integer.toHexString(System.identityHashCode(this)));
2269 sb.append(" type ");
2270 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002271 sb.append(" when ");
2272 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002273 sb.append(" ");
Christopher Tate14a7bb02015-10-01 10:24:31 -07002274 if (operation != null) {
2275 sb.append(operation.getTargetPackage());
2276 } else {
2277 sb.append(listener.asBinder().toString());
2278 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002279 sb.append('}');
2280 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002281 }
2282
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002283 public void dump(PrintWriter pw, String prefix, long nowRTC, long nowELAPSED,
2284 SimpleDateFormat sdf) {
2285 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002286 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002287 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002288 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
2289 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002290 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002291 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002292 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002293 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002294 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002295 }
2296 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002297 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002298 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002299 pw.print(" count="); pw.print(count);
2300 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002301 if (alarmClock != null) {
2302 pw.print(prefix); pw.println("Alarm clock:");
2303 pw.print(prefix); pw.print(" triggerTime=");
2304 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
2305 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
2306 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002307 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002308 if (listener != null) {
2309 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
2310 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002311 }
2312 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002313
Christopher Tatee0a22b32013-07-11 14:43:13 -07002314 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
2315 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002316 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
2317 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002318 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07002319 break;
2320 }
2321
Christopher Tatee0a22b32013-07-11 14:43:13 -07002322 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002323 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
2324 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002325 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07002326 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002327 }
2328 }
2329
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002330 long currentNonWakeupFuzzLocked(long nowELAPSED) {
2331 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
2332 if (timeSinceOn < 5*60*1000) {
2333 // If the screen has been off for 5 minutes, only delay by at most two minutes.
2334 return 2*60*1000;
2335 } else if (timeSinceOn < 30*60*1000) {
2336 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
2337 return 15*60*1000;
2338 } else {
2339 // Otherwise, we will delay by at most an hour.
2340 return 60*60*1000;
2341 }
2342 }
2343
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002344 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002345 if (duration < 15*60*1000) {
2346 // If the duration until the time is less than 15 minutes, the maximum fuzz
2347 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002348 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002349 } else if (duration < 90*60*1000) {
2350 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
2351 return 15*60*1000;
2352 } else {
2353 // Otherwise, we will fuzz by at most half an hour.
2354 return 30*60*1000;
2355 }
2356 }
2357
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002358 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
2359 if (mInteractive) {
2360 return false;
2361 }
2362 if (mLastAlarmDeliveryTime <= 0) {
2363 return false;
2364 }
minho.choo649acab2014-12-12 16:13:55 +09002365 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002366 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
2367 // and the next delivery time is in the past, then just deliver them all. This
2368 // avoids bugs where we get stuck in a loop trying to poll for alarms.
2369 return false;
2370 }
2371 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
2372 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
2373 }
2374
2375 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
2376 mLastAlarmDeliveryTime = nowELAPSED;
2377 for (int i=0; i<triggerList.size(); i++) {
2378 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07002379 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002380 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07002381 if (localLOGV) {
2382 Slog.v(TAG, "sending alarm " + alarm);
2383 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07002384 if (RECORD_ALARMS_IN_HISTORY) {
2385 if (alarm.workSource != null && alarm.workSource.size() > 0) {
2386 for (int wi=0; wi<alarm.workSource.size(); wi++) {
2387 ActivityManagerNative.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002388 alarm.operation, alarm.workSource.get(wi), alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002389 }
2390 } else {
2391 ActivityManagerNative.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002392 alarm.operation, alarm.uid, alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002393 }
2394 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002395 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002396 } catch (RuntimeException e) {
2397 Slog.w(TAG, "Failure sending alarm.", e);
2398 }
2399 }
2400 }
2401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002402 private class AlarmThread extends Thread
2403 {
2404 public AlarmThread()
2405 {
2406 super("AlarmManager");
2407 }
2408
2409 public void run()
2410 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002411 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002413 while (true)
2414 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002415 int result = waitForAlarm(mNativeData);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002416
2417 triggerList.clear();
2418
Dianne Hackbornc3527222015-05-13 14:03:20 -07002419 final long nowRTC = System.currentTimeMillis();
2420 final long nowELAPSED = SystemClock.elapsedRealtime();
2421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002422 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002423 // The kernel can give us spurious time change notifications due to
2424 // small adjustments it makes internally; we want to filter those out.
2425 final long lastTimeChangeClockTime;
2426 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07002427 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002428 lastTimeChangeClockTime = mLastTimeChangeClockTime;
2429 expectedClockTime = lastTimeChangeClockTime
2430 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07002431 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002432 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-500)
2433 || nowRTC > (expectedClockTime+500)) {
2434 // The change is by at least +/- 500 ms (or this is the first change),
2435 // let's do it!
2436 if (DEBUG_BATCH) {
2437 Slog.v(TAG, "Time changed notification from kernel; rebatching");
2438 }
2439 removeImpl(mTimeTickSender);
2440 rebatchAllAlarms();
2441 mClockReceiver.scheduleTimeTickEvent();
2442 synchronized (mLock) {
2443 mNumTimeChanged++;
2444 mLastTimeChangeClockTime = nowRTC;
2445 mLastTimeChangeRealtime = nowELAPSED;
2446 }
2447 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
2448 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
2449 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2450 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
2451
2452 // The world has changed on us, so we need to re-evaluate alarms
2453 // regardless of whether the kernel has told us one went off.
2454 result |= IS_WAKEUP_MASK;
2455 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002456 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002457
Dianne Hackbornc3527222015-05-13 14:03:20 -07002458 if (result != TIME_CHANGED_MASK) {
2459 // If this was anything besides just a time change, then figure what if
2460 // anything to do about alarms.
2461 synchronized (mLock) {
2462 if (localLOGV) Slog.v(
2463 TAG, "Checking for alarms... rtc=" + nowRTC
2464 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07002465
Dianne Hackbornc3527222015-05-13 14:03:20 -07002466 if (WAKEUP_STATS) {
2467 if ((result & IS_WAKEUP_MASK) != 0) {
2468 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
2469 int n = 0;
2470 for (WakeupEvent event : mRecentWakeups) {
2471 if (event.when > newEarliest) break;
2472 n++; // number of now-stale entries at the list head
2473 }
2474 for (int i = 0; i < n; i++) {
2475 mRecentWakeups.remove();
2476 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002477
Dianne Hackbornc3527222015-05-13 14:03:20 -07002478 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002479 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002480 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002481
2482 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2483 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
2484 // if there are no wakeup alarms and the screen is off, we can
2485 // delay what we have so far until the future.
2486 if (mPendingNonWakeupAlarms.size() == 0) {
2487 mStartCurrentDelayTime = nowELAPSED;
2488 mNextNonWakeupDeliveryTime = nowELAPSED
2489 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
2490 }
2491 mPendingNonWakeupAlarms.addAll(triggerList);
2492 mNumDelayedAlarms += triggerList.size();
2493 rescheduleKernelAlarmsLocked();
2494 updateNextAlarmClockLocked();
2495 } else {
2496 // now deliver the alarm intents; if there are pending non-wakeup
2497 // alarms, we need to merge them in to the list. note we don't
2498 // just deliver them first because we generally want non-wakeup
2499 // alarms delivered after wakeup alarms.
2500 rescheduleKernelAlarmsLocked();
2501 updateNextAlarmClockLocked();
2502 if (mPendingNonWakeupAlarms.size() > 0) {
2503 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
2504 triggerList.addAll(mPendingNonWakeupAlarms);
2505 Collections.sort(triggerList, mAlarmDispatchComparator);
2506 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2507 mTotalDelayTime += thisDelayTime;
2508 if (mMaxDelayTime < thisDelayTime) {
2509 mMaxDelayTime = thisDelayTime;
2510 }
2511 mPendingNonWakeupAlarms.clear();
2512 }
2513 deliverAlarmsLocked(triggerList, nowELAPSED);
2514 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002515 }
2516 }
2517 }
2518 }
2519 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002520
David Christieebe51fc2013-07-26 13:23:29 -07002521 /**
2522 * Attribute blame for a WakeLock.
2523 * @param pi PendingIntent to attribute blame to if ws is null.
2524 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002525 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07002526 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002527 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002528 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07002529 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002530 final boolean unimportant = pi == mTimeTickSender;
2531 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002532 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002533 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002534 } else {
2535 mWakeLock.setHistoryTag(null);
2536 }
2537 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07002538 if (ws != null) {
2539 mWakeLock.setWorkSource(ws);
2540 return;
2541 }
2542
Christopher Tate14a7bb02015-10-01 10:24:31 -07002543 final int uid = (knownUid >= 0)
2544 ? knownUid
2545 : ActivityManagerNative.getDefault().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07002546 if (uid >= 0) {
2547 mWakeLock.setWorkSource(new WorkSource(uid));
2548 return;
2549 }
2550 } catch (Exception e) {
2551 }
2552
2553 // Something went wrong; fall back to attributing the lock to the OS
2554 mWakeLock.setWorkSource(null);
2555 }
2556
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002557 private class AlarmHandler extends Handler {
2558 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002559 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
2560 public static final int LISTENER_TIMEOUT = 3;
2561 public static final int REPORT_ALARMS_ACTIVE = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562
2563 public AlarmHandler() {
2564 }
2565
2566 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002567 switch (msg.what) {
2568 case ALARM_EVENT: {
2569 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2570 synchronized (mLock) {
2571 final long nowRTC = System.currentTimeMillis();
2572 final long nowELAPSED = SystemClock.elapsedRealtime();
2573 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2574 updateNextAlarmClockLocked();
2575 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002576
Christopher Tate14a7bb02015-10-01 10:24:31 -07002577 // now trigger the alarms without the lock held
2578 for (int i=0; i<triggerList.size(); i++) {
2579 Alarm alarm = triggerList.get(i);
2580 try {
2581 alarm.operation.send();
2582 } catch (PendingIntent.CanceledException e) {
2583 if (alarm.repeatInterval > 0) {
2584 // This IntentSender is no longer valid, but this
2585 // is a repeating alarm, so toss the hoser.
2586 removeImpl(alarm.operation);
2587 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002588 }
2589 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002590 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002592
2593 case SEND_NEXT_ALARM_CLOCK_CHANGED:
2594 sendNextAlarmClockChanged();
2595 break;
2596
2597 case LISTENER_TIMEOUT:
2598 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
2599 break;
2600
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002601 case REPORT_ALARMS_ACTIVE:
2602 if (mLocalDeviceIdleController != null) {
2603 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
2604 }
2605 break;
2606
Christopher Tate14a7bb02015-10-01 10:24:31 -07002607 default:
2608 // nope, just ignore it
2609 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002610 }
2611 }
2612 }
2613
2614 class ClockReceiver extends BroadcastReceiver {
2615 public ClockReceiver() {
2616 IntentFilter filter = new IntentFilter();
2617 filter.addAction(Intent.ACTION_TIME_TICK);
2618 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002619 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002620 }
2621
2622 @Override
2623 public void onReceive(Context context, Intent intent) {
2624 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07002625 if (DEBUG_BATCH) {
2626 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
2627 }
2628 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002629 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
2630 // Since the kernel does not keep track of DST, we need to
2631 // reset the TZ information at the beginning of each day
2632 // based off of the current Zone gmt offset + userspace tracked
2633 // daylight savings information.
2634 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02002635 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002636 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07002637 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002638 }
2639 }
2640
2641 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07002642 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09002643 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07002644
2645 // Schedule this event for the amount of time that it would take to get to
2646 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09002647 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07002648
David Christieebe51fc2013-07-26 13:23:29 -07002649 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002650 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002651 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
2652 null, Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002653 }
Christopher Tate385e4982013-07-23 18:22:29 -07002654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002655 public void scheduleDateChangedEvent() {
2656 Calendar calendar = Calendar.getInstance();
2657 calendar.setTimeInMillis(System.currentTimeMillis());
2658 calendar.set(Calendar.HOUR, 0);
2659 calendar.set(Calendar.MINUTE, 0);
2660 calendar.set(Calendar.SECOND, 0);
2661 calendar.set(Calendar.MILLISECOND, 0);
2662 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07002663
2664 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002665 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
2666 AlarmManager.FLAG_STANDALONE, workSource, null,
2667 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002668 }
2669 }
2670
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002671 class InteractiveStateReceiver extends BroadcastReceiver {
2672 public InteractiveStateReceiver() {
2673 IntentFilter filter = new IntentFilter();
2674 filter.addAction(Intent.ACTION_SCREEN_OFF);
2675 filter.addAction(Intent.ACTION_SCREEN_ON);
2676 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
2677 getContext().registerReceiver(this, filter);
2678 }
2679
2680 @Override
2681 public void onReceive(Context context, Intent intent) {
2682 synchronized (mLock) {
2683 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
2684 }
2685 }
2686 }
2687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 class UninstallReceiver extends BroadcastReceiver {
2689 public UninstallReceiver() {
2690 IntentFilter filter = new IntentFilter();
2691 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2692 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002693 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08002695 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002696 // Register for events related to sdcard installation.
2697 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08002698 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002699 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002700 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002701 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002702 }
2703
2704 @Override
2705 public void onReceive(Context context, Intent intent) {
2706 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002707 String action = intent.getAction();
2708 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002709 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
2710 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
2711 for (String packageName : pkgList) {
2712 if (lookForPackageLocked(packageName)) {
2713 setResultCode(Activity.RESULT_OK);
2714 return;
2715 }
2716 }
2717 return;
2718 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002719 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002720 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
2721 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
2722 if (userHandle >= 0) {
2723 removeUserLocked(userHandle);
2724 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002725 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
2726 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
2727 if (uid >= 0) {
2728 mLastAllowWhileIdleDispatch.delete(uid);
2729 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002730 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08002731 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
2732 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
2733 // This package is being updated; don't kill its alarms.
2734 return;
2735 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002736 Uri data = intent.getData();
2737 if (data != null) {
2738 String pkg = data.getSchemeSpecificPart();
2739 if (pkg != null) {
2740 pkgList = new String[]{pkg};
2741 }
2742 }
2743 }
2744 if (pkgList != null && (pkgList.length > 0)) {
2745 for (String pkg : pkgList) {
2746 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07002747 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002748 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
2749 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
2750 if (uidStats.remove(pkg) != null) {
2751 if (uidStats.size() <= 0) {
2752 mBroadcastStats.removeAt(i);
2753 }
2754 }
2755 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002756 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002757 }
2758 }
2759 }
2760 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002761
2762 final class UidObserver extends IUidObserver.Stub {
2763 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
2764 }
2765
2766 @Override public void onUidGone(int uid) throws RemoteException {
2767 }
2768
2769 @Override public void onUidActive(int uid) throws RemoteException {
2770 }
2771
2772 @Override public void onUidIdle(int uid) throws RemoteException {
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08002773 synchronized (mLock) {
2774 removeForStoppedLocked(uid);
2775 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002776 }
2777 };
2778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002779 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002780 String pkg = pi.getCreatorPackage();
2781 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002782 return getStatsLocked(uid, pkg);
2783 }
2784
2785 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002786 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
2787 if (uidStats == null) {
2788 uidStats = new ArrayMap<String, BroadcastStats>();
2789 mBroadcastStats.put(uid, uidStats);
2790 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002791 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002792 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002793 bs = new BroadcastStats(uid, pkgName);
2794 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002795 }
2796 return bs;
2797 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002798
Christopher Tate14a7bb02015-10-01 10:24:31 -07002799 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
2800 private InFlight removeLocked(PendingIntent pi, Intent intent) {
2801 for (int i = 0; i < mInFlight.size(); i++) {
2802 if (mInFlight.get(i).mPendingIntent == pi) {
2803 return mInFlight.remove(i);
2804 }
2805 }
2806 mLog.w("No in-flight alarm for " + pi + " " + intent);
2807 return null;
2808 }
2809
2810 private InFlight removeLocked(IBinder listener) {
2811 for (int i = 0; i < mInFlight.size(); i++) {
2812 if (mInFlight.get(i).mListener == listener) {
2813 return mInFlight.remove(i);
2814 }
2815 }
2816 mLog.w("No in-flight alarm for listener " + listener);
2817 return null;
2818 }
2819
2820 private void updateStatsLocked(InFlight inflight) {
2821 final long nowELAPSED = SystemClock.elapsedRealtime();
2822 BroadcastStats bs = inflight.mBroadcastStats;
2823 bs.nesting--;
2824 if (bs.nesting <= 0) {
2825 bs.nesting = 0;
2826 bs.aggregateTime += nowELAPSED - bs.startTime;
2827 }
2828 FilterStats fs = inflight.mFilterStats;
2829 fs.nesting--;
2830 if (fs.nesting <= 0) {
2831 fs.nesting = 0;
2832 fs.aggregateTime += nowELAPSED - fs.startTime;
2833 }
2834 if (RECORD_ALARMS_IN_HISTORY) {
2835 if (inflight.mWorkSource != null && inflight.mWorkSource.size() > 0) {
2836 for (int wi=0; wi<inflight.mWorkSource.size(); wi++) {
2837 ActivityManagerNative.noteAlarmFinish(
2838 inflight.mPendingIntent, inflight.mWorkSource.get(wi), inflight.mTag);
2839 }
2840 } else {
2841 ActivityManagerNative.noteAlarmFinish(
2842 inflight.mPendingIntent, inflight.mUid, inflight.mTag);
2843 }
2844 }
2845 }
2846
2847 private void updateTrackingLocked(InFlight inflight) {
2848 if (inflight != null) {
2849 updateStatsLocked(inflight);
2850 }
2851 mBroadcastRefCount--;
2852 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002853 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002854 mWakeLock.release();
2855 if (mInFlight.size() > 0) {
2856 mLog.w("Finished all dispatches with " + mInFlight.size()
2857 + " remaining inflights");
2858 for (int i=0; i<mInFlight.size(); i++) {
2859 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
2860 }
2861 mInFlight.clear();
2862 }
2863 } else {
2864 // the next of our alarms is now in flight. reattribute the wakelock.
2865 if (mInFlight.size() > 0) {
2866 InFlight inFlight = mInFlight.get(0);
2867 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
2868 inFlight.mAlarmType, inFlight.mTag, -1, false);
2869 } else {
2870 // should never happen
2871 mLog.w("Alarm wakelock still held but sent queue empty");
2872 mWakeLock.setWorkSource(null);
2873 }
2874 }
2875 }
2876
2877 /**
2878 * Callback that arrives when a direct-call alarm reports that delivery has finished
2879 */
2880 @Override
2881 public void alarmComplete(IBinder who) {
2882 if (who == null) {
2883 Slog.w(TAG, "Invalid alarmComplete: uid=" + Binder.getCallingUid()
2884 + " pid=" + Binder.getCallingPid());
2885 return;
2886 }
2887
2888 final long ident = Binder.clearCallingIdentity();
2889 try {
2890 synchronized (mLock) {
2891 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
2892 InFlight inflight = removeLocked(who);
2893 if (inflight != null) {
2894 if (DEBUG_LISTENER_CALLBACK) {
2895 Slog.i(TAG, "alarmComplete() from " + who);
2896 }
2897 updateTrackingLocked(inflight);
2898 } else {
2899 // Delivery timed out, and the timeout handling already took care of
2900 // updating our tracking here, so we needn't do anything further.
2901 if (DEBUG_LISTENER_CALLBACK) {
2902 Slog.i(TAG, "Late alarmComplete() from " + who);
2903 }
2904 }
2905 }
2906 } finally {
2907 Binder.restoreCallingIdentity(ident);
2908 }
2909 }
2910
2911 /**
2912 * Callback that arrives when a PendingIntent alarm has finished delivery
2913 */
2914 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002915 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
2916 String resultData, Bundle resultExtras) {
2917 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002918 updateTrackingLocked(removeLocked(pi, intent));
2919 }
2920 }
2921
2922 /**
2923 * Timeout of a direct-call alarm delivery
2924 */
2925 public void alarmTimedOut(IBinder who) {
2926 synchronized (mLock) {
2927 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08002928 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002929 // TODO: implement ANR policy for the target
2930 if (DEBUG_LISTENER_CALLBACK) {
2931 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002932 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002933 updateTrackingLocked(inflight);
Dianne Hackborn81038902012-11-26 17:04:09 -08002934 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002935 if (DEBUG_LISTENER_CALLBACK) {
2936 Slog.i(TAG, "Spurious timeout of listener " + who);
2937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002938 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002939 }
2940 }
2941
2942 /**
2943 * Deliver an alarm and set up the post-delivery handling appropriately
2944 */
2945 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
2946 if (alarm.operation != null) {
2947 // PendingIntent alarm
2948 try {
2949 alarm.operation.send(getContext(), 0,
2950 mBackgroundIntent.putExtra(
2951 Intent.EXTRA_ALARM_COUNT, alarm.count),
2952 mDeliveryTracker, mHandler, null,
2953 allowWhileIdle ? mIdleOptions : null);
2954 } catch (PendingIntent.CanceledException e) {
2955 if (alarm.repeatInterval > 0) {
2956 // This IntentSender is no longer valid, but this
2957 // is a repeating alarm, so toss it
2958 removeImpl(alarm.operation);
2959 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08002960 // No actual delivery was possible, so the delivery tracker's
2961 // 'finished' callback won't be invoked. We also don't need
2962 // to do any wakelock or stats tracking, so we have nothing
2963 // left to do here but go on to the next thing.
2964 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002965 }
2966 } else {
2967 // Direct listener callback alarm
2968 try {
2969 if (DEBUG_LISTENER_CALLBACK) {
2970 Slog.v(TAG, "Alarm to uid=" + alarm.uid
2971 + " listener=" + alarm.listener.asBinder());
2972 }
2973 alarm.listener.doAlarm(this);
2974 mHandler.sendMessageDelayed(
2975 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
2976 alarm.listener.asBinder()),
2977 mConstants.LISTENER_TIMEOUT);
2978 } catch (Exception e) {
2979 if (DEBUG_LISTENER_CALLBACK) {
2980 Slog.i(TAG, "Alarm undeliverable to listener "
2981 + alarm.listener.asBinder(), e);
2982 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08002983 // As in the PendingIntent.CanceledException case, delivery of the
2984 // alarm was not possible, so we have no wakelock or timeout or
2985 // stats management to do. It threw before we posted the delayed
2986 // timeout message, so we're done here.
2987 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002988 }
2989 }
2990
2991 // The alarm is now in flight; now arrange wakelock and stats tracking
2992 if (mBroadcastRefCount == 0) {
2993 setWakelockWorkSource(alarm.operation, alarm.workSource,
2994 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
2995 true);
2996 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002997 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002998 }
2999 final InFlight inflight = new InFlight(AlarmManagerService.this,
3000 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
3001 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
3002 mInFlight.add(inflight);
3003 mBroadcastRefCount++;
3004
3005 if (allowWhileIdle) {
3006 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
3007 mLastAllowWhileIdleDispatch.put(alarm.uid, nowELAPSED);
3008 if (RECORD_DEVICE_IDLE_ALARMS) {
3009 IdleDispatchEntry ent = new IdleDispatchEntry();
3010 ent.uid = alarm.uid;
3011 ent.pkg = alarm.packageName;
3012 ent.tag = alarm.statsTag;
3013 ent.op = "DELIVER";
3014 ent.elapsedRealtime = nowELAPSED;
3015 mAllowWhileIdleDispatches.add(ent);
3016 }
3017 }
3018
3019 final BroadcastStats bs = inflight.mBroadcastStats;
3020 bs.count++;
3021 if (bs.nesting == 0) {
3022 bs.nesting = 1;
3023 bs.startTime = nowELAPSED;
3024 } else {
3025 bs.nesting++;
3026 }
3027 final FilterStats fs = inflight.mFilterStats;
3028 fs.count++;
3029 if (fs.nesting == 0) {
3030 fs.nesting = 1;
3031 fs.startTime = nowELAPSED;
3032 } else {
3033 fs.nesting++;
3034 }
3035 if (alarm.type == ELAPSED_REALTIME_WAKEUP
3036 || alarm.type == RTC_WAKEUP) {
3037 bs.numWakeup++;
3038 fs.numWakeup++;
3039 if (alarm.workSource != null && alarm.workSource.size() > 0) {
3040 for (int wi=0; wi<alarm.workSource.size(); wi++) {
3041 ActivityManagerNative.noteWakeupAlarm(
3042 alarm.operation, alarm.workSource.get(wi),
3043 alarm.workSource.getName(wi), alarm.statsTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08003044 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003045 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003046 ActivityManagerNative.noteWakeupAlarm(
3047 alarm.operation, -1, alarm.packageName, alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003048 }
3049 }
3050 }
3051 }
3052}