blob: c5ce2fd0477bc617209c9ab0e4b5a54014e0387f [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 Tate0dab4dc2014-12-16 12:14:06 -08001366 pw.print(" nowELAPSED="); TimeUtils.formatDuration(nowELAPSED, pw);
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
Dianne Hackborna750a632015-06-16 17:18:23 -07001467 pw.print(" mAllowWhileIdleMinTime=");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001468 TimeUtils.formatDuration(mAllowWhileIdleMinTime, pw);
1469 pw.println();
1470 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001471 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001472 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
1473 pw.print(" UID ");
1474 UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
1475 pw.print(": ");
1476 TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i),
1477 nowELAPSED, pw);
1478 pw.println();
1479 }
1480 }
1481 pw.println();
1482
Dianne Hackborn81038902012-11-26 17:04:09 -08001483 if (mLog.dump(pw, " Recent problems", " ")) {
1484 pw.println();
1485 }
1486
1487 final FilterStats[] topFilters = new FilterStats[10];
1488 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1489 @Override
1490 public int compare(FilterStats lhs, FilterStats rhs) {
1491 if (lhs.aggregateTime < rhs.aggregateTime) {
1492 return 1;
1493 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1494 return -1;
1495 }
1496 return 0;
1497 }
1498 };
1499 int len = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001500 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1501 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1502 for (int ip=0; ip<uidStats.size(); ip++) {
1503 BroadcastStats bs = uidStats.valueAt(ip);
1504 for (int is=0; is<bs.filterStats.size(); is++) {
1505 FilterStats fs = bs.filterStats.valueAt(is);
1506 int pos = len > 0
1507 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1508 if (pos < 0) {
1509 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001510 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001511 if (pos < topFilters.length) {
1512 int copylen = topFilters.length - pos - 1;
1513 if (copylen > 0) {
1514 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1515 }
1516 topFilters[pos] = fs;
1517 if (len < topFilters.length) {
1518 len++;
1519 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001520 }
1521 }
1522 }
1523 }
1524 if (len > 0) {
1525 pw.println(" Top Alarms:");
1526 for (int i=0; i<len; i++) {
1527 FilterStats fs = topFilters[i];
1528 pw.print(" ");
1529 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1530 TimeUtils.formatDuration(fs.aggregateTime, pw);
1531 pw.print(" running, "); pw.print(fs.numWakeup);
1532 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001533 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1534 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001535 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001536 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001537 pw.println();
1538 }
1539 }
1540
1541 pw.println(" ");
1542 pw.println(" Alarm Stats:");
1543 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001544 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1545 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1546 for (int ip=0; ip<uidStats.size(); ip++) {
1547 BroadcastStats bs = uidStats.valueAt(ip);
1548 pw.print(" ");
1549 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1550 UserHandle.formatUid(pw, bs.mUid);
1551 pw.print(":");
1552 pw.print(bs.mPackageName);
1553 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1554 pw.print(" running, "); pw.print(bs.numWakeup);
1555 pw.println(" wakeups:");
1556 tmpFilters.clear();
1557 for (int is=0; is<bs.filterStats.size(); is++) {
1558 tmpFilters.add(bs.filterStats.valueAt(is));
1559 }
1560 Collections.sort(tmpFilters, comparator);
1561 for (int i=0; i<tmpFilters.size(); i++) {
1562 FilterStats fs = tmpFilters.get(i);
1563 pw.print(" ");
1564 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1565 TimeUtils.formatDuration(fs.aggregateTime, pw);
1566 pw.print(" "); pw.print(fs.numWakeup);
1567 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001568 pw.print(" alarms, last ");
1569 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1570 pw.println(":");
1571 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001572 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001573 pw.println();
1574 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 }
1576 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001577
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001578 if (RECORD_DEVICE_IDLE_ALARMS) {
1579 pw.println();
1580 pw.println(" Allow while idle dispatches:");
1581 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
1582 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
1583 pw.print(" ");
1584 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
1585 pw.print(": ");
1586 UserHandle.formatUid(pw, ent.uid);
1587 pw.print(":");
1588 pw.println(ent.pkg);
1589 if (ent.op != null) {
1590 pw.print(" ");
1591 pw.print(ent.op);
1592 pw.print(" / ");
1593 pw.print(ent.tag);
1594 if (ent.argRealtime != 0) {
1595 pw.print(" (");
1596 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
1597 pw.print(")");
1598 }
1599 pw.println();
1600 }
1601 }
1602 }
1603
Christopher Tate18a75f12013-07-01 18:18:59 -07001604 if (WAKEUP_STATS) {
1605 pw.println();
1606 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001607 long last = -1;
1608 for (WakeupEvent event : mRecentWakeups) {
1609 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1610 pw.print('|');
1611 if (last < 0) {
1612 pw.print('0');
1613 } else {
1614 pw.print(event.when - last);
1615 }
1616 last = event.when;
1617 pw.print('|'); pw.print(event.uid);
1618 pw.print('|'); pw.print(event.action);
1619 pw.println();
1620 }
1621 pw.println();
1622 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 }
1624 }
1625
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001626 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001627 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
1628 PrintWriter pw = new PrintWriter(bs);
1629 final long nowRTC = System.currentTimeMillis();
1630 final long nowELAPSED = SystemClock.elapsedRealtime();
1631 final int NZ = mAlarmBatches.size();
1632 for (int iz = 0; iz < NZ; iz++) {
1633 Batch bz = mAlarmBatches.get(iz);
1634 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001635 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001636 pw.flush();
1637 Slog.v(TAG, bs.toString());
1638 bs.reset();
1639 }
1640 }
1641
1642 private boolean validateConsistencyLocked() {
1643 if (DEBUG_VALIDATE) {
1644 long lastTime = Long.MIN_VALUE;
1645 final int N = mAlarmBatches.size();
1646 for (int i = 0; i < N; i++) {
1647 Batch b = mAlarmBatches.get(i);
1648 if (b.start >= lastTime) {
1649 // duplicate start times are okay because of standalone batches
1650 lastTime = b.start;
1651 } else {
1652 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001653 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1654 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001655 return false;
1656 }
1657 }
1658 }
1659 return true;
1660 }
1661
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001662 private Batch findFirstWakeupBatchLocked() {
1663 final int N = mAlarmBatches.size();
1664 for (int i = 0; i < N; i++) {
1665 Batch b = mAlarmBatches.get(i);
1666 if (b.hasWakeups()) {
1667 return b;
1668 }
1669 }
1670 return null;
1671 }
1672
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001673 long getNextWakeFromIdleTimeImpl() {
1674 synchronized (mLock) {
1675 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
1676 }
1677 }
1678
1679 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001680 synchronized (mLock) {
1681 return mNextAlarmClockForUser.get(userId);
1682 }
1683 }
1684
1685 /**
1686 * Recomputes the next alarm clock for all users.
1687 */
1688 private void updateNextAlarmClockLocked() {
1689 if (!mNextAlarmClockMayChange) {
1690 return;
1691 }
1692 mNextAlarmClockMayChange = false;
1693
Jose Lima235510e2014-08-13 12:50:01 -07001694 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001695 nextForUser.clear();
1696
1697 final int N = mAlarmBatches.size();
1698 for (int i = 0; i < N; i++) {
1699 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
1700 final int M = alarms.size();
1701
1702 for (int j = 0; j < M; j++) {
1703 Alarm a = alarms.get(j);
1704 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001705 final int userId = UserHandle.getUserId(a.uid);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001706
1707 if (DEBUG_ALARM_CLOCK) {
1708 Log.v(TAG, "Found AlarmClockInfo at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001709 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02001710 " for user " + userId);
1711 }
1712
1713 // Alarms and batches are sorted by time, no need to compare times here.
1714 if (nextForUser.get(userId) == null) {
1715 nextForUser.put(userId, a.alarmClock);
1716 }
1717 }
1718 }
1719 }
1720
1721 // Update mNextAlarmForUser with new values.
1722 final int NN = nextForUser.size();
1723 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07001724 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001725 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001726 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001727 if (!newAlarm.equals(currentAlarm)) {
1728 updateNextAlarmInfoForUserLocked(userId, newAlarm);
1729 }
1730 }
1731
1732 // Remove users without any alarm clocks scheduled.
1733 final int NNN = mNextAlarmClockForUser.size();
1734 for (int i = NNN - 1; i >= 0; i--) {
1735 int userId = mNextAlarmClockForUser.keyAt(i);
1736 if (nextForUser.get(userId) == null) {
1737 updateNextAlarmInfoForUserLocked(userId, null);
1738 }
1739 }
1740 }
1741
Jose Lima235510e2014-08-13 12:50:01 -07001742 private void updateNextAlarmInfoForUserLocked(int userId,
1743 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001744 if (alarmClock != null) {
1745 if (DEBUG_ALARM_CLOCK) {
1746 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001747 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02001748 }
1749 mNextAlarmClockForUser.put(userId, alarmClock);
1750 } else {
1751 if (DEBUG_ALARM_CLOCK) {
1752 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
1753 }
1754 mNextAlarmClockForUser.remove(userId);
1755 }
1756
1757 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
1758 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1759 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1760 }
1761
1762 /**
1763 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
1764 * for which alarm clocks have changed since the last call to this.
1765 *
1766 * Do not call with a lock held. Only call from mHandler's thread.
1767 *
1768 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
1769 */
1770 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07001771 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001772 pendingUsers.clear();
1773
1774 synchronized (mLock) {
1775 final int N = mPendingSendNextAlarmClockChangedForUser.size();
1776 for (int i = 0; i < N; i++) {
1777 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
1778 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
1779 }
1780 mPendingSendNextAlarmClockChangedForUser.clear();
1781 }
1782
1783 final int N = pendingUsers.size();
1784 for (int i = 0; i < N; i++) {
1785 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001786 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001787 Settings.System.putStringForUser(getContext().getContentResolver(),
1788 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01001789 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02001790 userId);
1791
1792 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
1793 new UserHandle(userId));
1794 }
1795 }
1796
1797 /**
1798 * Formats an alarm like platform/packages/apps/DeskClock used to.
1799 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01001800 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
1801 int userId) {
1802 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02001803 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
1804 return (info == null) ? "" :
1805 DateFormat.format(pattern, info.getTriggerTime()).toString();
1806 }
1807
Adam Lesinski182f73f2013-12-05 16:48:06 -08001808 void rescheduleKernelAlarmsLocked() {
1809 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
1810 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001811 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001812 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001813 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001814 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07001815 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001816 mNextWakeup = firstWakeup.start;
1817 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001818 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001819 if (firstBatch != firstWakeup) {
1820 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001821 }
1822 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001823 if (mPendingNonWakeupAlarms.size() > 0) {
1824 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
1825 nextNonWakeup = mNextNonWakeupDeliveryTime;
1826 }
1827 }
Prashant Malani753e9e02015-06-10 17:43:49 -07001828 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001829 mNextNonWakeup = nextNonWakeup;
1830 setLocked(ELAPSED_REALTIME, nextNonWakeup);
1831 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001832 }
1833
Christopher Tate14a7bb02015-10-01 10:24:31 -07001834 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001835 boolean didRemove = false;
1836 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1837 Batch b = mAlarmBatches.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -07001838 didRemove |= b.remove(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001839 if (b.size() == 0) {
1840 mAlarmBatches.remove(i);
1841 }
1842 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001843 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001844 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001845 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1846 mPendingWhileIdleAlarms.remove(i);
1847 }
1848 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001849
1850 if (didRemove) {
1851 if (DEBUG_BATCH) {
1852 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
1853 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001854 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001855 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001856 mPendingIdleUntil = null;
1857 restorePending = true;
1858 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001859 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001860 mNextWakeFromIdle = null;
1861 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001862 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001863 if (restorePending) {
1864 restorePendingWhileIdleAlarmsLocked();
1865 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001866 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001867 }
1868 }
1869
1870 void removeLocked(String packageName) {
1871 boolean didRemove = false;
1872 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1873 Batch b = mAlarmBatches.get(i);
1874 didRemove |= b.remove(packageName);
1875 if (b.size() == 0) {
1876 mAlarmBatches.remove(i);
1877 }
1878 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001879 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001880 final Alarm a = mPendingWhileIdleAlarms.get(i);
1881 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001882 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1883 mPendingWhileIdleAlarms.remove(i);
1884 }
1885 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001886
1887 if (didRemove) {
1888 if (DEBUG_BATCH) {
1889 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1890 }
1891 rebatchAllAlarmsLocked(true);
1892 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001893 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001894 }
1895 }
1896
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001897 void removeForStoppedLocked(int uid) {
1898 boolean didRemove = false;
1899 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1900 Batch b = mAlarmBatches.get(i);
1901 didRemove |= b.removeForStopped(uid);
1902 if (b.size() == 0) {
1903 mAlarmBatches.remove(i);
1904 }
1905 }
1906 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1907 final Alarm a = mPendingWhileIdleAlarms.get(i);
1908 try {
1909 if (a.uid == uid && ActivityManagerNative.getDefault().getAppStartMode(
1910 uid, a.packageName) == ActivityManager.APP_START_MODE_DISABLED) {
1911 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1912 mPendingWhileIdleAlarms.remove(i);
1913 }
1914 } catch (RemoteException e) {
1915 }
1916 }
1917
1918 if (didRemove) {
1919 if (DEBUG_BATCH) {
1920 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1921 }
1922 rebatchAllAlarmsLocked(true);
1923 rescheduleKernelAlarmsLocked();
1924 updateNextAlarmClockLocked();
1925 }
1926 }
1927
Adam Lesinski182f73f2013-12-05 16:48:06 -08001928 void removeUserLocked(int userHandle) {
1929 boolean didRemove = false;
1930 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1931 Batch b = mAlarmBatches.get(i);
1932 didRemove |= b.remove(userHandle);
1933 if (b.size() == 0) {
1934 mAlarmBatches.remove(i);
1935 }
1936 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001937 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001938 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001939 == userHandle) {
1940 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1941 mPendingWhileIdleAlarms.remove(i);
1942 }
1943 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001944 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
1945 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
1946 mLastAllowWhileIdleDispatch.removeAt(i);
1947 }
1948 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001949
1950 if (didRemove) {
1951 if (DEBUG_BATCH) {
1952 Slog.v(TAG, "remove(user) changed bounds; rebatching");
1953 }
1954 rebatchAllAlarmsLocked(true);
1955 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001956 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001957 }
1958 }
1959
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001960 void interactiveStateChangedLocked(boolean interactive) {
1961 if (mInteractive != interactive) {
1962 mInteractive = interactive;
1963 final long nowELAPSED = SystemClock.elapsedRealtime();
1964 if (interactive) {
1965 if (mPendingNonWakeupAlarms.size() > 0) {
1966 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1967 mTotalDelayTime += thisDelayTime;
1968 if (mMaxDelayTime < thisDelayTime) {
1969 mMaxDelayTime = thisDelayTime;
1970 }
1971 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
1972 mPendingNonWakeupAlarms.clear();
1973 }
1974 if (mNonInteractiveStartTime > 0) {
1975 long dur = nowELAPSED - mNonInteractiveStartTime;
1976 if (dur > mNonInteractiveTime) {
1977 mNonInteractiveTime = dur;
1978 }
1979 }
1980 } else {
1981 mNonInteractiveStartTime = nowELAPSED;
1982 }
1983 }
1984 }
1985
Adam Lesinski182f73f2013-12-05 16:48:06 -08001986 boolean lookForPackageLocked(String packageName) {
1987 for (int i = 0; i < mAlarmBatches.size(); i++) {
1988 Batch b = mAlarmBatches.get(i);
1989 if (b.hasPackage(packageName)) {
1990 return true;
1991 }
1992 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001993 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001994 final Alarm a = mPendingWhileIdleAlarms.get(i);
1995 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001996 return true;
1997 }
1998 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001999 return false;
2000 }
2001
2002 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002003 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002004 // The kernel never triggers alarms with negative wakeup times
2005 // so we ensure they are positive.
2006 long alarmSeconds, alarmNanoseconds;
2007 if (when < 0) {
2008 alarmSeconds = 0;
2009 alarmNanoseconds = 0;
2010 } else {
2011 alarmSeconds = when / 1000;
2012 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2013 }
2014
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002015 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002016 } else {
2017 Message msg = Message.obtain();
2018 msg.what = ALARM_EVENT;
2019
2020 mHandler.removeMessages(ALARM_EVENT);
2021 mHandler.sendMessageAtTime(msg, when);
2022 }
2023 }
2024
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002025 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002026 String prefix, String label, long nowRTC, long nowELAPSED, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002027 for (int i=list.size()-1; i>=0; i--) {
2028 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002029 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2030 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002031 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 }
2033 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002034
2035 private static final String labelForType(int type) {
2036 switch (type) {
2037 case RTC: return "RTC";
2038 case RTC_WAKEUP : return "RTC_WAKEUP";
2039 case ELAPSED_REALTIME : return "ELAPSED";
2040 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
2041 default:
2042 break;
2043 }
2044 return "--unknown--";
2045 }
2046
2047 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002048 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002049 for (int i=list.size()-1; i>=0; i--) {
2050 Alarm a = list.get(i);
2051 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002052 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2053 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002054 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002055 }
2056 }
2057
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002058 private native long init();
2059 private native void close(long nativeData);
2060 private native void set(long nativeData, int type, long seconds, long nanoseconds);
2061 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08002062 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002063 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002064
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002065 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002066 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002067 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002068 // batches are temporally sorted, so we need only pull from the
2069 // start of the list until we either empty it or hit a batch
2070 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07002071 while (mAlarmBatches.size() > 0) {
2072 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002073 if (batch.start > nowELAPSED) {
2074 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002075 break;
2076 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002077
Christopher Tatee0a22b32013-07-11 14:43:13 -07002078 // We will (re)schedule some alarms now; don't let that interfere
2079 // with delivery of this current batch
2080 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002081
Christopher Tatee0a22b32013-07-11 14:43:13 -07002082 final int N = batch.size();
2083 for (int i = 0; i < N; i++) {
2084 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002085
2086 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
2087 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
2088 // schedule such alarms.
2089 long lastTime = mLastAllowWhileIdleDispatch.get(alarm.uid, 0);
2090 long minTime = lastTime + mAllowWhileIdleMinTime;
2091 if (nowELAPSED < minTime) {
2092 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
2093 // alarm went off for this app. Reschedule the alarm to be in the
2094 // correct time period.
2095 alarm.whenElapsed = minTime;
2096 if (alarm.maxWhenElapsed < minTime) {
2097 alarm.maxWhenElapsed = minTime;
2098 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002099 if (RECORD_DEVICE_IDLE_ALARMS) {
2100 IdleDispatchEntry ent = new IdleDispatchEntry();
2101 ent.uid = alarm.uid;
2102 ent.pkg = alarm.operation.getCreatorPackage();
2103 ent.tag = alarm.operation.getTag("");
2104 ent.op = "RESCHEDULE";
2105 ent.elapsedRealtime = nowELAPSED;
2106 ent.argRealtime = lastTime;
2107 mAllowWhileIdleDispatches.add(ent);
2108 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002109 setImplLocked(alarm, true, false);
2110 continue;
2111 }
2112 }
2113
Christopher Tatee0a22b32013-07-11 14:43:13 -07002114 alarm.count = 1;
2115 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002116 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
2117 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002118 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002119 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002120 if (mPendingIdleUntil == alarm) {
2121 mPendingIdleUntil = null;
2122 rebatchAllAlarmsLocked(false);
2123 restorePendingWhileIdleAlarmsLocked();
2124 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002125 if (mNextWakeFromIdle == alarm) {
2126 mNextWakeFromIdle = null;
2127 rebatchAllAlarmsLocked(false);
2128 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002129
2130 // Recurring alarms may have passed several alarm intervals while the
2131 // phone was asleep or off, so pass a trigger count when sending them.
2132 if (alarm.repeatInterval > 0) {
2133 // this adjustment will be zero if we're late by
2134 // less than one full repeat interval
2135 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
2136
2137 // Also schedule its next recurrence
2138 final long delta = alarm.count * alarm.repeatInterval;
2139 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07002140 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07002141 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07002142 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
2143 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08002144 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002145
Christopher Tate864d42e2014-12-02 11:48:53 -08002146 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002147 hasWakeup = true;
2148 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002149
2150 // We removed an alarm clock. Let the caller recompute the next alarm clock.
2151 if (alarm.alarmClock != null) {
2152 mNextAlarmClockMayChange = true;
2153 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07002154 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002155 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002156
Christopher Tate1590f1e2014-10-02 17:27:57 -07002157 // This is a new alarm delivery set; bump the sequence number to indicate that
2158 // all apps' alarm delivery classes should be recalculated.
2159 mCurrentSeq++;
2160 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002161 Collections.sort(triggerList, mAlarmDispatchComparator);
2162
2163 if (localLOGV) {
2164 for (int i=0; i<triggerList.size(); i++) {
2165 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
2166 }
2167 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002168
2169 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002170 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002171
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002172 /**
2173 * This Comparator sorts Alarms into increasing time order.
2174 */
2175 public static class IncreasingTimeOrder implements Comparator<Alarm> {
2176 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09002177 long when1 = a1.whenElapsed;
2178 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002179 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002180 return 1;
2181 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002182 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002183 return -1;
2184 }
2185 return 0;
2186 }
2187 }
2188
2189 private static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002190 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002191 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002192 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002193 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002194 public final IAlarmListener listener;
2195 public final String listenerTag;
2196 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002197 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002198 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002199 public final AlarmManager.AlarmClockInfo alarmClock;
2200 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002201 public final int creatorUid;
2202 public final String packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002203 public int count;
2204 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07002205 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002206 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002207 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002208 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07002209 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002210
Christopher Tate3e04b472013-10-21 17:51:31 -07002211 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002212 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
2213 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
2214 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002215 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002216 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002217 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
2218 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002219 when = _when;
2220 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07002221 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002222 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002223 repeatInterval = _interval;
2224 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002225 listener = _rec;
2226 listenerTag = _listenerTag;
2227 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07002228 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002229 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002230 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002231 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002232 packageName = _pkgName;
2233
2234 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002235 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002236
Christopher Tate14a7bb02015-10-01 10:24:31 -07002237 public static String makeTag(PendingIntent pi, String tag, int type) {
2238 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
2239 ? "*walarm*:" : "*alarm*:";
2240 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
2241 }
2242
2243 public WakeupEvent makeWakeupEvent(long nowRTC) {
2244 return new WakeupEvent(nowRTC, creatorUid,
2245 (operation != null)
2246 ? operation.getIntent().getAction()
2247 : ("<listener>:" + listenerTag));
2248 }
2249
2250 // Returns true if either matches
2251 public boolean matches(PendingIntent pi, IAlarmListener rec) {
2252 return (operation != null)
2253 ? operation.equals(pi)
2254 : listener.asBinder().equals(rec.asBinder());
2255 }
2256
2257 public boolean matches(String packageName) {
2258 return (operation != null)
2259 ? packageName.equals(operation.getTargetPackage())
2260 : packageName.equals(this.packageName);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002261 }
2262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002263 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002264 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002265 StringBuilder sb = new StringBuilder(128);
2266 sb.append("Alarm{");
2267 sb.append(Integer.toHexString(System.identityHashCode(this)));
2268 sb.append(" type ");
2269 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002270 sb.append(" when ");
2271 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002272 sb.append(" ");
Christopher Tate14a7bb02015-10-01 10:24:31 -07002273 if (operation != null) {
2274 sb.append(operation.getTargetPackage());
2275 } else {
2276 sb.append(listener.asBinder().toString());
2277 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002278 sb.append('}');
2279 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002280 }
2281
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002282 public void dump(PrintWriter pw, String prefix, long nowRTC, long nowELAPSED,
2283 SimpleDateFormat sdf) {
2284 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002285 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002286 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002287 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
2288 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002289 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002290 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002291 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002292 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002293 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002294 }
2295 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002296 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002297 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002298 pw.print(" count="); pw.print(count);
2299 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002300 if (alarmClock != null) {
2301 pw.print(prefix); pw.println("Alarm clock:");
2302 pw.print(prefix); pw.print(" triggerTime=");
2303 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
2304 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
2305 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002306 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002307 if (listener != null) {
2308 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
2309 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002310 }
2311 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002312
Christopher Tatee0a22b32013-07-11 14:43:13 -07002313 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
2314 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002315 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
2316 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002317 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07002318 break;
2319 }
2320
Christopher Tatee0a22b32013-07-11 14:43:13 -07002321 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002322 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
2323 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002324 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07002325 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002326 }
2327 }
2328
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002329 long currentNonWakeupFuzzLocked(long nowELAPSED) {
2330 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
2331 if (timeSinceOn < 5*60*1000) {
2332 // If the screen has been off for 5 minutes, only delay by at most two minutes.
2333 return 2*60*1000;
2334 } else if (timeSinceOn < 30*60*1000) {
2335 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
2336 return 15*60*1000;
2337 } else {
2338 // Otherwise, we will delay by at most an hour.
2339 return 60*60*1000;
2340 }
2341 }
2342
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002343 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002344 if (duration < 15*60*1000) {
2345 // If the duration until the time is less than 15 minutes, the maximum fuzz
2346 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002347 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002348 } else if (duration < 90*60*1000) {
2349 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
2350 return 15*60*1000;
2351 } else {
2352 // Otherwise, we will fuzz by at most half an hour.
2353 return 30*60*1000;
2354 }
2355 }
2356
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002357 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
2358 if (mInteractive) {
2359 return false;
2360 }
2361 if (mLastAlarmDeliveryTime <= 0) {
2362 return false;
2363 }
minho.choo649acab2014-12-12 16:13:55 +09002364 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002365 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
2366 // and the next delivery time is in the past, then just deliver them all. This
2367 // avoids bugs where we get stuck in a loop trying to poll for alarms.
2368 return false;
2369 }
2370 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
2371 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
2372 }
2373
2374 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
2375 mLastAlarmDeliveryTime = nowELAPSED;
2376 for (int i=0; i<triggerList.size(); i++) {
2377 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07002378 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002379 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07002380 if (localLOGV) {
2381 Slog.v(TAG, "sending alarm " + alarm);
2382 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07002383 if (RECORD_ALARMS_IN_HISTORY) {
2384 if (alarm.workSource != null && alarm.workSource.size() > 0) {
2385 for (int wi=0; wi<alarm.workSource.size(); wi++) {
2386 ActivityManagerNative.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002387 alarm.operation, alarm.workSource.get(wi), alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002388 }
2389 } else {
2390 ActivityManagerNative.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002391 alarm.operation, alarm.uid, alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002392 }
2393 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002394 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002395 } catch (RuntimeException e) {
2396 Slog.w(TAG, "Failure sending alarm.", e);
2397 }
2398 }
2399 }
2400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002401 private class AlarmThread extends Thread
2402 {
2403 public AlarmThread()
2404 {
2405 super("AlarmManager");
2406 }
2407
2408 public void run()
2409 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002410 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002412 while (true)
2413 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002414 int result = waitForAlarm(mNativeData);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002415
2416 triggerList.clear();
2417
Dianne Hackbornc3527222015-05-13 14:03:20 -07002418 final long nowRTC = System.currentTimeMillis();
2419 final long nowELAPSED = SystemClock.elapsedRealtime();
2420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002421 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002422 // The kernel can give us spurious time change notifications due to
2423 // small adjustments it makes internally; we want to filter those out.
2424 final long lastTimeChangeClockTime;
2425 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07002426 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002427 lastTimeChangeClockTime = mLastTimeChangeClockTime;
2428 expectedClockTime = lastTimeChangeClockTime
2429 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07002430 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002431 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-500)
2432 || nowRTC > (expectedClockTime+500)) {
2433 // The change is by at least +/- 500 ms (or this is the first change),
2434 // let's do it!
2435 if (DEBUG_BATCH) {
2436 Slog.v(TAG, "Time changed notification from kernel; rebatching");
2437 }
2438 removeImpl(mTimeTickSender);
2439 rebatchAllAlarms();
2440 mClockReceiver.scheduleTimeTickEvent();
2441 synchronized (mLock) {
2442 mNumTimeChanged++;
2443 mLastTimeChangeClockTime = nowRTC;
2444 mLastTimeChangeRealtime = nowELAPSED;
2445 }
2446 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
2447 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
2448 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2449 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
2450
2451 // The world has changed on us, so we need to re-evaluate alarms
2452 // regardless of whether the kernel has told us one went off.
2453 result |= IS_WAKEUP_MASK;
2454 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002455 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002456
Dianne Hackbornc3527222015-05-13 14:03:20 -07002457 if (result != TIME_CHANGED_MASK) {
2458 // If this was anything besides just a time change, then figure what if
2459 // anything to do about alarms.
2460 synchronized (mLock) {
2461 if (localLOGV) Slog.v(
2462 TAG, "Checking for alarms... rtc=" + nowRTC
2463 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07002464
Dianne Hackbornc3527222015-05-13 14:03:20 -07002465 if (WAKEUP_STATS) {
2466 if ((result & IS_WAKEUP_MASK) != 0) {
2467 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
2468 int n = 0;
2469 for (WakeupEvent event : mRecentWakeups) {
2470 if (event.when > newEarliest) break;
2471 n++; // number of now-stale entries at the list head
2472 }
2473 for (int i = 0; i < n; i++) {
2474 mRecentWakeups.remove();
2475 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002476
Dianne Hackbornc3527222015-05-13 14:03:20 -07002477 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002478 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002479 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002480
2481 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2482 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
2483 // if there are no wakeup alarms and the screen is off, we can
2484 // delay what we have so far until the future.
2485 if (mPendingNonWakeupAlarms.size() == 0) {
2486 mStartCurrentDelayTime = nowELAPSED;
2487 mNextNonWakeupDeliveryTime = nowELAPSED
2488 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
2489 }
2490 mPendingNonWakeupAlarms.addAll(triggerList);
2491 mNumDelayedAlarms += triggerList.size();
2492 rescheduleKernelAlarmsLocked();
2493 updateNextAlarmClockLocked();
2494 } else {
2495 // now deliver the alarm intents; if there are pending non-wakeup
2496 // alarms, we need to merge them in to the list. note we don't
2497 // just deliver them first because we generally want non-wakeup
2498 // alarms delivered after wakeup alarms.
2499 rescheduleKernelAlarmsLocked();
2500 updateNextAlarmClockLocked();
2501 if (mPendingNonWakeupAlarms.size() > 0) {
2502 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
2503 triggerList.addAll(mPendingNonWakeupAlarms);
2504 Collections.sort(triggerList, mAlarmDispatchComparator);
2505 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2506 mTotalDelayTime += thisDelayTime;
2507 if (mMaxDelayTime < thisDelayTime) {
2508 mMaxDelayTime = thisDelayTime;
2509 }
2510 mPendingNonWakeupAlarms.clear();
2511 }
2512 deliverAlarmsLocked(triggerList, nowELAPSED);
2513 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514 }
2515 }
2516 }
2517 }
2518 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002519
David Christieebe51fc2013-07-26 13:23:29 -07002520 /**
2521 * Attribute blame for a WakeLock.
2522 * @param pi PendingIntent to attribute blame to if ws is null.
2523 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002524 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07002525 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002526 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002527 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07002528 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002529 final boolean unimportant = pi == mTimeTickSender;
2530 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002531 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002532 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002533 } else {
2534 mWakeLock.setHistoryTag(null);
2535 }
2536 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07002537 if (ws != null) {
2538 mWakeLock.setWorkSource(ws);
2539 return;
2540 }
2541
Christopher Tate14a7bb02015-10-01 10:24:31 -07002542 final int uid = (knownUid >= 0)
2543 ? knownUid
2544 : ActivityManagerNative.getDefault().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07002545 if (uid >= 0) {
2546 mWakeLock.setWorkSource(new WorkSource(uid));
2547 return;
2548 }
2549 } catch (Exception e) {
2550 }
2551
2552 // Something went wrong; fall back to attributing the lock to the OS
2553 mWakeLock.setWorkSource(null);
2554 }
2555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 private class AlarmHandler extends Handler {
2557 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002558 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
2559 public static final int LISTENER_TIMEOUT = 3;
2560 public static final int REPORT_ALARMS_ACTIVE = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002561
2562 public AlarmHandler() {
2563 }
2564
2565 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002566 switch (msg.what) {
2567 case ALARM_EVENT: {
2568 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2569 synchronized (mLock) {
2570 final long nowRTC = System.currentTimeMillis();
2571 final long nowELAPSED = SystemClock.elapsedRealtime();
2572 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2573 updateNextAlarmClockLocked();
2574 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002575
Christopher Tate14a7bb02015-10-01 10:24:31 -07002576 // now trigger the alarms without the lock held
2577 for (int i=0; i<triggerList.size(); i++) {
2578 Alarm alarm = triggerList.get(i);
2579 try {
2580 alarm.operation.send();
2581 } catch (PendingIntent.CanceledException e) {
2582 if (alarm.repeatInterval > 0) {
2583 // This IntentSender is no longer valid, but this
2584 // is a repeating alarm, so toss the hoser.
2585 removeImpl(alarm.operation);
2586 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 }
2588 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002589 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002590 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002591
2592 case SEND_NEXT_ALARM_CLOCK_CHANGED:
2593 sendNextAlarmClockChanged();
2594 break;
2595
2596 case LISTENER_TIMEOUT:
2597 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
2598 break;
2599
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002600 case REPORT_ALARMS_ACTIVE:
2601 if (mLocalDeviceIdleController != null) {
2602 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
2603 }
2604 break;
2605
Christopher Tate14a7bb02015-10-01 10:24:31 -07002606 default:
2607 // nope, just ignore it
2608 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002609 }
2610 }
2611 }
2612
2613 class ClockReceiver extends BroadcastReceiver {
2614 public ClockReceiver() {
2615 IntentFilter filter = new IntentFilter();
2616 filter.addAction(Intent.ACTION_TIME_TICK);
2617 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002618 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002619 }
2620
2621 @Override
2622 public void onReceive(Context context, Intent intent) {
2623 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07002624 if (DEBUG_BATCH) {
2625 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
2626 }
2627 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002628 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
2629 // Since the kernel does not keep track of DST, we need to
2630 // reset the TZ information at the beginning of each day
2631 // based off of the current Zone gmt offset + userspace tracked
2632 // daylight savings information.
2633 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02002634 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002635 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07002636 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002637 }
2638 }
2639
2640 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07002641 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09002642 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07002643
2644 // Schedule this event for the amount of time that it would take to get to
2645 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09002646 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07002647
David Christieebe51fc2013-07-26 13:23:29 -07002648 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002649 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002650 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
2651 null, Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002652 }
Christopher Tate385e4982013-07-23 18:22:29 -07002653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002654 public void scheduleDateChangedEvent() {
2655 Calendar calendar = Calendar.getInstance();
2656 calendar.setTimeInMillis(System.currentTimeMillis());
2657 calendar.set(Calendar.HOUR, 0);
2658 calendar.set(Calendar.MINUTE, 0);
2659 calendar.set(Calendar.SECOND, 0);
2660 calendar.set(Calendar.MILLISECOND, 0);
2661 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07002662
2663 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002664 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
2665 AlarmManager.FLAG_STANDALONE, workSource, null,
2666 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002667 }
2668 }
2669
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002670 class InteractiveStateReceiver extends BroadcastReceiver {
2671 public InteractiveStateReceiver() {
2672 IntentFilter filter = new IntentFilter();
2673 filter.addAction(Intent.ACTION_SCREEN_OFF);
2674 filter.addAction(Intent.ACTION_SCREEN_ON);
2675 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
2676 getContext().registerReceiver(this, filter);
2677 }
2678
2679 @Override
2680 public void onReceive(Context context, Intent intent) {
2681 synchronized (mLock) {
2682 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
2683 }
2684 }
2685 }
2686
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002687 class UninstallReceiver extends BroadcastReceiver {
2688 public UninstallReceiver() {
2689 IntentFilter filter = new IntentFilter();
2690 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2691 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002692 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002693 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08002694 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002695 // Register for events related to sdcard installation.
2696 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08002697 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002698 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002699 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002700 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002701 }
2702
2703 @Override
2704 public void onReceive(Context context, Intent intent) {
2705 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002706 String action = intent.getAction();
2707 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002708 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
2709 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
2710 for (String packageName : pkgList) {
2711 if (lookForPackageLocked(packageName)) {
2712 setResultCode(Activity.RESULT_OK);
2713 return;
2714 }
2715 }
2716 return;
2717 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002718 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002719 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
2720 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
2721 if (userHandle >= 0) {
2722 removeUserLocked(userHandle);
2723 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002724 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
2725 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
2726 if (uid >= 0) {
2727 mLastAllowWhileIdleDispatch.delete(uid);
2728 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002729 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08002730 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
2731 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
2732 // This package is being updated; don't kill its alarms.
2733 return;
2734 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002735 Uri data = intent.getData();
2736 if (data != null) {
2737 String pkg = data.getSchemeSpecificPart();
2738 if (pkg != null) {
2739 pkgList = new String[]{pkg};
2740 }
2741 }
2742 }
2743 if (pkgList != null && (pkgList.length > 0)) {
2744 for (String pkg : pkgList) {
2745 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07002746 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002747 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
2748 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
2749 if (uidStats.remove(pkg) != null) {
2750 if (uidStats.size() <= 0) {
2751 mBroadcastStats.removeAt(i);
2752 }
2753 }
2754 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002755 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002756 }
2757 }
2758 }
2759 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002760
2761 final class UidObserver extends IUidObserver.Stub {
2762 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
2763 }
2764
2765 @Override public void onUidGone(int uid) throws RemoteException {
2766 }
2767
2768 @Override public void onUidActive(int uid) throws RemoteException {
2769 }
2770
2771 @Override public void onUidIdle(int uid) throws RemoteException {
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08002772 synchronized (mLock) {
2773 removeForStoppedLocked(uid);
2774 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002775 }
2776 };
2777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002778 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002779 String pkg = pi.getCreatorPackage();
2780 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002781 return getStatsLocked(uid, pkg);
2782 }
2783
2784 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002785 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
2786 if (uidStats == null) {
2787 uidStats = new ArrayMap<String, BroadcastStats>();
2788 mBroadcastStats.put(uid, uidStats);
2789 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002790 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002791 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002792 bs = new BroadcastStats(uid, pkgName);
2793 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002794 }
2795 return bs;
2796 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002797
Christopher Tate14a7bb02015-10-01 10:24:31 -07002798 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
2799 private InFlight removeLocked(PendingIntent pi, Intent intent) {
2800 for (int i = 0; i < mInFlight.size(); i++) {
2801 if (mInFlight.get(i).mPendingIntent == pi) {
2802 return mInFlight.remove(i);
2803 }
2804 }
2805 mLog.w("No in-flight alarm for " + pi + " " + intent);
2806 return null;
2807 }
2808
2809 private InFlight removeLocked(IBinder listener) {
2810 for (int i = 0; i < mInFlight.size(); i++) {
2811 if (mInFlight.get(i).mListener == listener) {
2812 return mInFlight.remove(i);
2813 }
2814 }
2815 mLog.w("No in-flight alarm for listener " + listener);
2816 return null;
2817 }
2818
2819 private void updateStatsLocked(InFlight inflight) {
2820 final long nowELAPSED = SystemClock.elapsedRealtime();
2821 BroadcastStats bs = inflight.mBroadcastStats;
2822 bs.nesting--;
2823 if (bs.nesting <= 0) {
2824 bs.nesting = 0;
2825 bs.aggregateTime += nowELAPSED - bs.startTime;
2826 }
2827 FilterStats fs = inflight.mFilterStats;
2828 fs.nesting--;
2829 if (fs.nesting <= 0) {
2830 fs.nesting = 0;
2831 fs.aggregateTime += nowELAPSED - fs.startTime;
2832 }
2833 if (RECORD_ALARMS_IN_HISTORY) {
2834 if (inflight.mWorkSource != null && inflight.mWorkSource.size() > 0) {
2835 for (int wi=0; wi<inflight.mWorkSource.size(); wi++) {
2836 ActivityManagerNative.noteAlarmFinish(
2837 inflight.mPendingIntent, inflight.mWorkSource.get(wi), inflight.mTag);
2838 }
2839 } else {
2840 ActivityManagerNative.noteAlarmFinish(
2841 inflight.mPendingIntent, inflight.mUid, inflight.mTag);
2842 }
2843 }
2844 }
2845
2846 private void updateTrackingLocked(InFlight inflight) {
2847 if (inflight != null) {
2848 updateStatsLocked(inflight);
2849 }
2850 mBroadcastRefCount--;
2851 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002852 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002853 mWakeLock.release();
2854 if (mInFlight.size() > 0) {
2855 mLog.w("Finished all dispatches with " + mInFlight.size()
2856 + " remaining inflights");
2857 for (int i=0; i<mInFlight.size(); i++) {
2858 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
2859 }
2860 mInFlight.clear();
2861 }
2862 } else {
2863 // the next of our alarms is now in flight. reattribute the wakelock.
2864 if (mInFlight.size() > 0) {
2865 InFlight inFlight = mInFlight.get(0);
2866 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
2867 inFlight.mAlarmType, inFlight.mTag, -1, false);
2868 } else {
2869 // should never happen
2870 mLog.w("Alarm wakelock still held but sent queue empty");
2871 mWakeLock.setWorkSource(null);
2872 }
2873 }
2874 }
2875
2876 /**
2877 * Callback that arrives when a direct-call alarm reports that delivery has finished
2878 */
2879 @Override
2880 public void alarmComplete(IBinder who) {
2881 if (who == null) {
2882 Slog.w(TAG, "Invalid alarmComplete: uid=" + Binder.getCallingUid()
2883 + " pid=" + Binder.getCallingPid());
2884 return;
2885 }
2886
2887 final long ident = Binder.clearCallingIdentity();
2888 try {
2889 synchronized (mLock) {
2890 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
2891 InFlight inflight = removeLocked(who);
2892 if (inflight != null) {
2893 if (DEBUG_LISTENER_CALLBACK) {
2894 Slog.i(TAG, "alarmComplete() from " + who);
2895 }
2896 updateTrackingLocked(inflight);
2897 } else {
2898 // Delivery timed out, and the timeout handling already took care of
2899 // updating our tracking here, so we needn't do anything further.
2900 if (DEBUG_LISTENER_CALLBACK) {
2901 Slog.i(TAG, "Late alarmComplete() from " + who);
2902 }
2903 }
2904 }
2905 } finally {
2906 Binder.restoreCallingIdentity(ident);
2907 }
2908 }
2909
2910 /**
2911 * Callback that arrives when a PendingIntent alarm has finished delivery
2912 */
2913 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002914 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
2915 String resultData, Bundle resultExtras) {
2916 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002917 updateTrackingLocked(removeLocked(pi, intent));
2918 }
2919 }
2920
2921 /**
2922 * Timeout of a direct-call alarm delivery
2923 */
2924 public void alarmTimedOut(IBinder who) {
2925 synchronized (mLock) {
2926 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08002927 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002928 // TODO: implement ANR policy for the target
2929 if (DEBUG_LISTENER_CALLBACK) {
2930 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002931 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002932 updateTrackingLocked(inflight);
Dianne Hackborn81038902012-11-26 17:04:09 -08002933 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002934 if (DEBUG_LISTENER_CALLBACK) {
2935 Slog.i(TAG, "Spurious timeout of listener " + who);
2936 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002937 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002938 }
2939 }
2940
2941 /**
2942 * Deliver an alarm and set up the post-delivery handling appropriately
2943 */
2944 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
2945 if (alarm.operation != null) {
2946 // PendingIntent alarm
2947 try {
2948 alarm.operation.send(getContext(), 0,
2949 mBackgroundIntent.putExtra(
2950 Intent.EXTRA_ALARM_COUNT, alarm.count),
2951 mDeliveryTracker, mHandler, null,
2952 allowWhileIdle ? mIdleOptions : null);
2953 } catch (PendingIntent.CanceledException e) {
2954 if (alarm.repeatInterval > 0) {
2955 // This IntentSender is no longer valid, but this
2956 // is a repeating alarm, so toss it
2957 removeImpl(alarm.operation);
2958 }
2959 }
2960 } else {
2961 // Direct listener callback alarm
2962 try {
2963 if (DEBUG_LISTENER_CALLBACK) {
2964 Slog.v(TAG, "Alarm to uid=" + alarm.uid
2965 + " listener=" + alarm.listener.asBinder());
2966 }
2967 alarm.listener.doAlarm(this);
2968 mHandler.sendMessageDelayed(
2969 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
2970 alarm.listener.asBinder()),
2971 mConstants.LISTENER_TIMEOUT);
2972 } catch (Exception e) {
2973 if (DEBUG_LISTENER_CALLBACK) {
2974 Slog.i(TAG, "Alarm undeliverable to listener "
2975 + alarm.listener.asBinder(), e);
2976 }
2977 }
2978 }
2979
2980 // The alarm is now in flight; now arrange wakelock and stats tracking
2981 if (mBroadcastRefCount == 0) {
2982 setWakelockWorkSource(alarm.operation, alarm.workSource,
2983 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
2984 true);
2985 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002986 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002987 }
2988 final InFlight inflight = new InFlight(AlarmManagerService.this,
2989 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
2990 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
2991 mInFlight.add(inflight);
2992 mBroadcastRefCount++;
2993
2994 if (allowWhileIdle) {
2995 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
2996 mLastAllowWhileIdleDispatch.put(alarm.uid, nowELAPSED);
2997 if (RECORD_DEVICE_IDLE_ALARMS) {
2998 IdleDispatchEntry ent = new IdleDispatchEntry();
2999 ent.uid = alarm.uid;
3000 ent.pkg = alarm.packageName;
3001 ent.tag = alarm.statsTag;
3002 ent.op = "DELIVER";
3003 ent.elapsedRealtime = nowELAPSED;
3004 mAllowWhileIdleDispatches.add(ent);
3005 }
3006 }
3007
3008 final BroadcastStats bs = inflight.mBroadcastStats;
3009 bs.count++;
3010 if (bs.nesting == 0) {
3011 bs.nesting = 1;
3012 bs.startTime = nowELAPSED;
3013 } else {
3014 bs.nesting++;
3015 }
3016 final FilterStats fs = inflight.mFilterStats;
3017 fs.count++;
3018 if (fs.nesting == 0) {
3019 fs.nesting = 1;
3020 fs.startTime = nowELAPSED;
3021 } else {
3022 fs.nesting++;
3023 }
3024 if (alarm.type == ELAPSED_REALTIME_WAKEUP
3025 || alarm.type == RTC_WAKEUP) {
3026 bs.numWakeup++;
3027 fs.numWakeup++;
3028 if (alarm.workSource != null && alarm.workSource.size() > 0) {
3029 for (int wi=0; wi<alarm.workSource.size(); wi++) {
3030 ActivityManagerNative.noteWakeupAlarm(
3031 alarm.operation, alarm.workSource.get(wi),
3032 alarm.workSource.getName(wi), alarm.statsTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08003033 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003034 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003035 ActivityManagerNative.noteWakeupAlarm(
3036 alarm.operation, -1, alarm.packageName, alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003037 }
3038 }
3039 }
3040 }
3041}