blob: 960fb4bcbd0780843e039d6d2a8f55deb4a9b5b4 [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
1236 // direct-callback alarms must be wakeup alarms (otherwise they should just be
1237 // posting work to a Handler)
1238 if (directReceiver != null) {
1239 if (type != RTC_WAKEUP && type != ELAPSED_REALTIME_WAKEUP) {
1240 throw new IllegalArgumentException("Only wakeup alarms can use AlarmReceivers");
1241 }
1242 }
1243
Adam Lesinski182f73f2013-12-05 16:48:06 -08001244 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001245 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001246 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001247 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001248 }
1249
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001250 // No incoming callers can request either WAKE_FROM_IDLE or
1251 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1252 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1253 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1254
1255 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1256 // manager when to come out of idle mode, which is only for DeviceIdleController.
1257 if (callingUid != Process.SYSTEM_UID) {
1258 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1259 }
1260
1261 // If the caller is a core system component, and not calling to do work on behalf
1262 // of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED. This means we
1263 // will allow these alarms to go off as normal even while idle, with no timing
1264 // restrictions.
1265 if (callingUid < Process.FIRST_APPLICATION_UID && workSource == null) {
1266 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1267 }
1268
1269 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001270 if (windowLength == AlarmManager.WINDOW_EXACT) {
1271 flags |= AlarmManager.FLAG_STANDALONE;
1272 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001273
1274 // If this alarm is for an alarm clock, then it must be standalone and we will
1275 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001276 if (alarmClock != null) {
1277 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
1278 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001279
Christopher Tate14a7bb02015-10-01 10:24:31 -07001280 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1281 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001282 }
Christopher Tate89779822012-08-31 14:40:03 -07001283
Adam Lesinski182f73f2013-12-05 16:48:06 -08001284 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001285 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001286 getContext().enforceCallingOrSelfPermission(
1287 "android.permission.SET_TIME",
1288 "setTime");
1289
Greg Hackmann0cab8962014-02-21 16:35:52 -08001290 if (mNativeData == 0) {
1291 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1292 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001293 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001294
1295 synchronized (mLock) {
1296 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001298 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001299
1300 @Override
1301 public void setTimeZone(String tz) {
1302 getContext().enforceCallingOrSelfPermission(
1303 "android.permission.SET_TIME_ZONE",
1304 "setTimeZone");
1305
1306 final long oldId = Binder.clearCallingIdentity();
1307 try {
1308 setTimeZoneImpl(tz);
1309 } finally {
1310 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311 }
1312 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001313
Adam Lesinski182f73f2013-12-05 16:48:06 -08001314 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001315 public void remove(PendingIntent operation, IAlarmListener listener) {
1316 if (operation == null && listener == null) {
1317 Slog.w(TAG, "remove() with no intent or listener");
1318 return;
1319 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001320
Christopher Tate14a7bb02015-10-01 10:24:31 -07001321 synchronized (mLock) {
1322 removeLocked(operation, listener);
1323 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001325
Adam Lesinski182f73f2013-12-05 16:48:06 -08001326 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001327 public long getNextWakeFromIdleTime() {
1328 return getNextWakeFromIdleTimeImpl();
1329 }
1330
1331 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001332 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001333 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1334 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1335 "getNextAlarmClock", null);
1336
1337 return getNextAlarmClockImpl(userId);
1338 }
1339
1340 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001341 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1342 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1343 != PackageManager.PERMISSION_GRANTED) {
1344 pw.println("Permission Denial: can't dump AlarmManager from from pid="
1345 + Binder.getCallingPid()
1346 + ", uid=" + Binder.getCallingUid());
1347 return;
Christopher Tate4cb338d2013-07-26 13:11:31 -07001348 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001349
Adam Lesinski182f73f2013-12-05 16:48:06 -08001350 dumpImpl(pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001351 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001352 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001353
Adam Lesinski182f73f2013-12-05 16:48:06 -08001354 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 synchronized (mLock) {
1356 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001357 mConstants.dump(pw);
1358 pw.println();
1359
Christopher Tatee0a22b32013-07-11 14:43:13 -07001360 final long nowRTC = System.currentTimeMillis();
1361 final long nowELAPSED = SystemClock.elapsedRealtime();
1362 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1363
Dianne Hackborna750a632015-06-16 17:18:23 -07001364 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001365 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001366 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001367 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001368 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001369 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001370 pw.print(" mLastTimeChangeRealtime=");
Dianne Hackbornc3527222015-05-13 14:03:20 -07001371 TimeUtils.formatDuration(mLastTimeChangeRealtime, pw);
1372 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001373 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001374 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001375 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1376 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001377 pw.print(" Max wakeup delay: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001378 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1379 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001380 pw.print(" Time since last dispatch: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001381 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1382 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001383 pw.print(" Next non-wakeup delivery time: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001384 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1385 pw.println();
1386 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001387
1388 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1389 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001390 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001391 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001392 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001393 pw.print(" Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001394 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001395 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001396
John Spurlock604a5ee2015-06-01 12:27:22 -04001397 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001398 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001399 final TreeSet<Integer> users = new TreeSet<>();
1400 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1401 users.add(mNextAlarmClockForUser.keyAt(i));
1402 }
1403 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1404 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1405 }
1406 for (int user : users) {
1407 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1408 final long time = next != null ? next.getTriggerTime() : 0;
1409 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001410 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001411 pw.print(" pendingSend:"); pw.print(pendingSend);
1412 pw.print(" time:"); pw.print(time);
1413 if (time > 0) {
1414 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1415 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1416 }
1417 pw.println();
1418 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001419 if (mAlarmBatches.size() > 0) {
1420 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001421 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001422 pw.println(mAlarmBatches.size());
1423 for (Batch b : mAlarmBatches) {
1424 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001425 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001426 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001428 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001429 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001430 pw.println(" Idle mode state:");
1431 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001432 if (mPendingIdleUntil != null) {
1433 pw.println(mPendingIdleUntil);
Dianne Hackbornf3831292015-10-15 14:51:06 -07001434 mPendingIdleUntil.dump(pw, " ", nowRTC, nowELAPSED, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001435 } else {
1436 pw.println("null");
1437 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001438 pw.println(" Pending alarms:");
1439 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001440 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001441 if (mNextWakeFromIdle != null) {
1442 pw.println();
1443 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
1444 mNextWakeFromIdle.dump(pw, " ", nowRTC, nowELAPSED, sdf);
1445 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001446
1447 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001448 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001449 if (mPendingNonWakeupAlarms.size() > 0) {
1450 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001451 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001452 } else {
1453 pw.println("(none)");
1454 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001455 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001456 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1457 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001458 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001459 pw.print(", max non-interactive time: ");
1460 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1461 pw.println();
1462
1463 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001464 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001465 pw.println();
1466
Christopher Tate7f2a0352015-12-08 10:24:33 -08001467 if (mInFlight.size() > 0) {
1468 pw.println("Outstanding deliveries:");
1469 for (int i = 0; i < mInFlight.size(); i++) {
1470 pw.print(" #"); pw.print(i); pw.print(": ");
1471 pw.println(mInFlight.get(i));
1472 }
1473 pw.println();
1474 }
1475
Dianne Hackborna750a632015-06-16 17:18:23 -07001476 pw.print(" mAllowWhileIdleMinTime=");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001477 TimeUtils.formatDuration(mAllowWhileIdleMinTime, pw);
1478 pw.println();
1479 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001480 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001481 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
1482 pw.print(" UID ");
1483 UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
1484 pw.print(": ");
1485 TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i),
1486 nowELAPSED, pw);
1487 pw.println();
1488 }
1489 }
1490 pw.println();
1491
Dianne Hackborn81038902012-11-26 17:04:09 -08001492 if (mLog.dump(pw, " Recent problems", " ")) {
1493 pw.println();
1494 }
1495
1496 final FilterStats[] topFilters = new FilterStats[10];
1497 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1498 @Override
1499 public int compare(FilterStats lhs, FilterStats rhs) {
1500 if (lhs.aggregateTime < rhs.aggregateTime) {
1501 return 1;
1502 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1503 return -1;
1504 }
1505 return 0;
1506 }
1507 };
1508 int len = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001509 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1510 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1511 for (int ip=0; ip<uidStats.size(); ip++) {
1512 BroadcastStats bs = uidStats.valueAt(ip);
1513 for (int is=0; is<bs.filterStats.size(); is++) {
1514 FilterStats fs = bs.filterStats.valueAt(is);
1515 int pos = len > 0
1516 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1517 if (pos < 0) {
1518 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001519 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001520 if (pos < topFilters.length) {
1521 int copylen = topFilters.length - pos - 1;
1522 if (copylen > 0) {
1523 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1524 }
1525 topFilters[pos] = fs;
1526 if (len < topFilters.length) {
1527 len++;
1528 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001529 }
1530 }
1531 }
1532 }
1533 if (len > 0) {
1534 pw.println(" Top Alarms:");
1535 for (int i=0; i<len; i++) {
1536 FilterStats fs = topFilters[i];
1537 pw.print(" ");
1538 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1539 TimeUtils.formatDuration(fs.aggregateTime, pw);
1540 pw.print(" running, "); pw.print(fs.numWakeup);
1541 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001542 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1543 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001544 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001545 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001546 pw.println();
1547 }
1548 }
1549
1550 pw.println(" ");
1551 pw.println(" Alarm Stats:");
1552 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001553 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1554 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1555 for (int ip=0; ip<uidStats.size(); ip++) {
1556 BroadcastStats bs = uidStats.valueAt(ip);
1557 pw.print(" ");
1558 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1559 UserHandle.formatUid(pw, bs.mUid);
1560 pw.print(":");
1561 pw.print(bs.mPackageName);
1562 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1563 pw.print(" running, "); pw.print(bs.numWakeup);
1564 pw.println(" wakeups:");
1565 tmpFilters.clear();
1566 for (int is=0; is<bs.filterStats.size(); is++) {
1567 tmpFilters.add(bs.filterStats.valueAt(is));
1568 }
1569 Collections.sort(tmpFilters, comparator);
1570 for (int i=0; i<tmpFilters.size(); i++) {
1571 FilterStats fs = tmpFilters.get(i);
1572 pw.print(" ");
1573 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1574 TimeUtils.formatDuration(fs.aggregateTime, pw);
1575 pw.print(" "); pw.print(fs.numWakeup);
1576 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001577 pw.print(" alarms, last ");
1578 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1579 pw.println(":");
1580 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001581 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001582 pw.println();
1583 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 }
1585 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001586
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001587 if (RECORD_DEVICE_IDLE_ALARMS) {
1588 pw.println();
1589 pw.println(" Allow while idle dispatches:");
1590 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
1591 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
1592 pw.print(" ");
1593 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
1594 pw.print(": ");
1595 UserHandle.formatUid(pw, ent.uid);
1596 pw.print(":");
1597 pw.println(ent.pkg);
1598 if (ent.op != null) {
1599 pw.print(" ");
1600 pw.print(ent.op);
1601 pw.print(" / ");
1602 pw.print(ent.tag);
1603 if (ent.argRealtime != 0) {
1604 pw.print(" (");
1605 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
1606 pw.print(")");
1607 }
1608 pw.println();
1609 }
1610 }
1611 }
1612
Christopher Tate18a75f12013-07-01 18:18:59 -07001613 if (WAKEUP_STATS) {
1614 pw.println();
1615 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001616 long last = -1;
1617 for (WakeupEvent event : mRecentWakeups) {
1618 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1619 pw.print('|');
1620 if (last < 0) {
1621 pw.print('0');
1622 } else {
1623 pw.print(event.when - last);
1624 }
1625 last = event.when;
1626 pw.print('|'); pw.print(event.uid);
1627 pw.print('|'); pw.print(event.action);
1628 pw.println();
1629 }
1630 pw.println();
1631 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 }
1633 }
1634
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001635 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001636 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
1637 PrintWriter pw = new PrintWriter(bs);
1638 final long nowRTC = System.currentTimeMillis();
1639 final long nowELAPSED = SystemClock.elapsedRealtime();
1640 final int NZ = mAlarmBatches.size();
1641 for (int iz = 0; iz < NZ; iz++) {
1642 Batch bz = mAlarmBatches.get(iz);
1643 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001644 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001645 pw.flush();
1646 Slog.v(TAG, bs.toString());
1647 bs.reset();
1648 }
1649 }
1650
1651 private boolean validateConsistencyLocked() {
1652 if (DEBUG_VALIDATE) {
1653 long lastTime = Long.MIN_VALUE;
1654 final int N = mAlarmBatches.size();
1655 for (int i = 0; i < N; i++) {
1656 Batch b = mAlarmBatches.get(i);
1657 if (b.start >= lastTime) {
1658 // duplicate start times are okay because of standalone batches
1659 lastTime = b.start;
1660 } else {
1661 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001662 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1663 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001664 return false;
1665 }
1666 }
1667 }
1668 return true;
1669 }
1670
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001671 private Batch findFirstWakeupBatchLocked() {
1672 final int N = mAlarmBatches.size();
1673 for (int i = 0; i < N; i++) {
1674 Batch b = mAlarmBatches.get(i);
1675 if (b.hasWakeups()) {
1676 return b;
1677 }
1678 }
1679 return null;
1680 }
1681
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001682 long getNextWakeFromIdleTimeImpl() {
1683 synchronized (mLock) {
1684 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
1685 }
1686 }
1687
1688 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001689 synchronized (mLock) {
1690 return mNextAlarmClockForUser.get(userId);
1691 }
1692 }
1693
1694 /**
1695 * Recomputes the next alarm clock for all users.
1696 */
1697 private void updateNextAlarmClockLocked() {
1698 if (!mNextAlarmClockMayChange) {
1699 return;
1700 }
1701 mNextAlarmClockMayChange = false;
1702
Jose Lima235510e2014-08-13 12:50:01 -07001703 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001704 nextForUser.clear();
1705
1706 final int N = mAlarmBatches.size();
1707 for (int i = 0; i < N; i++) {
1708 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
1709 final int M = alarms.size();
1710
1711 for (int j = 0; j < M; j++) {
1712 Alarm a = alarms.get(j);
1713 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001714 final int userId = UserHandle.getUserId(a.uid);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001715
1716 if (DEBUG_ALARM_CLOCK) {
1717 Log.v(TAG, "Found AlarmClockInfo at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001718 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02001719 " for user " + userId);
1720 }
1721
1722 // Alarms and batches are sorted by time, no need to compare times here.
1723 if (nextForUser.get(userId) == null) {
1724 nextForUser.put(userId, a.alarmClock);
1725 }
1726 }
1727 }
1728 }
1729
1730 // Update mNextAlarmForUser with new values.
1731 final int NN = nextForUser.size();
1732 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07001733 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001734 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001735 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001736 if (!newAlarm.equals(currentAlarm)) {
1737 updateNextAlarmInfoForUserLocked(userId, newAlarm);
1738 }
1739 }
1740
1741 // Remove users without any alarm clocks scheduled.
1742 final int NNN = mNextAlarmClockForUser.size();
1743 for (int i = NNN - 1; i >= 0; i--) {
1744 int userId = mNextAlarmClockForUser.keyAt(i);
1745 if (nextForUser.get(userId) == null) {
1746 updateNextAlarmInfoForUserLocked(userId, null);
1747 }
1748 }
1749 }
1750
Jose Lima235510e2014-08-13 12:50:01 -07001751 private void updateNextAlarmInfoForUserLocked(int userId,
1752 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001753 if (alarmClock != null) {
1754 if (DEBUG_ALARM_CLOCK) {
1755 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001756 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02001757 }
1758 mNextAlarmClockForUser.put(userId, alarmClock);
1759 } else {
1760 if (DEBUG_ALARM_CLOCK) {
1761 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
1762 }
1763 mNextAlarmClockForUser.remove(userId);
1764 }
1765
1766 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
1767 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1768 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1769 }
1770
1771 /**
1772 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
1773 * for which alarm clocks have changed since the last call to this.
1774 *
1775 * Do not call with a lock held. Only call from mHandler's thread.
1776 *
1777 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
1778 */
1779 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07001780 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001781 pendingUsers.clear();
1782
1783 synchronized (mLock) {
1784 final int N = mPendingSendNextAlarmClockChangedForUser.size();
1785 for (int i = 0; i < N; i++) {
1786 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
1787 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
1788 }
1789 mPendingSendNextAlarmClockChangedForUser.clear();
1790 }
1791
1792 final int N = pendingUsers.size();
1793 for (int i = 0; i < N; i++) {
1794 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001795 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001796 Settings.System.putStringForUser(getContext().getContentResolver(),
1797 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01001798 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02001799 userId);
1800
1801 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
1802 new UserHandle(userId));
1803 }
1804 }
1805
1806 /**
1807 * Formats an alarm like platform/packages/apps/DeskClock used to.
1808 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01001809 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
1810 int userId) {
1811 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02001812 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
1813 return (info == null) ? "" :
1814 DateFormat.format(pattern, info.getTriggerTime()).toString();
1815 }
1816
Adam Lesinski182f73f2013-12-05 16:48:06 -08001817 void rescheduleKernelAlarmsLocked() {
1818 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
1819 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001820 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001821 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001822 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001823 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07001824 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001825 mNextWakeup = firstWakeup.start;
1826 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001827 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001828 if (firstBatch != firstWakeup) {
1829 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001830 }
1831 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001832 if (mPendingNonWakeupAlarms.size() > 0) {
1833 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
1834 nextNonWakeup = mNextNonWakeupDeliveryTime;
1835 }
1836 }
Prashant Malani753e9e02015-06-10 17:43:49 -07001837 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001838 mNextNonWakeup = nextNonWakeup;
1839 setLocked(ELAPSED_REALTIME, nextNonWakeup);
1840 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001841 }
1842
Christopher Tate14a7bb02015-10-01 10:24:31 -07001843 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001844 boolean didRemove = false;
1845 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1846 Batch b = mAlarmBatches.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -07001847 didRemove |= b.remove(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001848 if (b.size() == 0) {
1849 mAlarmBatches.remove(i);
1850 }
1851 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001852 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001853 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001854 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1855 mPendingWhileIdleAlarms.remove(i);
1856 }
1857 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001858
1859 if (didRemove) {
1860 if (DEBUG_BATCH) {
1861 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
1862 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001863 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001864 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001865 mPendingIdleUntil = null;
1866 restorePending = true;
1867 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001868 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001869 mNextWakeFromIdle = null;
1870 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001871 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001872 if (restorePending) {
1873 restorePendingWhileIdleAlarmsLocked();
1874 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001875 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001876 }
1877 }
1878
1879 void removeLocked(String packageName) {
1880 boolean didRemove = false;
1881 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1882 Batch b = mAlarmBatches.get(i);
1883 didRemove |= b.remove(packageName);
1884 if (b.size() == 0) {
1885 mAlarmBatches.remove(i);
1886 }
1887 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001888 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001889 final Alarm a = mPendingWhileIdleAlarms.get(i);
1890 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001891 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1892 mPendingWhileIdleAlarms.remove(i);
1893 }
1894 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001895
1896 if (didRemove) {
1897 if (DEBUG_BATCH) {
1898 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1899 }
1900 rebatchAllAlarmsLocked(true);
1901 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001902 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001903 }
1904 }
1905
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001906 void removeForStoppedLocked(int uid) {
1907 boolean didRemove = false;
1908 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1909 Batch b = mAlarmBatches.get(i);
1910 didRemove |= b.removeForStopped(uid);
1911 if (b.size() == 0) {
1912 mAlarmBatches.remove(i);
1913 }
1914 }
1915 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1916 final Alarm a = mPendingWhileIdleAlarms.get(i);
1917 try {
1918 if (a.uid == uid && ActivityManagerNative.getDefault().getAppStartMode(
1919 uid, a.packageName) == ActivityManager.APP_START_MODE_DISABLED) {
1920 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1921 mPendingWhileIdleAlarms.remove(i);
1922 }
1923 } catch (RemoteException e) {
1924 }
1925 }
1926
1927 if (didRemove) {
1928 if (DEBUG_BATCH) {
1929 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1930 }
1931 rebatchAllAlarmsLocked(true);
1932 rescheduleKernelAlarmsLocked();
1933 updateNextAlarmClockLocked();
1934 }
1935 }
1936
Adam Lesinski182f73f2013-12-05 16:48:06 -08001937 void removeUserLocked(int userHandle) {
1938 boolean didRemove = false;
1939 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1940 Batch b = mAlarmBatches.get(i);
1941 didRemove |= b.remove(userHandle);
1942 if (b.size() == 0) {
1943 mAlarmBatches.remove(i);
1944 }
1945 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001946 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001947 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001948 == userHandle) {
1949 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1950 mPendingWhileIdleAlarms.remove(i);
1951 }
1952 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001953 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
1954 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
1955 mLastAllowWhileIdleDispatch.removeAt(i);
1956 }
1957 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001958
1959 if (didRemove) {
1960 if (DEBUG_BATCH) {
1961 Slog.v(TAG, "remove(user) changed bounds; rebatching");
1962 }
1963 rebatchAllAlarmsLocked(true);
1964 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001965 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001966 }
1967 }
1968
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001969 void interactiveStateChangedLocked(boolean interactive) {
1970 if (mInteractive != interactive) {
1971 mInteractive = interactive;
1972 final long nowELAPSED = SystemClock.elapsedRealtime();
1973 if (interactive) {
1974 if (mPendingNonWakeupAlarms.size() > 0) {
1975 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1976 mTotalDelayTime += thisDelayTime;
1977 if (mMaxDelayTime < thisDelayTime) {
1978 mMaxDelayTime = thisDelayTime;
1979 }
1980 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
1981 mPendingNonWakeupAlarms.clear();
1982 }
1983 if (mNonInteractiveStartTime > 0) {
1984 long dur = nowELAPSED - mNonInteractiveStartTime;
1985 if (dur > mNonInteractiveTime) {
1986 mNonInteractiveTime = dur;
1987 }
1988 }
1989 } else {
1990 mNonInteractiveStartTime = nowELAPSED;
1991 }
1992 }
1993 }
1994
Adam Lesinski182f73f2013-12-05 16:48:06 -08001995 boolean lookForPackageLocked(String packageName) {
1996 for (int i = 0; i < mAlarmBatches.size(); i++) {
1997 Batch b = mAlarmBatches.get(i);
1998 if (b.hasPackage(packageName)) {
1999 return true;
2000 }
2001 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002002 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002003 final Alarm a = mPendingWhileIdleAlarms.get(i);
2004 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002005 return true;
2006 }
2007 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002008 return false;
2009 }
2010
2011 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002012 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002013 // The kernel never triggers alarms with negative wakeup times
2014 // so we ensure they are positive.
2015 long alarmSeconds, alarmNanoseconds;
2016 if (when < 0) {
2017 alarmSeconds = 0;
2018 alarmNanoseconds = 0;
2019 } else {
2020 alarmSeconds = when / 1000;
2021 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2022 }
2023
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002024 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002025 } else {
2026 Message msg = Message.obtain();
2027 msg.what = ALARM_EVENT;
2028
2029 mHandler.removeMessages(ALARM_EVENT);
2030 mHandler.sendMessageAtTime(msg, when);
2031 }
2032 }
2033
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002034 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002035 String prefix, String label, long nowRTC, long nowELAPSED, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002036 for (int i=list.size()-1; i>=0; i--) {
2037 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002038 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2039 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002040 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002041 }
2042 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002043
2044 private static final String labelForType(int type) {
2045 switch (type) {
2046 case RTC: return "RTC";
2047 case RTC_WAKEUP : return "RTC_WAKEUP";
2048 case ELAPSED_REALTIME : return "ELAPSED";
2049 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
2050 default:
2051 break;
2052 }
2053 return "--unknown--";
2054 }
2055
2056 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002057 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002058 for (int i=list.size()-1; i>=0; i--) {
2059 Alarm a = list.get(i);
2060 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002061 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2062 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002063 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002064 }
2065 }
2066
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002067 private native long init();
2068 private native void close(long nativeData);
2069 private native void set(long nativeData, int type, long seconds, long nanoseconds);
2070 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08002071 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002072 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002073
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002074 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002075 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002076 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002077 // batches are temporally sorted, so we need only pull from the
2078 // start of the list until we either empty it or hit a batch
2079 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07002080 while (mAlarmBatches.size() > 0) {
2081 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002082 if (batch.start > nowELAPSED) {
2083 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002084 break;
2085 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002086
Christopher Tatee0a22b32013-07-11 14:43:13 -07002087 // We will (re)schedule some alarms now; don't let that interfere
2088 // with delivery of this current batch
2089 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002090
Christopher Tatee0a22b32013-07-11 14:43:13 -07002091 final int N = batch.size();
2092 for (int i = 0; i < N; i++) {
2093 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002094
2095 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
2096 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
2097 // schedule such alarms.
2098 long lastTime = mLastAllowWhileIdleDispatch.get(alarm.uid, 0);
2099 long minTime = lastTime + mAllowWhileIdleMinTime;
2100 if (nowELAPSED < minTime) {
2101 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
2102 // alarm went off for this app. Reschedule the alarm to be in the
2103 // correct time period.
2104 alarm.whenElapsed = minTime;
2105 if (alarm.maxWhenElapsed < minTime) {
2106 alarm.maxWhenElapsed = minTime;
2107 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002108 if (RECORD_DEVICE_IDLE_ALARMS) {
2109 IdleDispatchEntry ent = new IdleDispatchEntry();
2110 ent.uid = alarm.uid;
2111 ent.pkg = alarm.operation.getCreatorPackage();
2112 ent.tag = alarm.operation.getTag("");
2113 ent.op = "RESCHEDULE";
2114 ent.elapsedRealtime = nowELAPSED;
2115 ent.argRealtime = lastTime;
2116 mAllowWhileIdleDispatches.add(ent);
2117 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002118 setImplLocked(alarm, true, false);
2119 continue;
2120 }
2121 }
2122
Christopher Tatee0a22b32013-07-11 14:43:13 -07002123 alarm.count = 1;
2124 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002125 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
2126 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002127 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002128 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002129 if (mPendingIdleUntil == alarm) {
2130 mPendingIdleUntil = null;
2131 rebatchAllAlarmsLocked(false);
2132 restorePendingWhileIdleAlarmsLocked();
2133 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002134 if (mNextWakeFromIdle == alarm) {
2135 mNextWakeFromIdle = null;
2136 rebatchAllAlarmsLocked(false);
2137 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002138
2139 // Recurring alarms may have passed several alarm intervals while the
2140 // phone was asleep or off, so pass a trigger count when sending them.
2141 if (alarm.repeatInterval > 0) {
2142 // this adjustment will be zero if we're late by
2143 // less than one full repeat interval
2144 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
2145
2146 // Also schedule its next recurrence
2147 final long delta = alarm.count * alarm.repeatInterval;
2148 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07002149 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07002150 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07002151 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
2152 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08002153 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002154
Christopher Tate864d42e2014-12-02 11:48:53 -08002155 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002156 hasWakeup = true;
2157 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002158
2159 // We removed an alarm clock. Let the caller recompute the next alarm clock.
2160 if (alarm.alarmClock != null) {
2161 mNextAlarmClockMayChange = true;
2162 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07002163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002164 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002165
Christopher Tate1590f1e2014-10-02 17:27:57 -07002166 // This is a new alarm delivery set; bump the sequence number to indicate that
2167 // all apps' alarm delivery classes should be recalculated.
2168 mCurrentSeq++;
2169 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002170 Collections.sort(triggerList, mAlarmDispatchComparator);
2171
2172 if (localLOGV) {
2173 for (int i=0; i<triggerList.size(); i++) {
2174 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
2175 }
2176 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002177
2178 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002179 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002180
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002181 /**
2182 * This Comparator sorts Alarms into increasing time order.
2183 */
2184 public static class IncreasingTimeOrder implements Comparator<Alarm> {
2185 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09002186 long when1 = a1.whenElapsed;
2187 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002188 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002189 return 1;
2190 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002191 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002192 return -1;
2193 }
2194 return 0;
2195 }
2196 }
2197
2198 private static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002199 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002200 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002201 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002202 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002203 public final IAlarmListener listener;
2204 public final String listenerTag;
2205 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002206 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002207 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002208 public final AlarmManager.AlarmClockInfo alarmClock;
2209 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002210 public final int creatorUid;
2211 public final String packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002212 public int count;
2213 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07002214 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002215 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002216 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002217 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07002218 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002219
Christopher Tate3e04b472013-10-21 17:51:31 -07002220 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002221 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
2222 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
2223 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002224 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002225 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002226 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
2227 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002228 when = _when;
2229 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07002230 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002231 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002232 repeatInterval = _interval;
2233 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002234 listener = _rec;
2235 listenerTag = _listenerTag;
2236 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07002237 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002238 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002239 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002240 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002241 packageName = _pkgName;
2242
2243 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002244 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002245
Christopher Tate14a7bb02015-10-01 10:24:31 -07002246 public static String makeTag(PendingIntent pi, String tag, int type) {
2247 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
2248 ? "*walarm*:" : "*alarm*:";
2249 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
2250 }
2251
2252 public WakeupEvent makeWakeupEvent(long nowRTC) {
2253 return new WakeupEvent(nowRTC, creatorUid,
2254 (operation != null)
2255 ? operation.getIntent().getAction()
2256 : ("<listener>:" + listenerTag));
2257 }
2258
2259 // Returns true if either matches
2260 public boolean matches(PendingIntent pi, IAlarmListener rec) {
2261 return (operation != null)
2262 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09002263 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07002264 }
2265
2266 public boolean matches(String packageName) {
2267 return (operation != null)
2268 ? packageName.equals(operation.getTargetPackage())
2269 : packageName.equals(this.packageName);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002270 }
2271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002272 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002273 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002274 StringBuilder sb = new StringBuilder(128);
2275 sb.append("Alarm{");
2276 sb.append(Integer.toHexString(System.identityHashCode(this)));
2277 sb.append(" type ");
2278 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002279 sb.append(" when ");
2280 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002281 sb.append(" ");
Christopher Tate14a7bb02015-10-01 10:24:31 -07002282 if (operation != null) {
2283 sb.append(operation.getTargetPackage());
2284 } else {
2285 sb.append(listener.asBinder().toString());
2286 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002287 sb.append('}');
2288 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002289 }
2290
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002291 public void dump(PrintWriter pw, String prefix, long nowRTC, long nowELAPSED,
2292 SimpleDateFormat sdf) {
2293 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002294 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002295 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002296 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
2297 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002298 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002299 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002300 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002301 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002302 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002303 }
2304 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002305 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002306 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002307 pw.print(" count="); pw.print(count);
2308 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002309 if (alarmClock != null) {
2310 pw.print(prefix); pw.println("Alarm clock:");
2311 pw.print(prefix); pw.print(" triggerTime=");
2312 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
2313 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
2314 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002315 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002316 if (listener != null) {
2317 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
2318 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002319 }
2320 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002321
Christopher Tatee0a22b32013-07-11 14:43:13 -07002322 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
2323 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002324 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
2325 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002326 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07002327 break;
2328 }
2329
Christopher Tatee0a22b32013-07-11 14:43:13 -07002330 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002331 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
2332 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002333 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07002334 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002335 }
2336 }
2337
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002338 long currentNonWakeupFuzzLocked(long nowELAPSED) {
2339 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
2340 if (timeSinceOn < 5*60*1000) {
2341 // If the screen has been off for 5 minutes, only delay by at most two minutes.
2342 return 2*60*1000;
2343 } else if (timeSinceOn < 30*60*1000) {
2344 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
2345 return 15*60*1000;
2346 } else {
2347 // Otherwise, we will delay by at most an hour.
2348 return 60*60*1000;
2349 }
2350 }
2351
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002352 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002353 if (duration < 15*60*1000) {
2354 // If the duration until the time is less than 15 minutes, the maximum fuzz
2355 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002356 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002357 } else if (duration < 90*60*1000) {
2358 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
2359 return 15*60*1000;
2360 } else {
2361 // Otherwise, we will fuzz by at most half an hour.
2362 return 30*60*1000;
2363 }
2364 }
2365
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002366 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
2367 if (mInteractive) {
2368 return false;
2369 }
2370 if (mLastAlarmDeliveryTime <= 0) {
2371 return false;
2372 }
minho.choo649acab2014-12-12 16:13:55 +09002373 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002374 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
2375 // and the next delivery time is in the past, then just deliver them all. This
2376 // avoids bugs where we get stuck in a loop trying to poll for alarms.
2377 return false;
2378 }
2379 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
2380 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
2381 }
2382
2383 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
2384 mLastAlarmDeliveryTime = nowELAPSED;
2385 for (int i=0; i<triggerList.size(); i++) {
2386 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07002387 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002388 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07002389 if (localLOGV) {
2390 Slog.v(TAG, "sending alarm " + alarm);
2391 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07002392 if (RECORD_ALARMS_IN_HISTORY) {
2393 if (alarm.workSource != null && alarm.workSource.size() > 0) {
2394 for (int wi=0; wi<alarm.workSource.size(); wi++) {
2395 ActivityManagerNative.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002396 alarm.operation, alarm.workSource.get(wi), alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002397 }
2398 } else {
2399 ActivityManagerNative.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002400 alarm.operation, alarm.uid, alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002401 }
2402 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002403 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002404 } catch (RuntimeException e) {
2405 Slog.w(TAG, "Failure sending alarm.", e);
2406 }
2407 }
2408 }
2409
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002410 private class AlarmThread extends Thread
2411 {
2412 public AlarmThread()
2413 {
2414 super("AlarmManager");
2415 }
2416
2417 public void run()
2418 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002419 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002421 while (true)
2422 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002423 int result = waitForAlarm(mNativeData);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002424
2425 triggerList.clear();
2426
Dianne Hackbornc3527222015-05-13 14:03:20 -07002427 final long nowRTC = System.currentTimeMillis();
2428 final long nowELAPSED = SystemClock.elapsedRealtime();
2429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002431 // The kernel can give us spurious time change notifications due to
2432 // small adjustments it makes internally; we want to filter those out.
2433 final long lastTimeChangeClockTime;
2434 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07002435 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002436 lastTimeChangeClockTime = mLastTimeChangeClockTime;
2437 expectedClockTime = lastTimeChangeClockTime
2438 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07002439 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002440 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-500)
2441 || nowRTC > (expectedClockTime+500)) {
2442 // The change is by at least +/- 500 ms (or this is the first change),
2443 // let's do it!
2444 if (DEBUG_BATCH) {
2445 Slog.v(TAG, "Time changed notification from kernel; rebatching");
2446 }
2447 removeImpl(mTimeTickSender);
2448 rebatchAllAlarms();
2449 mClockReceiver.scheduleTimeTickEvent();
2450 synchronized (mLock) {
2451 mNumTimeChanged++;
2452 mLastTimeChangeClockTime = nowRTC;
2453 mLastTimeChangeRealtime = nowELAPSED;
2454 }
2455 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
2456 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
2457 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2458 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
2459
2460 // The world has changed on us, so we need to re-evaluate alarms
2461 // regardless of whether the kernel has told us one went off.
2462 result |= IS_WAKEUP_MASK;
2463 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002464 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002465
Dianne Hackbornc3527222015-05-13 14:03:20 -07002466 if (result != TIME_CHANGED_MASK) {
2467 // If this was anything besides just a time change, then figure what if
2468 // anything to do about alarms.
2469 synchronized (mLock) {
2470 if (localLOGV) Slog.v(
2471 TAG, "Checking for alarms... rtc=" + nowRTC
2472 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07002473
Dianne Hackbornc3527222015-05-13 14:03:20 -07002474 if (WAKEUP_STATS) {
2475 if ((result & IS_WAKEUP_MASK) != 0) {
2476 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
2477 int n = 0;
2478 for (WakeupEvent event : mRecentWakeups) {
2479 if (event.when > newEarliest) break;
2480 n++; // number of now-stale entries at the list head
2481 }
2482 for (int i = 0; i < n; i++) {
2483 mRecentWakeups.remove();
2484 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002485
Dianne Hackbornc3527222015-05-13 14:03:20 -07002486 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002487 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002488 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002489
2490 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2491 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
2492 // if there are no wakeup alarms and the screen is off, we can
2493 // delay what we have so far until the future.
2494 if (mPendingNonWakeupAlarms.size() == 0) {
2495 mStartCurrentDelayTime = nowELAPSED;
2496 mNextNonWakeupDeliveryTime = nowELAPSED
2497 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
2498 }
2499 mPendingNonWakeupAlarms.addAll(triggerList);
2500 mNumDelayedAlarms += triggerList.size();
2501 rescheduleKernelAlarmsLocked();
2502 updateNextAlarmClockLocked();
2503 } else {
2504 // now deliver the alarm intents; if there are pending non-wakeup
2505 // alarms, we need to merge them in to the list. note we don't
2506 // just deliver them first because we generally want non-wakeup
2507 // alarms delivered after wakeup alarms.
2508 rescheduleKernelAlarmsLocked();
2509 updateNextAlarmClockLocked();
2510 if (mPendingNonWakeupAlarms.size() > 0) {
2511 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
2512 triggerList.addAll(mPendingNonWakeupAlarms);
2513 Collections.sort(triggerList, mAlarmDispatchComparator);
2514 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2515 mTotalDelayTime += thisDelayTime;
2516 if (mMaxDelayTime < thisDelayTime) {
2517 mMaxDelayTime = thisDelayTime;
2518 }
2519 mPendingNonWakeupAlarms.clear();
2520 }
2521 deliverAlarmsLocked(triggerList, nowELAPSED);
2522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 }
2524 }
2525 }
2526 }
2527 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002528
David Christieebe51fc2013-07-26 13:23:29 -07002529 /**
2530 * Attribute blame for a WakeLock.
2531 * @param pi PendingIntent to attribute blame to if ws is null.
2532 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002533 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07002534 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002535 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002536 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07002537 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002538 final boolean unimportant = pi == mTimeTickSender;
2539 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002540 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002541 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002542 } else {
2543 mWakeLock.setHistoryTag(null);
2544 }
2545 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07002546 if (ws != null) {
2547 mWakeLock.setWorkSource(ws);
2548 return;
2549 }
2550
Christopher Tate14a7bb02015-10-01 10:24:31 -07002551 final int uid = (knownUid >= 0)
2552 ? knownUid
2553 : ActivityManagerNative.getDefault().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07002554 if (uid >= 0) {
2555 mWakeLock.setWorkSource(new WorkSource(uid));
2556 return;
2557 }
2558 } catch (Exception e) {
2559 }
2560
2561 // Something went wrong; fall back to attributing the lock to the OS
2562 mWakeLock.setWorkSource(null);
2563 }
2564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002565 private class AlarmHandler extends Handler {
2566 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002567 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
2568 public static final int LISTENER_TIMEOUT = 3;
2569 public static final int REPORT_ALARMS_ACTIVE = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002570
2571 public AlarmHandler() {
2572 }
2573
2574 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002575 switch (msg.what) {
2576 case ALARM_EVENT: {
2577 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2578 synchronized (mLock) {
2579 final long nowRTC = System.currentTimeMillis();
2580 final long nowELAPSED = SystemClock.elapsedRealtime();
2581 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2582 updateNextAlarmClockLocked();
2583 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002584
Christopher Tate14a7bb02015-10-01 10:24:31 -07002585 // now trigger the alarms without the lock held
2586 for (int i=0; i<triggerList.size(); i++) {
2587 Alarm alarm = triggerList.get(i);
2588 try {
2589 alarm.operation.send();
2590 } catch (PendingIntent.CanceledException e) {
2591 if (alarm.repeatInterval > 0) {
2592 // This IntentSender is no longer valid, but this
2593 // is a repeating alarm, so toss the hoser.
2594 removeImpl(alarm.operation);
2595 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002596 }
2597 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002598 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002599 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002600
2601 case SEND_NEXT_ALARM_CLOCK_CHANGED:
2602 sendNextAlarmClockChanged();
2603 break;
2604
2605 case LISTENER_TIMEOUT:
2606 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
2607 break;
2608
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002609 case REPORT_ALARMS_ACTIVE:
2610 if (mLocalDeviceIdleController != null) {
2611 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
2612 }
2613 break;
2614
Christopher Tate14a7bb02015-10-01 10:24:31 -07002615 default:
2616 // nope, just ignore it
2617 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002618 }
2619 }
2620 }
2621
2622 class ClockReceiver extends BroadcastReceiver {
2623 public ClockReceiver() {
2624 IntentFilter filter = new IntentFilter();
2625 filter.addAction(Intent.ACTION_TIME_TICK);
2626 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002627 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002628 }
2629
2630 @Override
2631 public void onReceive(Context context, Intent intent) {
2632 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07002633 if (DEBUG_BATCH) {
2634 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
2635 }
2636 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002637 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
2638 // Since the kernel does not keep track of DST, we need to
2639 // reset the TZ information at the beginning of each day
2640 // based off of the current Zone gmt offset + userspace tracked
2641 // daylight savings information.
2642 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02002643 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002644 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07002645 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002646 }
2647 }
2648
2649 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07002650 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09002651 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07002652
2653 // Schedule this event for the amount of time that it would take to get to
2654 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09002655 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07002656
David Christieebe51fc2013-07-26 13:23:29 -07002657 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002658 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002659 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
2660 null, Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 }
Christopher Tate385e4982013-07-23 18:22:29 -07002662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002663 public void scheduleDateChangedEvent() {
2664 Calendar calendar = Calendar.getInstance();
2665 calendar.setTimeInMillis(System.currentTimeMillis());
2666 calendar.set(Calendar.HOUR, 0);
2667 calendar.set(Calendar.MINUTE, 0);
2668 calendar.set(Calendar.SECOND, 0);
2669 calendar.set(Calendar.MILLISECOND, 0);
2670 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07002671
2672 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002673 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
2674 AlarmManager.FLAG_STANDALONE, workSource, null,
2675 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002676 }
2677 }
2678
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002679 class InteractiveStateReceiver extends BroadcastReceiver {
2680 public InteractiveStateReceiver() {
2681 IntentFilter filter = new IntentFilter();
2682 filter.addAction(Intent.ACTION_SCREEN_OFF);
2683 filter.addAction(Intent.ACTION_SCREEN_ON);
2684 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
2685 getContext().registerReceiver(this, filter);
2686 }
2687
2688 @Override
2689 public void onReceive(Context context, Intent intent) {
2690 synchronized (mLock) {
2691 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
2692 }
2693 }
2694 }
2695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002696 class UninstallReceiver extends BroadcastReceiver {
2697 public UninstallReceiver() {
2698 IntentFilter filter = new IntentFilter();
2699 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2700 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002701 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002702 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08002703 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002704 // Register for events related to sdcard installation.
2705 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08002706 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002707 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002708 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002709 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002710 }
2711
2712 @Override
2713 public void onReceive(Context context, Intent intent) {
2714 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002715 String action = intent.getAction();
2716 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002717 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
2718 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
2719 for (String packageName : pkgList) {
2720 if (lookForPackageLocked(packageName)) {
2721 setResultCode(Activity.RESULT_OK);
2722 return;
2723 }
2724 }
2725 return;
2726 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002727 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002728 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
2729 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
2730 if (userHandle >= 0) {
2731 removeUserLocked(userHandle);
2732 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002733 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
2734 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
2735 if (uid >= 0) {
2736 mLastAllowWhileIdleDispatch.delete(uid);
2737 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002738 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08002739 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
2740 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
2741 // This package is being updated; don't kill its alarms.
2742 return;
2743 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002744 Uri data = intent.getData();
2745 if (data != null) {
2746 String pkg = data.getSchemeSpecificPart();
2747 if (pkg != null) {
2748 pkgList = new String[]{pkg};
2749 }
2750 }
2751 }
2752 if (pkgList != null && (pkgList.length > 0)) {
2753 for (String pkg : pkgList) {
2754 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07002755 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002756 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
2757 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
2758 if (uidStats.remove(pkg) != null) {
2759 if (uidStats.size() <= 0) {
2760 mBroadcastStats.removeAt(i);
2761 }
2762 }
2763 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002764 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002765 }
2766 }
2767 }
2768 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002769
2770 final class UidObserver extends IUidObserver.Stub {
2771 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
2772 }
2773
2774 @Override public void onUidGone(int uid) throws RemoteException {
2775 }
2776
2777 @Override public void onUidActive(int uid) throws RemoteException {
2778 }
2779
2780 @Override public void onUidIdle(int uid) throws RemoteException {
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08002781 synchronized (mLock) {
2782 removeForStoppedLocked(uid);
2783 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002784 }
2785 };
2786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002787 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002788 String pkg = pi.getCreatorPackage();
2789 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002790 return getStatsLocked(uid, pkg);
2791 }
2792
2793 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002794 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
2795 if (uidStats == null) {
2796 uidStats = new ArrayMap<String, BroadcastStats>();
2797 mBroadcastStats.put(uid, uidStats);
2798 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002799 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002800 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002801 bs = new BroadcastStats(uid, pkgName);
2802 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002803 }
2804 return bs;
2805 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002806
Christopher Tate14a7bb02015-10-01 10:24:31 -07002807 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
2808 private InFlight removeLocked(PendingIntent pi, Intent intent) {
2809 for (int i = 0; i < mInFlight.size(); i++) {
2810 if (mInFlight.get(i).mPendingIntent == pi) {
2811 return mInFlight.remove(i);
2812 }
2813 }
2814 mLog.w("No in-flight alarm for " + pi + " " + intent);
2815 return null;
2816 }
2817
2818 private InFlight removeLocked(IBinder listener) {
2819 for (int i = 0; i < mInFlight.size(); i++) {
2820 if (mInFlight.get(i).mListener == listener) {
2821 return mInFlight.remove(i);
2822 }
2823 }
2824 mLog.w("No in-flight alarm for listener " + listener);
2825 return null;
2826 }
2827
2828 private void updateStatsLocked(InFlight inflight) {
2829 final long nowELAPSED = SystemClock.elapsedRealtime();
2830 BroadcastStats bs = inflight.mBroadcastStats;
2831 bs.nesting--;
2832 if (bs.nesting <= 0) {
2833 bs.nesting = 0;
2834 bs.aggregateTime += nowELAPSED - bs.startTime;
2835 }
2836 FilterStats fs = inflight.mFilterStats;
2837 fs.nesting--;
2838 if (fs.nesting <= 0) {
2839 fs.nesting = 0;
2840 fs.aggregateTime += nowELAPSED - fs.startTime;
2841 }
2842 if (RECORD_ALARMS_IN_HISTORY) {
2843 if (inflight.mWorkSource != null && inflight.mWorkSource.size() > 0) {
2844 for (int wi=0; wi<inflight.mWorkSource.size(); wi++) {
2845 ActivityManagerNative.noteAlarmFinish(
2846 inflight.mPendingIntent, inflight.mWorkSource.get(wi), inflight.mTag);
2847 }
2848 } else {
2849 ActivityManagerNative.noteAlarmFinish(
2850 inflight.mPendingIntent, inflight.mUid, inflight.mTag);
2851 }
2852 }
2853 }
2854
2855 private void updateTrackingLocked(InFlight inflight) {
2856 if (inflight != null) {
2857 updateStatsLocked(inflight);
2858 }
2859 mBroadcastRefCount--;
2860 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002861 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002862 mWakeLock.release();
2863 if (mInFlight.size() > 0) {
2864 mLog.w("Finished all dispatches with " + mInFlight.size()
2865 + " remaining inflights");
2866 for (int i=0; i<mInFlight.size(); i++) {
2867 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
2868 }
2869 mInFlight.clear();
2870 }
2871 } else {
2872 // the next of our alarms is now in flight. reattribute the wakelock.
2873 if (mInFlight.size() > 0) {
2874 InFlight inFlight = mInFlight.get(0);
2875 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
2876 inFlight.mAlarmType, inFlight.mTag, -1, false);
2877 } else {
2878 // should never happen
2879 mLog.w("Alarm wakelock still held but sent queue empty");
2880 mWakeLock.setWorkSource(null);
2881 }
2882 }
2883 }
2884
2885 /**
2886 * Callback that arrives when a direct-call alarm reports that delivery has finished
2887 */
2888 @Override
2889 public void alarmComplete(IBinder who) {
2890 if (who == null) {
2891 Slog.w(TAG, "Invalid alarmComplete: uid=" + Binder.getCallingUid()
2892 + " pid=" + Binder.getCallingPid());
2893 return;
2894 }
2895
2896 final long ident = Binder.clearCallingIdentity();
2897 try {
2898 synchronized (mLock) {
2899 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
2900 InFlight inflight = removeLocked(who);
2901 if (inflight != null) {
2902 if (DEBUG_LISTENER_CALLBACK) {
2903 Slog.i(TAG, "alarmComplete() from " + who);
2904 }
2905 updateTrackingLocked(inflight);
2906 } else {
2907 // Delivery timed out, and the timeout handling already took care of
2908 // updating our tracking here, so we needn't do anything further.
2909 if (DEBUG_LISTENER_CALLBACK) {
2910 Slog.i(TAG, "Late alarmComplete() from " + who);
2911 }
2912 }
2913 }
2914 } finally {
2915 Binder.restoreCallingIdentity(ident);
2916 }
2917 }
2918
2919 /**
2920 * Callback that arrives when a PendingIntent alarm has finished delivery
2921 */
2922 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002923 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
2924 String resultData, Bundle resultExtras) {
2925 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002926 updateTrackingLocked(removeLocked(pi, intent));
2927 }
2928 }
2929
2930 /**
2931 * Timeout of a direct-call alarm delivery
2932 */
2933 public void alarmTimedOut(IBinder who) {
2934 synchronized (mLock) {
2935 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08002936 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002937 // TODO: implement ANR policy for the target
2938 if (DEBUG_LISTENER_CALLBACK) {
2939 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002941 updateTrackingLocked(inflight);
Dianne Hackborn81038902012-11-26 17:04:09 -08002942 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002943 if (DEBUG_LISTENER_CALLBACK) {
2944 Slog.i(TAG, "Spurious timeout of listener " + who);
2945 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002946 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002947 }
2948 }
2949
2950 /**
2951 * Deliver an alarm and set up the post-delivery handling appropriately
2952 */
2953 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
2954 if (alarm.operation != null) {
2955 // PendingIntent alarm
2956 try {
2957 alarm.operation.send(getContext(), 0,
2958 mBackgroundIntent.putExtra(
2959 Intent.EXTRA_ALARM_COUNT, alarm.count),
2960 mDeliveryTracker, mHandler, null,
2961 allowWhileIdle ? mIdleOptions : null);
2962 } catch (PendingIntent.CanceledException e) {
2963 if (alarm.repeatInterval > 0) {
2964 // This IntentSender is no longer valid, but this
2965 // is a repeating alarm, so toss it
2966 removeImpl(alarm.operation);
2967 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08002968 // No actual delivery was possible, so the delivery tracker's
2969 // 'finished' callback won't be invoked. We also don't need
2970 // to do any wakelock or stats tracking, so we have nothing
2971 // left to do here but go on to the next thing.
2972 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002973 }
2974 } else {
2975 // Direct listener callback alarm
2976 try {
2977 if (DEBUG_LISTENER_CALLBACK) {
2978 Slog.v(TAG, "Alarm to uid=" + alarm.uid
2979 + " listener=" + alarm.listener.asBinder());
2980 }
2981 alarm.listener.doAlarm(this);
2982 mHandler.sendMessageDelayed(
2983 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
2984 alarm.listener.asBinder()),
2985 mConstants.LISTENER_TIMEOUT);
2986 } catch (Exception e) {
2987 if (DEBUG_LISTENER_CALLBACK) {
2988 Slog.i(TAG, "Alarm undeliverable to listener "
2989 + alarm.listener.asBinder(), e);
2990 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08002991 // As in the PendingIntent.CanceledException case, delivery of the
2992 // alarm was not possible, so we have no wakelock or timeout or
2993 // stats management to do. It threw before we posted the delayed
2994 // timeout message, so we're done here.
2995 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002996 }
2997 }
2998
2999 // The alarm is now in flight; now arrange wakelock and stats tracking
3000 if (mBroadcastRefCount == 0) {
3001 setWakelockWorkSource(alarm.operation, alarm.workSource,
3002 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
3003 true);
3004 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003005 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003006 }
3007 final InFlight inflight = new InFlight(AlarmManagerService.this,
3008 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
3009 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
3010 mInFlight.add(inflight);
3011 mBroadcastRefCount++;
3012
3013 if (allowWhileIdle) {
3014 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
3015 mLastAllowWhileIdleDispatch.put(alarm.uid, nowELAPSED);
3016 if (RECORD_DEVICE_IDLE_ALARMS) {
3017 IdleDispatchEntry ent = new IdleDispatchEntry();
3018 ent.uid = alarm.uid;
3019 ent.pkg = alarm.packageName;
3020 ent.tag = alarm.statsTag;
3021 ent.op = "DELIVER";
3022 ent.elapsedRealtime = nowELAPSED;
3023 mAllowWhileIdleDispatches.add(ent);
3024 }
3025 }
3026
3027 final BroadcastStats bs = inflight.mBroadcastStats;
3028 bs.count++;
3029 if (bs.nesting == 0) {
3030 bs.nesting = 1;
3031 bs.startTime = nowELAPSED;
3032 } else {
3033 bs.nesting++;
3034 }
3035 final FilterStats fs = inflight.mFilterStats;
3036 fs.count++;
3037 if (fs.nesting == 0) {
3038 fs.nesting = 1;
3039 fs.startTime = nowELAPSED;
3040 } else {
3041 fs.nesting++;
3042 }
3043 if (alarm.type == ELAPSED_REALTIME_WAKEUP
3044 || alarm.type == RTC_WAKEUP) {
3045 bs.numWakeup++;
3046 fs.numWakeup++;
3047 if (alarm.workSource != null && alarm.workSource.size() > 0) {
3048 for (int wi=0; wi<alarm.workSource.size(); wi++) {
3049 ActivityManagerNative.noteWakeupAlarm(
3050 alarm.operation, alarm.workSource.get(wi),
3051 alarm.workSource.getName(wi), alarm.statsTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08003052 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003053 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003054 ActivityManagerNative.noteWakeupAlarm(
3055 alarm.operation, -1, alarm.packageName, alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003056 }
3057 }
3058 }
3059 }
3060}