blob: f9d9950089b6de975e4d84e5c38613b18fbcf388 [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;
28import android.app.PendingIntent;
29import android.content.BroadcastReceiver;
Dianne Hackborna750a632015-06-16 17:18:23 -070030import android.content.ContentResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.content.Context;
32import android.content.Intent;
33import android.content.IntentFilter;
34import android.content.pm.PackageManager;
Dianne Hackborna750a632015-06-16 17:18:23 -070035import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.net.Uri;
37import android.os.Binder;
38import android.os.Bundle;
39import android.os.Handler;
Adam Lesinski182f73f2013-12-05 16:48:06 -080040import android.os.IBinder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.os.Message;
42import android.os.PowerManager;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070043import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.os.SystemClock;
45import android.os.SystemProperties;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070046import android.os.UserHandle;
Christopher Tatec4a07d12012-04-06 14:19:13 -070047import android.os.WorkSource;
Adrian Roosc42a1e12014-07-07 23:35:53 +020048import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.text.TextUtils;
Adrian Roosc42a1e12014-07-07 23:35:53 +020050import android.text.format.DateFormat;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080051import android.util.ArrayMap;
Dianne Hackborna750a632015-06-16 17:18:23 -070052import android.util.KeyValueListParser;
Adrian Roosc42a1e12014-07-07 23:35:53 +020053import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080054import android.util.Slog;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080055import android.util.SparseArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +020056import android.util.SparseBooleanArray;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -070057import android.util.SparseLongArray;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070058import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059
Christopher Tate4cb338d2013-07-26 13:11:31 -070060import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import java.io.FileDescriptor;
62import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070063import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -080065import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import java.util.Calendar;
67import java.util.Collections;
68import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -050069import java.util.Date;
Christopher Tate1590f1e2014-10-02 17:27:57 -070070import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -070071import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +020072import java.util.Locale;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070073import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import java.util.TimeZone;
John Spurlock604a5ee2015-06-01 12:27:22 -040075import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076
Christopher Tatee0a22b32013-07-11 14:43:13 -070077import static android.app.AlarmManager.RTC_WAKEUP;
78import static android.app.AlarmManager.RTC;
79import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
80import static android.app.AlarmManager.ELAPSED_REALTIME;
81
Dianne Hackborn81038902012-11-26 17:04:09 -080082import com.android.internal.util.LocalLog;
83
Adam Lesinski182f73f2013-12-05 16:48:06 -080084class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -070085 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
86 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -080087 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -070088 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -080089 static final int TIME_CHANGED_MASK = 1 << 16;
90 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -080091
Christopher Tatee0a22b32013-07-11 14:43:13 -070092 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -080093 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -080094
Adam Lesinski182f73f2013-12-05 16:48:06 -080095 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -080096 static final boolean localLOGV = false;
97 static final boolean DEBUG_BATCH = localLOGV || false;
98 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +020099 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700100 static final boolean DEBUG_LISTENER_CALLBACK = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700101 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700102 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800103 static final int ALARM_EVENT = 1;
104 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200105
Christopher Tate14a7bb02015-10-01 10:24:31 -0700106 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800108 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109
Adam Lesinski182f73f2013-12-05 16:48:06 -0800110 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700111
Adrian Roosc42a1e12014-07-07 23:35:53 +0200112 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT = new Intent(
113 AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED);
114
Adam Lesinski182f73f2013-12-05 16:48:06 -0800115 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800116
Christopher Tate14a7bb02015-10-01 10:24:31 -0700117 AppOpsManager mAppOps;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800118 DeviceIdleController.LocalService mLocalDeviceIdleController;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700119
Adam Lesinski182f73f2013-12-05 16:48:06 -0800120 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800121
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800122 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800123 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700124 private long mNextNonWakeup;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800125 int mBroadcastRefCount = 0;
126 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700127 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700128 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
129 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800130 final AlarmHandler mHandler = new AlarmHandler();
131 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700132 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700134 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800135 PendingIntent mTimeTickSender;
136 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700137 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700138 boolean mInteractive = true;
139 long mNonInteractiveStartTime;
140 long mNonInteractiveTime;
141 long mLastAlarmDeliveryTime;
142 long mStartCurrentDelayTime;
143 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700144 long mLastTimeChangeClockTime;
145 long mLastTimeChangeRealtime;
Dianne Hackborna750a632015-06-16 17:18:23 -0700146 long mAllowWhileIdleMinTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700147 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800148
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700149 /**
150 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
151 * used to determine the earliest we can dispatch the next such alarm.
152 */
153 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
154
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700155 final static class IdleDispatchEntry {
156 int uid;
157 String pkg;
158 String tag;
159 String op;
160 long elapsedRealtime;
161 long argRealtime;
162 }
163 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
164
Dianne Hackborna750a632015-06-16 17:18:23 -0700165 /**
166 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
167 */
168 Bundle mIdleOptions;
169
Jose Lima235510e2014-08-13 12:50:01 -0700170 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
171 new SparseArray<>();
172 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
173 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200174 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
175 new SparseBooleanArray();
176 private boolean mNextAlarmClockMayChange;
177
178 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700179 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
180 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200181
Dianne Hackborna750a632015-06-16 17:18:23 -0700182 /**
183 * All times are in milliseconds. These constants are kept synchronized with the system
184 * global Settings. Any access to this class or its fields should be done while
185 * holding the AlarmManagerService.mLock lock.
186 */
187 private final class Constants extends ContentObserver {
188 // Key names stored in the settings value.
189 private static final String KEY_MIN_FUTURITY = "min_futurity";
190 private static final String KEY_MIN_INTERVAL = "min_interval";
191 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
192 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
193 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
194 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700195 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Dianne Hackborna750a632015-06-16 17:18:23 -0700196
197 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
198 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tateaa244da2015-08-27 15:57:57 -0700199 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700200 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700201 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
202
Christopher Tate14a7bb02015-10-01 10:24:31 -0700203 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
204
Dianne Hackborna750a632015-06-16 17:18:23 -0700205 // Minimum futurity of a new alarm
206 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
207
208 // Minimum alarm recurrence interval
209 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
210
211 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
212 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
213
214 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
215 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
216
217 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
218 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
219 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
220
Christopher Tate14a7bb02015-10-01 10:24:31 -0700221 // Direct alarm listener callback timeout
222 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
223
Dianne Hackborna750a632015-06-16 17:18:23 -0700224 private ContentResolver mResolver;
225 private final KeyValueListParser mParser = new KeyValueListParser(',');
226 private long mLastAllowWhileIdleWhitelistDuration = -1;
227
228 public Constants(Handler handler) {
229 super(handler);
230 updateAllowWhileIdleMinTimeLocked();
231 updateAllowWhileIdleWhitelistDurationLocked();
232 }
233
234 public void start(ContentResolver resolver) {
235 mResolver = resolver;
236 mResolver.registerContentObserver(Settings.Global.getUriFor(
237 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
238 updateConstants();
239 }
240
241 public void updateAllowWhileIdleMinTimeLocked() {
242 mAllowWhileIdleMinTime = mPendingIdleUntil != null
243 ? ALLOW_WHILE_IDLE_LONG_TIME : ALLOW_WHILE_IDLE_SHORT_TIME;
244 }
245
246 public void updateAllowWhileIdleWhitelistDurationLocked() {
247 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
248 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
249 BroadcastOptions opts = BroadcastOptions.makeBasic();
250 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
251 mIdleOptions = opts.toBundle();
252 }
253 }
254
255 @Override
256 public void onChange(boolean selfChange, Uri uri) {
257 updateConstants();
258 }
259
260 private void updateConstants() {
261 synchronized (mLock) {
262 try {
263 mParser.setString(Settings.Global.getString(mResolver,
264 Settings.Global.ALARM_MANAGER_CONSTANTS));
265 } catch (IllegalArgumentException e) {
266 // Failed to parse the settings string, log this and move on
267 // with defaults.
268 Slog.e(TAG, "Bad device idle settings", e);
269 }
270
271 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
272 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
273 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
274 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
275 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
276 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
277 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
278 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
279 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700280 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
281 DEFAULT_LISTENER_TIMEOUT);
Dianne Hackborna750a632015-06-16 17:18:23 -0700282
283 updateAllowWhileIdleMinTimeLocked();
284 updateAllowWhileIdleWhitelistDurationLocked();
285 }
286 }
287
288 void dump(PrintWriter pw) {
289 pw.println(" Settings:");
290
291 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
292 TimeUtils.formatDuration(MIN_FUTURITY, pw);
293 pw.println();
294
295 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
296 TimeUtils.formatDuration(MIN_INTERVAL, pw);
297 pw.println();
298
Christopher Tate14a7bb02015-10-01 10:24:31 -0700299 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
300 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
301 pw.println();
302
Dianne Hackborna750a632015-06-16 17:18:23 -0700303 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
304 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
305 pw.println();
306
307 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
308 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
309 pw.println();
310
311 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
312 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
313 pw.println();
314 }
315 }
316
317 final Constants mConstants;
318
Christopher Tate1590f1e2014-10-02 17:27:57 -0700319 // Alarm delivery ordering bookkeeping
320 static final int PRIO_TICK = 0;
321 static final int PRIO_WAKEUP = 1;
322 static final int PRIO_NORMAL = 2;
323
Dianne Hackborna750a632015-06-16 17:18:23 -0700324 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700325 int seq;
326 int priority;
327
328 PriorityClass() {
329 seq = mCurrentSeq - 1;
330 priority = PRIO_NORMAL;
331 }
332 }
333
Dianne Hackborna750a632015-06-16 17:18:23 -0700334 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700335 int mCurrentSeq = 0;
336
Dianne Hackborna750a632015-06-16 17:18:23 -0700337 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700338 public long when;
339 public int uid;
340 public String action;
341
342 public WakeupEvent(long theTime, int theUid, String theAction) {
343 when = theTime;
344 uid = theUid;
345 action = theAction;
346 }
347 }
348
Adam Lesinski182f73f2013-12-05 16:48:06 -0800349 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
350 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700351
Adrian Roosc42a1e12014-07-07 23:35:53 +0200352 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700353 long start; // These endpoints are always in ELAPSED
354 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700355 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700356
357 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
358
359 Batch() {
360 start = 0;
361 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700362 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700363 }
364
365 Batch(Alarm seed) {
366 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700367 end = seed.maxWhenElapsed;
368 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700369 alarms.add(seed);
370 }
371
372 int size() {
373 return alarms.size();
374 }
375
376 Alarm get(int index) {
377 return alarms.get(index);
378 }
379
380 boolean canHold(long whenElapsed, long maxWhen) {
381 return (end >= whenElapsed) && (start <= maxWhen);
382 }
383
384 boolean add(Alarm alarm) {
385 boolean newStart = false;
386 // narrows the batch if necessary; presumes that canHold(alarm) is true
387 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
388 if (index < 0) {
389 index = 0 - index - 1;
390 }
391 alarms.add(index, alarm);
392 if (DEBUG_BATCH) {
393 Slog.v(TAG, "Adding " + alarm + " to " + this);
394 }
395 if (alarm.whenElapsed > start) {
396 start = alarm.whenElapsed;
397 newStart = true;
398 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700399 if (alarm.maxWhenElapsed < end) {
400 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700401 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700402 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700403
404 if (DEBUG_BATCH) {
405 Slog.v(TAG, " => now " + this);
406 }
407 return newStart;
408 }
409
Christopher Tate14a7bb02015-10-01 10:24:31 -0700410 boolean remove(final PendingIntent operation, final IAlarmListener listener) {
411 if (operation == null && listener == null) {
412 if (localLOGV) {
413 Slog.w(TAG, "requested remove() of null operation",
414 new RuntimeException("here"));
415 }
416 return false;
417 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700418 boolean didRemove = false;
419 long newStart = 0; // recalculate endpoints as we go
420 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700421 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700422 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700423 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700424 if (alarm.matches(operation, listener)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700425 alarms.remove(i);
426 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200427 if (alarm.alarmClock != null) {
428 mNextAlarmClockMayChange = true;
429 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700430 } else {
431 if (alarm.whenElapsed > newStart) {
432 newStart = alarm.whenElapsed;
433 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700434 if (alarm.maxWhenElapsed < newEnd) {
435 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700436 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700437 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700438 i++;
439 }
440 }
441 if (didRemove) {
442 // commit the new batch bounds
443 start = newStart;
444 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700445 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700446 }
447 return didRemove;
448 }
449
450 boolean remove(final String packageName) {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700451 if (packageName == null) {
452 if (localLOGV) {
453 Slog.w(TAG, "requested remove() of null packageName",
454 new RuntimeException("here"));
455 }
456 return false;
457 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700458 boolean didRemove = false;
459 long newStart = 0; // recalculate endpoints as we go
460 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700461 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700462 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700463 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700464 if (alarm.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700465 alarms.remove(i);
466 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200467 if (alarm.alarmClock != null) {
468 mNextAlarmClockMayChange = true;
469 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700470 } else {
471 if (alarm.whenElapsed > newStart) {
472 newStart = alarm.whenElapsed;
473 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700474 if (alarm.maxWhenElapsed < newEnd) {
475 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700476 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700477 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700478 i++;
479 }
480 }
481 if (didRemove) {
482 // commit the new batch bounds
483 start = newStart;
484 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700485 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700486 }
487 return didRemove;
488 }
489
490 boolean remove(final int userHandle) {
491 boolean didRemove = false;
492 long newStart = 0; // recalculate endpoints as we go
493 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700494 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700495 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700496 if (UserHandle.getUserId(alarm.creatorUid) == userHandle) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700497 alarms.remove(i);
498 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200499 if (alarm.alarmClock != null) {
500 mNextAlarmClockMayChange = true;
501 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700502 } else {
503 if (alarm.whenElapsed > newStart) {
504 newStart = alarm.whenElapsed;
505 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700506 if (alarm.maxWhenElapsed < newEnd) {
507 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700508 }
509 i++;
510 }
511 }
512 if (didRemove) {
513 // commit the new batch bounds
514 start = newStart;
515 end = newEnd;
516 }
517 return didRemove;
518 }
519
520 boolean hasPackage(final String packageName) {
521 final int N = alarms.size();
522 for (int i = 0; i < N; i++) {
523 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700524 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700525 return true;
526 }
527 }
528 return false;
529 }
530
531 boolean hasWakeups() {
532 final int N = alarms.size();
533 for (int i = 0; i < N; i++) {
534 Alarm a = alarms.get(i);
535 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
536 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
537 return true;
538 }
539 }
540 return false;
541 }
542
543 @Override
544 public String toString() {
545 StringBuilder b = new StringBuilder(40);
546 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
547 b.append(" num="); b.append(size());
548 b.append(" start="); b.append(start);
549 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700550 if (flags != 0) {
551 b.append(" flgs=0x");
552 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700553 }
554 b.append('}');
555 return b.toString();
556 }
557 }
558
559 static class BatchTimeOrder implements Comparator<Batch> {
560 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800561 long when1 = b1.start;
562 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800563 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700564 return 1;
565 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800566 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700567 return -1;
568 }
569 return 0;
570 }
571 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800572
573 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
574 @Override
575 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700576 // priority class trumps everything. TICK < WAKEUP < NORMAL
577 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
578 return -1;
579 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
580 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800581 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700582
583 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800584 if (lhs.whenElapsed < rhs.whenElapsed) {
585 return -1;
586 } else if (lhs.whenElapsed > rhs.whenElapsed) {
587 return 1;
588 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700589
590 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800591 return 0;
592 }
593 };
594
Christopher Tate1590f1e2014-10-02 17:27:57 -0700595 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
596 final int N = alarms.size();
597 for (int i = 0; i < N; i++) {
598 Alarm a = alarms.get(i);
599
600 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700601 if (a.operation != null
602 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700603 alarmPrio = PRIO_TICK;
604 } else if (a.wakeup) {
605 alarmPrio = PRIO_WAKEUP;
606 } else {
607 alarmPrio = PRIO_NORMAL;
608 }
609
610 PriorityClass packagePrio = a.priorityClass;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700611 String alarmPackage = (a.operation != null)
612 ? a.operation.getCreatorPackage()
613 : a.packageName;
614 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700615 if (packagePrio == null) {
616 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700617 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700618 }
619 a.priorityClass = packagePrio;
620
621 if (packagePrio.seq != mCurrentSeq) {
622 // first alarm we've seen in the current delivery generation from this package
623 packagePrio.priority = alarmPrio;
624 packagePrio.seq = mCurrentSeq;
625 } else {
626 // Multiple alarms from this package being delivered in this generation;
627 // bump the package's delivery class if it's warranted.
628 // TICK < WAKEUP < NORMAL
629 if (alarmPrio < packagePrio.priority) {
630 packagePrio.priority = alarmPrio;
631 }
632 }
633 }
634 }
635
Christopher Tatee0a22b32013-07-11 14:43:13 -0700636 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800637 static final long MIN_FUZZABLE_INTERVAL = 10000;
638 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700639 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
640
641 // set to null if in idle mode; while in this mode, any alarms we don't want
642 // to run during this time are placed in mPendingWhileIdleAlarms
643 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700644 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700645 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700646
Jeff Brownb880d882014-02-10 19:47:07 -0800647 public AlarmManagerService(Context context) {
648 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700649 mConstants = new Constants(mHandler);
Jeff Brownb880d882014-02-10 19:47:07 -0800650 }
651
Christopher Tatee0a22b32013-07-11 14:43:13 -0700652 static long convertToElapsed(long when, int type) {
653 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
654 if (isRtc) {
655 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
656 }
657 return when;
658 }
659
660 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
661 // calculate the end of our nominal delivery window for the alarm.
662 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
663 // Current heuristic: batchable window is 75% of either the recurrence interval
664 // [for a periodic alarm] or of the time from now to the desired delivery time,
665 // with a minimum delay/interval of 10 seconds, under which we will simply not
666 // defer the alarm.
667 long futurity = (interval == 0)
668 ? (triggerAtTime - now)
669 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700670 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700671 futurity = 0;
672 }
673 return triggerAtTime + (long)(.75 * futurity);
674 }
675
676 // returns true if the batch was added at the head
677 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
678 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
679 if (index < 0) {
680 index = 0 - index - 1;
681 }
682 list.add(index, newBatch);
683 return (index == 0);
684 }
685
Christopher Tate385e4982013-07-23 18:22:29 -0700686 // Return the index of the matching batch, or -1 if none found.
687 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700688 final int N = mAlarmBatches.size();
689 for (int i = 0; i < N; i++) {
690 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700691 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700692 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700693 }
694 }
Christopher Tate385e4982013-07-23 18:22:29 -0700695 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700696 }
697
698 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
699 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700700 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700701 rebatchAllAlarmsLocked(true);
702 }
703 }
704
705 void rebatchAllAlarmsLocked(boolean doValidate) {
706 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
707 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700708 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700709 final long nowElapsed = SystemClock.elapsedRealtime();
710 final int oldBatches = oldSet.size();
711 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
712 Batch batch = oldSet.get(batchNum);
713 final int N = batch.size();
714 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700715 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700716 }
717 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700718 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
719 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
720 + " to " + mPendingIdleUntil);
721 if (mPendingIdleUntil == null) {
722 // Somehow we lost this... we need to restore all of the pending alarms.
723 restorePendingWhileIdleAlarmsLocked();
724 }
725 }
726 rescheduleKernelAlarmsLocked();
727 updateNextAlarmClockLocked();
728 }
729
730 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
731 a.when = a.origWhen;
732 long whenElapsed = convertToElapsed(a.when, a.type);
733 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700734 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700735 // Exact
736 maxElapsed = whenElapsed;
737 } else {
738 // Not exact. Preserve any explicit window, otherwise recalculate
739 // the window based on the alarm's new futurity. Note that this
740 // reflects a policy of preferring timely to deferred delivery.
741 maxElapsed = (a.windowLength > 0)
742 ? (whenElapsed + a.windowLength)
743 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
744 }
745 a.whenElapsed = whenElapsed;
746 a.maxWhenElapsed = maxElapsed;
747 setImplLocked(a, true, doValidate);
748 }
749
750 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700751 if (RECORD_DEVICE_IDLE_ALARMS) {
752 IdleDispatchEntry ent = new IdleDispatchEntry();
753 ent.uid = 0;
754 ent.pkg = "FINISH IDLE";
755 ent.elapsedRealtime = SystemClock.elapsedRealtime();
756 mAllowWhileIdleDispatches.add(ent);
757 }
758
Dianne Hackborn35d54032015-04-23 10:30:43 -0700759 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700760 if (mPendingWhileIdleAlarms.size() > 0) {
761 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
762 mPendingWhileIdleAlarms = new ArrayList<>();
763 final long nowElapsed = SystemClock.elapsedRealtime();
764 for (int i=alarms.size() - 1; i >= 0; i--) {
765 Alarm a = alarms.get(i);
766 reAddAlarmLocked(a, nowElapsed, false);
767 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700768 }
Dianne Hackborn35d54032015-04-23 10:30:43 -0700769
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700770 // Make sure we are using the correct ALLOW_WHILE_IDLE min time.
Dianne Hackborna750a632015-06-16 17:18:23 -0700771 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700772
Dianne Hackborn35d54032015-04-23 10:30:43 -0700773 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700774 rescheduleKernelAlarmsLocked();
775 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -0700776
777 // And send a TIME_TICK right now, since it is important to get the UI updated.
778 try {
779 mTimeTickSender.send();
780 } catch (PendingIntent.CanceledException e) {
781 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700782 }
783
Christopher Tate14a7bb02015-10-01 10:24:31 -0700784 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -0800785 final PendingIntent mPendingIntent;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700786 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -0700787 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700788 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700789 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800790 final BroadcastStats mBroadcastStats;
791 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800792 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800793
Christopher Tate14a7bb02015-10-01 10:24:31 -0700794 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
795 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
796 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800797 mPendingIntent = pendingIntent;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700798 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -0700799 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700800 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700801 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700802 mBroadcastStats = (pendingIntent != null)
803 ? service.getStatsLocked(pendingIntent)
804 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700805 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -0800806 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700807 fs = new FilterStats(mBroadcastStats, mTag);
808 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -0800809 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700810 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -0800811 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800812 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800813 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800815
Adam Lesinski182f73f2013-12-05 16:48:06 -0800816 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -0800817 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700818 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800819
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700820 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800822 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 int numWakeup;
824 long startTime;
825 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -0800826
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700827 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800828 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700829 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800830 }
831 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700832
Adam Lesinski182f73f2013-12-05 16:48:06 -0800833 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800834 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800835 final String mPackageName;
836
837 long aggregateTime;
838 int count;
839 int numWakeup;
840 long startTime;
841 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700842 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -0800843
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800844 BroadcastStats(int uid, String packageName) {
845 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800846 mPackageName = packageName;
847 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700849
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800850 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
851 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700852
853 int mNumDelayedAlarms = 0;
854 long mTotalDelayTime = 0;
855 long mMaxDelayTime = 0;
856
Adam Lesinski182f73f2013-12-05 16:48:06 -0800857 @Override
858 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800859 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800860 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800861
862 // We have to set current TimeZone info to kernel
863 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -0800864 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800865
Adam Lesinski182f73f2013-12-05 16:48:06 -0800866 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800867 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800868
Adam Lesinski182f73f2013-12-05 16:48:06 -0800869 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700871 Intent.FLAG_RECEIVER_REGISTERED_ONLY
872 | Intent.FLAG_RECEIVER_FOREGROUND), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700873 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800874 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
875 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800876 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700877 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878
879 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -0800880 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 mClockReceiver.scheduleTimeTickEvent();
882 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700883 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884 mUninstallReceiver = new UninstallReceiver();
885
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800886 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800887 AlarmThread waitThread = new AlarmThread();
888 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800890 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800892
893 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800895
896 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -0700897 public void onBootPhase(int phase) {
898 if (phase == PHASE_SYSTEM_SERVICES_READY) {
899 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -0700900 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800901 mLocalDeviceIdleController
902 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackborna750a632015-06-16 17:18:23 -0700903 }
904 }
905
906 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 protected void finalize() throws Throwable {
908 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800909 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 } finally {
911 super.finalize();
912 }
913 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700914
Adam Lesinski182f73f2013-12-05 16:48:06 -0800915 void setTimeZoneImpl(String tz) {
916 if (TextUtils.isEmpty(tz)) {
917 return;
David Christieebe51fc2013-07-26 13:23:29 -0700918 }
919
Adam Lesinski182f73f2013-12-05 16:48:06 -0800920 TimeZone zone = TimeZone.getTimeZone(tz);
921 // Prevent reentrant calls from stepping on each other when writing
922 // the time zone property
923 boolean timeZoneWasChanged = false;
924 synchronized (this) {
925 String current = SystemProperties.get(TIMEZONE_PROPERTY);
926 if (current == null || !current.equals(zone.getID())) {
927 if (localLOGV) {
928 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
929 }
930 timeZoneWasChanged = true;
931 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
932 }
933
934 // Update the kernel timezone information
935 // Kernel tracks time offsets as 'minutes west of GMT'
936 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800937 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -0800938 }
939
940 TimeZone.setDefault(null);
941
942 if (timeZoneWasChanged) {
943 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
944 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
945 intent.putExtra("time-zone", zone.getID());
946 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
947 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700949
Adam Lesinski182f73f2013-12-05 16:48:06 -0800950 void removeImpl(PendingIntent operation) {
951 if (operation == null) {
952 return;
953 }
954 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700955 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800956 }
957 }
958
959 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -0700960 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
961 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
962 int callingUid, String callingPackage) {
963 // must be *either* PendingIntent or AlarmReceiver, but not both
964 if ((operation == null && directReceiver == null)
965 || (operation != null && directReceiver != null)) {
966 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
967 // NB: previous releases failed silently here, so we are continuing to do the same
968 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 return;
970 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700971
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700972 // Sanity check the window length. This will catch people mistakenly
973 // trying to pass an end-of-window timestamp rather than a duration.
974 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
975 Slog.w(TAG, "Window length " + windowLength
976 + "ms suspiciously long; limiting to 1 hour");
977 windowLength = AlarmManager.INTERVAL_HOUR;
978 }
979
Christopher Tate498c6cb2014-11-17 16:09:27 -0800980 // Sanity check the recurrence interval. This will catch people who supply
981 // seconds when the API expects milliseconds.
Dianne Hackborna750a632015-06-16 17:18:23 -0700982 final long minInterval = mConstants.MIN_INTERVAL;
983 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -0800984 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -0700985 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -0800986 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -0700987 interval = minInterval;
Christopher Tate498c6cb2014-11-17 16:09:27 -0800988 }
989
Christopher Tatee0a22b32013-07-11 14:43:13 -0700990 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
991 throw new IllegalArgumentException("Invalid alarm type " + type);
992 }
993
Christopher Tate5f221e82013-07-30 17:13:15 -0700994 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -0700995 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700996 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -0700997 + " pid=" + what);
998 triggerAtTime = 0;
999 }
1000
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001001 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001002 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1003 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001004 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001005 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1006
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001007 final long maxElapsed;
1008 if (windowLength == AlarmManager.WINDOW_EXACT) {
1009 maxElapsed = triggerElapsed;
1010 } else if (windowLength < 0) {
1011 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001012 // Fix this window in place, so that as time approaches we don't collapse it.
1013 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001014 } else {
1015 maxElapsed = triggerElapsed + windowLength;
1016 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001019 if (DEBUG_BATCH) {
1020 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001021 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001022 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001023 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001025 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001026 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1027 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 }
1029 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030
Christopher Tate3e04b472013-10-21 17:51:31 -07001031 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001032 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1033 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1034 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001035 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001036 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1037 callingUid, callingPackage);
1038 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001039 setImplLocked(a, false, doValidate);
1040 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001041
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001042 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1043 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001044 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001045 // The caller has given the time they want this to happen at, however we need
1046 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001047 // bring us out of idle at an earlier time.
1048 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001049 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001050 }
1051 // Add fuzz to make the alarm go off some time before the actual desired time.
1052 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001053 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001054 if (fuzz > 0) {
1055 if (mRandom == null) {
1056 mRandom = new Random();
1057 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001058 final int delta = mRandom.nextInt(fuzz);
1059 a.whenElapsed -= delta;
1060 if (false) {
1061 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1062 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1063 Slog.d(TAG, "Applied fuzz: " + fuzz);
1064 Slog.d(TAG, "Final delta: " + delta);
1065 Slog.d(TAG, "Final when: " + a.whenElapsed);
1066 }
1067 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001068 }
1069
1070 } else if (mPendingIdleUntil != null) {
1071 // We currently have an idle until alarm scheduled; if the new alarm has
1072 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001073 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1074 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1075 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001076 == 0) {
1077 mPendingWhileIdleAlarms.add(a);
1078 return;
1079 }
1080 }
1081
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001082 if (RECORD_DEVICE_IDLE_ALARMS) {
1083 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1084 IdleDispatchEntry ent = new IdleDispatchEntry();
1085 ent.uid = a.uid;
1086 ent.pkg = a.operation.getCreatorPackage();
1087 ent.tag = a.operation.getTag("");
1088 ent.op = "SET";
1089 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1090 ent.argRealtime = a.whenElapsed;
1091 mAllowWhileIdleDispatches.add(ent);
1092 }
1093 }
1094
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001095 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
1096 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -07001097 if (whichBatch < 0) {
1098 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001099 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 } else {
Christopher Tate385e4982013-07-23 18:22:29 -07001101 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001102 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001103 // The start time of this batch advanced, so batch ordering may
1104 // have just been broken. Move it to where it now belongs.
1105 mAlarmBatches.remove(whichBatch);
1106 addBatchLocked(mAlarmBatches, batch);
1107 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 }
1109
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001110 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001111 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001112 }
1113
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001114 boolean needRebatch = false;
1115
1116 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001117 if (RECORD_DEVICE_IDLE_ALARMS) {
1118 if (mPendingIdleUntil == null) {
1119 IdleDispatchEntry ent = new IdleDispatchEntry();
1120 ent.uid = 0;
1121 ent.pkg = "START IDLE";
1122 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1123 mAllowWhileIdleDispatches.add(ent);
1124 }
1125 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001126 mPendingIdleUntil = a;
Dianne Hackborna750a632015-06-16 17:18:23 -07001127 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001128 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001129 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1130 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1131 mNextWakeFromIdle = a;
1132 // If this wake from idle is earlier than whatever was previously scheduled,
1133 // and we are currently idling, then we need to rebatch alarms in case the idle
1134 // until time needs to be updated.
1135 if (mPendingIdleUntil != null) {
1136 needRebatch = true;
1137 }
1138 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001139 }
1140
1141 if (!rebatching) {
1142 if (DEBUG_VALIDATE) {
1143 if (doValidate && !validateConsistencyLocked()) {
1144 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1145 + " when(hex)=" + Long.toHexString(a.when)
1146 + " whenElapsed=" + a.whenElapsed
1147 + " maxWhenElapsed=" + a.maxWhenElapsed
1148 + " interval=" + a.repeatInterval + " op=" + a.operation
1149 + " flags=0x" + Integer.toHexString(a.flags));
1150 rebatchAllAlarmsLocked(false);
1151 needRebatch = false;
1152 }
1153 }
1154
1155 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001156 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001157 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001158
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001159 rescheduleKernelAlarmsLocked();
1160 updateNextAlarmClockLocked();
1161 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001162 }
1163
Adam Lesinski182f73f2013-12-05 16:48:06 -08001164 private final IBinder mService = new IAlarmManager.Stub() {
1165 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001166 public void set(String callingPackage,
1167 int type, long triggerAtTime, long windowLength, long interval, int flags,
1168 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1169 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001170 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001171
1172 // make sure the caller is not lying about which package should be blamed for
1173 // wakelock time spent in alarm delivery
1174 mAppOps.checkPackage(callingUid, callingPackage);
1175
1176 // Repeating alarms must use PendingIntent, not direct listener
1177 if (interval != 0) {
1178 if (directReceiver != null) {
1179 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1180 }
1181 }
1182
1183 // direct-callback alarms must be wakeup alarms (otherwise they should just be
1184 // posting work to a Handler)
1185 if (directReceiver != null) {
1186 if (type != RTC_WAKEUP && type != ELAPSED_REALTIME_WAKEUP) {
1187 throw new IllegalArgumentException("Only wakeup alarms can use AlarmReceivers");
1188 }
1189 }
1190
Adam Lesinski182f73f2013-12-05 16:48:06 -08001191 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001192 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001193 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001194 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001195 }
1196
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001197 // No incoming callers can request either WAKE_FROM_IDLE or
1198 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1199 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1200 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1201
1202 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1203 // manager when to come out of idle mode, which is only for DeviceIdleController.
1204 if (callingUid != Process.SYSTEM_UID) {
1205 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1206 }
1207
1208 // If the caller is a core system component, and not calling to do work on behalf
1209 // of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED. This means we
1210 // will allow these alarms to go off as normal even while idle, with no timing
1211 // restrictions.
1212 if (callingUid < Process.FIRST_APPLICATION_UID && workSource == null) {
1213 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1214 }
1215
1216 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001217 if (windowLength == AlarmManager.WINDOW_EXACT) {
1218 flags |= AlarmManager.FLAG_STANDALONE;
1219 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001220
1221 // If this alarm is for an alarm clock, then it must be standalone and we will
1222 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001223 if (alarmClock != null) {
1224 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
1225 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001226
Christopher Tate14a7bb02015-10-01 10:24:31 -07001227 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1228 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001229 }
Christopher Tate89779822012-08-31 14:40:03 -07001230
Adam Lesinski182f73f2013-12-05 16:48:06 -08001231 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001232 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001233 getContext().enforceCallingOrSelfPermission(
1234 "android.permission.SET_TIME",
1235 "setTime");
1236
Greg Hackmann0cab8962014-02-21 16:35:52 -08001237 if (mNativeData == 0) {
1238 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1239 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001240 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001241
1242 synchronized (mLock) {
1243 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001246
1247 @Override
1248 public void setTimeZone(String tz) {
1249 getContext().enforceCallingOrSelfPermission(
1250 "android.permission.SET_TIME_ZONE",
1251 "setTimeZone");
1252
1253 final long oldId = Binder.clearCallingIdentity();
1254 try {
1255 setTimeZoneImpl(tz);
1256 } finally {
1257 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001258 }
1259 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001260
Adam Lesinski182f73f2013-12-05 16:48:06 -08001261 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001262 public void remove(PendingIntent operation, IAlarmListener listener) {
1263 if (operation == null && listener == null) {
1264 Slog.w(TAG, "remove() with no intent or listener");
1265 return;
1266 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001267
Christopher Tate14a7bb02015-10-01 10:24:31 -07001268 synchronized (mLock) {
1269 removeLocked(operation, listener);
1270 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001272
Adam Lesinski182f73f2013-12-05 16:48:06 -08001273 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001274 public long getNextWakeFromIdleTime() {
1275 return getNextWakeFromIdleTimeImpl();
1276 }
1277
1278 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001279 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001280 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1281 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1282 "getNextAlarmClock", null);
1283
1284 return getNextAlarmClockImpl(userId);
1285 }
1286
1287 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001288 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1289 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1290 != PackageManager.PERMISSION_GRANTED) {
1291 pw.println("Permission Denial: can't dump AlarmManager from from pid="
1292 + Binder.getCallingPid()
1293 + ", uid=" + Binder.getCallingUid());
1294 return;
Christopher Tate4cb338d2013-07-26 13:11:31 -07001295 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001296
Adam Lesinski182f73f2013-12-05 16:48:06 -08001297 dumpImpl(pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001298 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001299 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001300
Adam Lesinski182f73f2013-12-05 16:48:06 -08001301 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 synchronized (mLock) {
1303 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001304 mConstants.dump(pw);
1305 pw.println();
1306
Christopher Tatee0a22b32013-07-11 14:43:13 -07001307 final long nowRTC = System.currentTimeMillis();
1308 final long nowELAPSED = SystemClock.elapsedRealtime();
1309 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1310
Dianne Hackborna750a632015-06-16 17:18:23 -07001311 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001312 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001313 pw.print(" nowELAPSED="); TimeUtils.formatDuration(nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001314 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001315 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001316 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001317 pw.print(" mLastTimeChangeRealtime=");
Dianne Hackbornc3527222015-05-13 14:03:20 -07001318 TimeUtils.formatDuration(mLastTimeChangeRealtime, pw);
1319 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001320 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001321 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001322 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1323 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001324 pw.print(" Max wakeup delay: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001325 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1326 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001327 pw.print(" Time since last dispatch: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001328 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1329 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001330 pw.print(" Next non-wakeup delivery time: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001331 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1332 pw.println();
1333 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001334
1335 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1336 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001337 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001338 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001339 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001340 pw.print(" Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001341 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001342 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001343
John Spurlock604a5ee2015-06-01 12:27:22 -04001344 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001345 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001346 final TreeSet<Integer> users = new TreeSet<>();
1347 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1348 users.add(mNextAlarmClockForUser.keyAt(i));
1349 }
1350 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1351 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1352 }
1353 for (int user : users) {
1354 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1355 final long time = next != null ? next.getTriggerTime() : 0;
1356 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001357 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001358 pw.print(" pendingSend:"); pw.print(pendingSend);
1359 pw.print(" time:"); pw.print(time);
1360 if (time > 0) {
1361 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1362 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1363 }
1364 pw.println();
1365 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001366 if (mAlarmBatches.size() > 0) {
1367 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001368 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001369 pw.println(mAlarmBatches.size());
1370 for (Batch b : mAlarmBatches) {
1371 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001372 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001373 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001375 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001376 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001377 pw.println(" Idle mode state:");
1378 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001379 if (mPendingIdleUntil != null) {
1380 pw.println(mPendingIdleUntil);
Dianne Hackbornf3831292015-10-15 14:51:06 -07001381 mPendingIdleUntil.dump(pw, " ", nowRTC, nowELAPSED, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001382 } else {
1383 pw.println("null");
1384 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001385 pw.println(" Pending alarms:");
1386 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001387 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001388 if (mNextWakeFromIdle != null) {
1389 pw.println();
1390 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
1391 mNextWakeFromIdle.dump(pw, " ", nowRTC, nowELAPSED, sdf);
1392 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001393
1394 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001395 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001396 if (mPendingNonWakeupAlarms.size() > 0) {
1397 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001398 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001399 } else {
1400 pw.println("(none)");
1401 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001402 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001403 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1404 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001405 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001406 pw.print(", max non-interactive time: ");
1407 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1408 pw.println();
1409
1410 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001411 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001412 pw.println();
1413
Dianne Hackborna750a632015-06-16 17:18:23 -07001414 pw.print(" mAllowWhileIdleMinTime=");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001415 TimeUtils.formatDuration(mAllowWhileIdleMinTime, pw);
1416 pw.println();
1417 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001418 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001419 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
1420 pw.print(" UID ");
1421 UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
1422 pw.print(": ");
1423 TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i),
1424 nowELAPSED, pw);
1425 pw.println();
1426 }
1427 }
1428 pw.println();
1429
Dianne Hackborn81038902012-11-26 17:04:09 -08001430 if (mLog.dump(pw, " Recent problems", " ")) {
1431 pw.println();
1432 }
1433
1434 final FilterStats[] topFilters = new FilterStats[10];
1435 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1436 @Override
1437 public int compare(FilterStats lhs, FilterStats rhs) {
1438 if (lhs.aggregateTime < rhs.aggregateTime) {
1439 return 1;
1440 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1441 return -1;
1442 }
1443 return 0;
1444 }
1445 };
1446 int len = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001447 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1448 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1449 for (int ip=0; ip<uidStats.size(); ip++) {
1450 BroadcastStats bs = uidStats.valueAt(ip);
1451 for (int is=0; is<bs.filterStats.size(); is++) {
1452 FilterStats fs = bs.filterStats.valueAt(is);
1453 int pos = len > 0
1454 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1455 if (pos < 0) {
1456 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001457 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001458 if (pos < topFilters.length) {
1459 int copylen = topFilters.length - pos - 1;
1460 if (copylen > 0) {
1461 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1462 }
1463 topFilters[pos] = fs;
1464 if (len < topFilters.length) {
1465 len++;
1466 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001467 }
1468 }
1469 }
1470 }
1471 if (len > 0) {
1472 pw.println(" Top Alarms:");
1473 for (int i=0; i<len; i++) {
1474 FilterStats fs = topFilters[i];
1475 pw.print(" ");
1476 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1477 TimeUtils.formatDuration(fs.aggregateTime, pw);
1478 pw.print(" running, "); pw.print(fs.numWakeup);
1479 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001480 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1481 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001482 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001483 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001484 pw.println();
1485 }
1486 }
1487
1488 pw.println(" ");
1489 pw.println(" Alarm Stats:");
1490 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001491 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1492 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1493 for (int ip=0; ip<uidStats.size(); ip++) {
1494 BroadcastStats bs = uidStats.valueAt(ip);
1495 pw.print(" ");
1496 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1497 UserHandle.formatUid(pw, bs.mUid);
1498 pw.print(":");
1499 pw.print(bs.mPackageName);
1500 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1501 pw.print(" running, "); pw.print(bs.numWakeup);
1502 pw.println(" wakeups:");
1503 tmpFilters.clear();
1504 for (int is=0; is<bs.filterStats.size(); is++) {
1505 tmpFilters.add(bs.filterStats.valueAt(is));
1506 }
1507 Collections.sort(tmpFilters, comparator);
1508 for (int i=0; i<tmpFilters.size(); i++) {
1509 FilterStats fs = tmpFilters.get(i);
1510 pw.print(" ");
1511 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1512 TimeUtils.formatDuration(fs.aggregateTime, pw);
1513 pw.print(" "); pw.print(fs.numWakeup);
1514 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001515 pw.print(" alarms, last ");
1516 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1517 pw.println(":");
1518 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001519 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001520 pw.println();
1521 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 }
1523 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001524
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001525 if (RECORD_DEVICE_IDLE_ALARMS) {
1526 pw.println();
1527 pw.println(" Allow while idle dispatches:");
1528 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
1529 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
1530 pw.print(" ");
1531 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
1532 pw.print(": ");
1533 UserHandle.formatUid(pw, ent.uid);
1534 pw.print(":");
1535 pw.println(ent.pkg);
1536 if (ent.op != null) {
1537 pw.print(" ");
1538 pw.print(ent.op);
1539 pw.print(" / ");
1540 pw.print(ent.tag);
1541 if (ent.argRealtime != 0) {
1542 pw.print(" (");
1543 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
1544 pw.print(")");
1545 }
1546 pw.println();
1547 }
1548 }
1549 }
1550
Christopher Tate18a75f12013-07-01 18:18:59 -07001551 if (WAKEUP_STATS) {
1552 pw.println();
1553 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001554 long last = -1;
1555 for (WakeupEvent event : mRecentWakeups) {
1556 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1557 pw.print('|');
1558 if (last < 0) {
1559 pw.print('0');
1560 } else {
1561 pw.print(event.when - last);
1562 }
1563 last = event.when;
1564 pw.print('|'); pw.print(event.uid);
1565 pw.print('|'); pw.print(event.action);
1566 pw.println();
1567 }
1568 pw.println();
1569 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 }
1571 }
1572
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001573 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001574 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
1575 PrintWriter pw = new PrintWriter(bs);
1576 final long nowRTC = System.currentTimeMillis();
1577 final long nowELAPSED = SystemClock.elapsedRealtime();
1578 final int NZ = mAlarmBatches.size();
1579 for (int iz = 0; iz < NZ; iz++) {
1580 Batch bz = mAlarmBatches.get(iz);
1581 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001582 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001583 pw.flush();
1584 Slog.v(TAG, bs.toString());
1585 bs.reset();
1586 }
1587 }
1588
1589 private boolean validateConsistencyLocked() {
1590 if (DEBUG_VALIDATE) {
1591 long lastTime = Long.MIN_VALUE;
1592 final int N = mAlarmBatches.size();
1593 for (int i = 0; i < N; i++) {
1594 Batch b = mAlarmBatches.get(i);
1595 if (b.start >= lastTime) {
1596 // duplicate start times are okay because of standalone batches
1597 lastTime = b.start;
1598 } else {
1599 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001600 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1601 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001602 return false;
1603 }
1604 }
1605 }
1606 return true;
1607 }
1608
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001609 private Batch findFirstWakeupBatchLocked() {
1610 final int N = mAlarmBatches.size();
1611 for (int i = 0; i < N; i++) {
1612 Batch b = mAlarmBatches.get(i);
1613 if (b.hasWakeups()) {
1614 return b;
1615 }
1616 }
1617 return null;
1618 }
1619
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001620 long getNextWakeFromIdleTimeImpl() {
1621 synchronized (mLock) {
1622 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
1623 }
1624 }
1625
1626 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001627 synchronized (mLock) {
1628 return mNextAlarmClockForUser.get(userId);
1629 }
1630 }
1631
1632 /**
1633 * Recomputes the next alarm clock for all users.
1634 */
1635 private void updateNextAlarmClockLocked() {
1636 if (!mNextAlarmClockMayChange) {
1637 return;
1638 }
1639 mNextAlarmClockMayChange = false;
1640
Jose Lima235510e2014-08-13 12:50:01 -07001641 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001642 nextForUser.clear();
1643
1644 final int N = mAlarmBatches.size();
1645 for (int i = 0; i < N; i++) {
1646 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
1647 final int M = alarms.size();
1648
1649 for (int j = 0; j < M; j++) {
1650 Alarm a = alarms.get(j);
1651 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001652 final int userId = UserHandle.getUserId(a.uid);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001653
1654 if (DEBUG_ALARM_CLOCK) {
1655 Log.v(TAG, "Found AlarmClockInfo at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001656 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02001657 " for user " + userId);
1658 }
1659
1660 // Alarms and batches are sorted by time, no need to compare times here.
1661 if (nextForUser.get(userId) == null) {
1662 nextForUser.put(userId, a.alarmClock);
1663 }
1664 }
1665 }
1666 }
1667
1668 // Update mNextAlarmForUser with new values.
1669 final int NN = nextForUser.size();
1670 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07001671 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001672 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001673 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001674 if (!newAlarm.equals(currentAlarm)) {
1675 updateNextAlarmInfoForUserLocked(userId, newAlarm);
1676 }
1677 }
1678
1679 // Remove users without any alarm clocks scheduled.
1680 final int NNN = mNextAlarmClockForUser.size();
1681 for (int i = NNN - 1; i >= 0; i--) {
1682 int userId = mNextAlarmClockForUser.keyAt(i);
1683 if (nextForUser.get(userId) == null) {
1684 updateNextAlarmInfoForUserLocked(userId, null);
1685 }
1686 }
1687 }
1688
Jose Lima235510e2014-08-13 12:50:01 -07001689 private void updateNextAlarmInfoForUserLocked(int userId,
1690 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001691 if (alarmClock != null) {
1692 if (DEBUG_ALARM_CLOCK) {
1693 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001694 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02001695 }
1696 mNextAlarmClockForUser.put(userId, alarmClock);
1697 } else {
1698 if (DEBUG_ALARM_CLOCK) {
1699 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
1700 }
1701 mNextAlarmClockForUser.remove(userId);
1702 }
1703
1704 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
1705 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1706 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1707 }
1708
1709 /**
1710 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
1711 * for which alarm clocks have changed since the last call to this.
1712 *
1713 * Do not call with a lock held. Only call from mHandler's thread.
1714 *
1715 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
1716 */
1717 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07001718 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001719 pendingUsers.clear();
1720
1721 synchronized (mLock) {
1722 final int N = mPendingSendNextAlarmClockChangedForUser.size();
1723 for (int i = 0; i < N; i++) {
1724 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
1725 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
1726 }
1727 mPendingSendNextAlarmClockChangedForUser.clear();
1728 }
1729
1730 final int N = pendingUsers.size();
1731 for (int i = 0; i < N; i++) {
1732 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001733 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001734 Settings.System.putStringForUser(getContext().getContentResolver(),
1735 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01001736 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02001737 userId);
1738
1739 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
1740 new UserHandle(userId));
1741 }
1742 }
1743
1744 /**
1745 * Formats an alarm like platform/packages/apps/DeskClock used to.
1746 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01001747 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
1748 int userId) {
1749 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02001750 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
1751 return (info == null) ? "" :
1752 DateFormat.format(pattern, info.getTriggerTime()).toString();
1753 }
1754
Adam Lesinski182f73f2013-12-05 16:48:06 -08001755 void rescheduleKernelAlarmsLocked() {
1756 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
1757 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001758 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001759 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001760 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001761 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07001762 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001763 mNextWakeup = firstWakeup.start;
1764 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001765 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001766 if (firstBatch != firstWakeup) {
1767 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001768 }
1769 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001770 if (mPendingNonWakeupAlarms.size() > 0) {
1771 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
1772 nextNonWakeup = mNextNonWakeupDeliveryTime;
1773 }
1774 }
Prashant Malani753e9e02015-06-10 17:43:49 -07001775 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001776 mNextNonWakeup = nextNonWakeup;
1777 setLocked(ELAPSED_REALTIME, nextNonWakeup);
1778 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001779 }
1780
Christopher Tate14a7bb02015-10-01 10:24:31 -07001781 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001782 boolean didRemove = false;
1783 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1784 Batch b = mAlarmBatches.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -07001785 didRemove |= b.remove(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001786 if (b.size() == 0) {
1787 mAlarmBatches.remove(i);
1788 }
1789 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001790 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001791 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001792 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1793 mPendingWhileIdleAlarms.remove(i);
1794 }
1795 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001796
1797 if (didRemove) {
1798 if (DEBUG_BATCH) {
1799 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
1800 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001801 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001802 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001803 mPendingIdleUntil = null;
1804 restorePending = true;
1805 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001806 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001807 mNextWakeFromIdle = null;
1808 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001809 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001810 if (restorePending) {
1811 restorePendingWhileIdleAlarmsLocked();
1812 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001813 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001814 }
1815 }
1816
1817 void removeLocked(String packageName) {
1818 boolean didRemove = false;
1819 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1820 Batch b = mAlarmBatches.get(i);
1821 didRemove |= b.remove(packageName);
1822 if (b.size() == 0) {
1823 mAlarmBatches.remove(i);
1824 }
1825 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001826 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001827 final Alarm a = mPendingWhileIdleAlarms.get(i);
1828 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001829 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1830 mPendingWhileIdleAlarms.remove(i);
1831 }
1832 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001833
1834 if (didRemove) {
1835 if (DEBUG_BATCH) {
1836 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1837 }
1838 rebatchAllAlarmsLocked(true);
1839 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001840 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001841 }
1842 }
1843
1844 void removeUserLocked(int userHandle) {
1845 boolean didRemove = false;
1846 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1847 Batch b = mAlarmBatches.get(i);
1848 didRemove |= b.remove(userHandle);
1849 if (b.size() == 0) {
1850 mAlarmBatches.remove(i);
1851 }
1852 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001853 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001854 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001855 == userHandle) {
1856 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1857 mPendingWhileIdleAlarms.remove(i);
1858 }
1859 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001860 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
1861 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
1862 mLastAllowWhileIdleDispatch.removeAt(i);
1863 }
1864 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001865
1866 if (didRemove) {
1867 if (DEBUG_BATCH) {
1868 Slog.v(TAG, "remove(user) changed bounds; rebatching");
1869 }
1870 rebatchAllAlarmsLocked(true);
1871 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001872 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001873 }
1874 }
1875
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001876 void interactiveStateChangedLocked(boolean interactive) {
1877 if (mInteractive != interactive) {
1878 mInteractive = interactive;
1879 final long nowELAPSED = SystemClock.elapsedRealtime();
1880 if (interactive) {
1881 if (mPendingNonWakeupAlarms.size() > 0) {
1882 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1883 mTotalDelayTime += thisDelayTime;
1884 if (mMaxDelayTime < thisDelayTime) {
1885 mMaxDelayTime = thisDelayTime;
1886 }
1887 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
1888 mPendingNonWakeupAlarms.clear();
1889 }
1890 if (mNonInteractiveStartTime > 0) {
1891 long dur = nowELAPSED - mNonInteractiveStartTime;
1892 if (dur > mNonInteractiveTime) {
1893 mNonInteractiveTime = dur;
1894 }
1895 }
1896 } else {
1897 mNonInteractiveStartTime = nowELAPSED;
1898 }
1899 }
1900 }
1901
Adam Lesinski182f73f2013-12-05 16:48:06 -08001902 boolean lookForPackageLocked(String packageName) {
1903 for (int i = 0; i < mAlarmBatches.size(); i++) {
1904 Batch b = mAlarmBatches.get(i);
1905 if (b.hasPackage(packageName)) {
1906 return true;
1907 }
1908 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001909 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001910 final Alarm a = mPendingWhileIdleAlarms.get(i);
1911 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001912 return true;
1913 }
1914 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001915 return false;
1916 }
1917
1918 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001919 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001920 // The kernel never triggers alarms with negative wakeup times
1921 // so we ensure they are positive.
1922 long alarmSeconds, alarmNanoseconds;
1923 if (when < 0) {
1924 alarmSeconds = 0;
1925 alarmNanoseconds = 0;
1926 } else {
1927 alarmSeconds = when / 1000;
1928 alarmNanoseconds = (when % 1000) * 1000 * 1000;
1929 }
1930
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001931 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001932 } else {
1933 Message msg = Message.obtain();
1934 msg.what = ALARM_EVENT;
1935
1936 mHandler.removeMessages(ALARM_EVENT);
1937 mHandler.sendMessageAtTime(msg, when);
1938 }
1939 }
1940
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001941 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001942 String prefix, String label, long nowRTC, long nowELAPSED, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 for (int i=list.size()-1; i>=0; i--) {
1944 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001945 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1946 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001947 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 }
1949 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001950
1951 private static final String labelForType(int type) {
1952 switch (type) {
1953 case RTC: return "RTC";
1954 case RTC_WAKEUP : return "RTC_WAKEUP";
1955 case ELAPSED_REALTIME : return "ELAPSED";
1956 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
1957 default:
1958 break;
1959 }
1960 return "--unknown--";
1961 }
1962
1963 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001964 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001965 for (int i=list.size()-1; i>=0; i--) {
1966 Alarm a = list.get(i);
1967 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001968 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1969 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001970 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001971 }
1972 }
1973
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001974 private native long init();
1975 private native void close(long nativeData);
1976 private native void set(long nativeData, int type, long seconds, long nanoseconds);
1977 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08001978 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001979 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001981 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001982 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001983 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001984 // batches are temporally sorted, so we need only pull from the
1985 // start of the list until we either empty it or hit a batch
1986 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07001987 while (mAlarmBatches.size() > 0) {
1988 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001989 if (batch.start > nowELAPSED) {
1990 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001991 break;
1992 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993
Christopher Tatee0a22b32013-07-11 14:43:13 -07001994 // We will (re)schedule some alarms now; don't let that interfere
1995 // with delivery of this current batch
1996 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001997
Christopher Tatee0a22b32013-07-11 14:43:13 -07001998 final int N = batch.size();
1999 for (int i = 0; i < N; i++) {
2000 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002001
2002 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
2003 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
2004 // schedule such alarms.
2005 long lastTime = mLastAllowWhileIdleDispatch.get(alarm.uid, 0);
2006 long minTime = lastTime + mAllowWhileIdleMinTime;
2007 if (nowELAPSED < minTime) {
2008 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
2009 // alarm went off for this app. Reschedule the alarm to be in the
2010 // correct time period.
2011 alarm.whenElapsed = minTime;
2012 if (alarm.maxWhenElapsed < minTime) {
2013 alarm.maxWhenElapsed = minTime;
2014 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002015 if (RECORD_DEVICE_IDLE_ALARMS) {
2016 IdleDispatchEntry ent = new IdleDispatchEntry();
2017 ent.uid = alarm.uid;
2018 ent.pkg = alarm.operation.getCreatorPackage();
2019 ent.tag = alarm.operation.getTag("");
2020 ent.op = "RESCHEDULE";
2021 ent.elapsedRealtime = nowELAPSED;
2022 ent.argRealtime = lastTime;
2023 mAllowWhileIdleDispatches.add(ent);
2024 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002025 setImplLocked(alarm, true, false);
2026 continue;
2027 }
2028 }
2029
Christopher Tatee0a22b32013-07-11 14:43:13 -07002030 alarm.count = 1;
2031 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002032 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
2033 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002034 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002035 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002036 if (mPendingIdleUntil == alarm) {
2037 mPendingIdleUntil = null;
2038 rebatchAllAlarmsLocked(false);
2039 restorePendingWhileIdleAlarmsLocked();
2040 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002041 if (mNextWakeFromIdle == alarm) {
2042 mNextWakeFromIdle = null;
2043 rebatchAllAlarmsLocked(false);
2044 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002045
2046 // Recurring alarms may have passed several alarm intervals while the
2047 // phone was asleep or off, so pass a trigger count when sending them.
2048 if (alarm.repeatInterval > 0) {
2049 // this adjustment will be zero if we're late by
2050 // less than one full repeat interval
2051 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
2052
2053 // Also schedule its next recurrence
2054 final long delta = alarm.count * alarm.repeatInterval;
2055 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07002056 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07002057 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07002058 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
2059 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08002060 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002061
Christopher Tate864d42e2014-12-02 11:48:53 -08002062 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002063 hasWakeup = true;
2064 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002065
2066 // We removed an alarm clock. Let the caller recompute the next alarm clock.
2067 if (alarm.alarmClock != null) {
2068 mNextAlarmClockMayChange = true;
2069 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07002070 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002072
Christopher Tate1590f1e2014-10-02 17:27:57 -07002073 // This is a new alarm delivery set; bump the sequence number to indicate that
2074 // all apps' alarm delivery classes should be recalculated.
2075 mCurrentSeq++;
2076 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002077 Collections.sort(triggerList, mAlarmDispatchComparator);
2078
2079 if (localLOGV) {
2080 for (int i=0; i<triggerList.size(); i++) {
2081 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
2082 }
2083 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002084
2085 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002086 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 /**
2089 * This Comparator sorts Alarms into increasing time order.
2090 */
2091 public static class IncreasingTimeOrder implements Comparator<Alarm> {
2092 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09002093 long when1 = a1.whenElapsed;
2094 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002095 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002096 return 1;
2097 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002098 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002099 return -1;
2100 }
2101 return 0;
2102 }
2103 }
2104
2105 private static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002106 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002107 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002108 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002109 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002110 public final IAlarmListener listener;
2111 public final String listenerTag;
2112 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002113 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002114 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002115 public final AlarmManager.AlarmClockInfo alarmClock;
2116 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002117 public final int creatorUid;
2118 public final String packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002119 public int count;
2120 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07002121 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002122 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002123 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002124 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07002125 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002126
Christopher Tate3e04b472013-10-21 17:51:31 -07002127 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002128 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
2129 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
2130 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002131 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002132 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002133 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
2134 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002135 when = _when;
2136 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07002137 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002138 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002139 repeatInterval = _interval;
2140 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002141 listener = _rec;
2142 listenerTag = _listenerTag;
2143 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07002144 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002145 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002146 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002147 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002148 packageName = _pkgName;
2149
2150 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002151 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002152
Christopher Tate14a7bb02015-10-01 10:24:31 -07002153 public static String makeTag(PendingIntent pi, String tag, int type) {
2154 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
2155 ? "*walarm*:" : "*alarm*:";
2156 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
2157 }
2158
2159 public WakeupEvent makeWakeupEvent(long nowRTC) {
2160 return new WakeupEvent(nowRTC, creatorUid,
2161 (operation != null)
2162 ? operation.getIntent().getAction()
2163 : ("<listener>:" + listenerTag));
2164 }
2165
2166 // Returns true if either matches
2167 public boolean matches(PendingIntent pi, IAlarmListener rec) {
2168 return (operation != null)
2169 ? operation.equals(pi)
2170 : listener.asBinder().equals(rec.asBinder());
2171 }
2172
2173 public boolean matches(String packageName) {
2174 return (operation != null)
2175 ? packageName.equals(operation.getTargetPackage())
2176 : packageName.equals(this.packageName);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002177 }
2178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002179 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002180 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002181 StringBuilder sb = new StringBuilder(128);
2182 sb.append("Alarm{");
2183 sb.append(Integer.toHexString(System.identityHashCode(this)));
2184 sb.append(" type ");
2185 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002186 sb.append(" when ");
2187 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002188 sb.append(" ");
Christopher Tate14a7bb02015-10-01 10:24:31 -07002189 if (operation != null) {
2190 sb.append(operation.getTargetPackage());
2191 } else {
2192 sb.append(listener.asBinder().toString());
2193 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002194 sb.append('}');
2195 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002196 }
2197
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002198 public void dump(PrintWriter pw, String prefix, long nowRTC, long nowELAPSED,
2199 SimpleDateFormat sdf) {
2200 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002201 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002202 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002203 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
2204 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002205 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002206 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002207 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002208 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002209 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002210 }
2211 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002212 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002213 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002214 pw.print(" count="); pw.print(count);
2215 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002216 if (alarmClock != null) {
2217 pw.print(prefix); pw.println("Alarm clock:");
2218 pw.print(prefix); pw.print(" triggerTime=");
2219 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
2220 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
2221 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002222 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002223 if (listener != null) {
2224 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
2225 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002226 }
2227 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002228
Christopher Tatee0a22b32013-07-11 14:43:13 -07002229 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
2230 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002231 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
2232 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002233 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07002234 break;
2235 }
2236
Christopher Tatee0a22b32013-07-11 14:43:13 -07002237 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002238 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
2239 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002240 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07002241 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002242 }
2243 }
2244
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002245 long currentNonWakeupFuzzLocked(long nowELAPSED) {
2246 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
2247 if (timeSinceOn < 5*60*1000) {
2248 // If the screen has been off for 5 minutes, only delay by at most two minutes.
2249 return 2*60*1000;
2250 } else if (timeSinceOn < 30*60*1000) {
2251 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
2252 return 15*60*1000;
2253 } else {
2254 // Otherwise, we will delay by at most an hour.
2255 return 60*60*1000;
2256 }
2257 }
2258
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002259 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002260 if (duration < 15*60*1000) {
2261 // If the duration until the time is less than 15 minutes, the maximum fuzz
2262 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002263 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002264 } else if (duration < 90*60*1000) {
2265 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
2266 return 15*60*1000;
2267 } else {
2268 // Otherwise, we will fuzz by at most half an hour.
2269 return 30*60*1000;
2270 }
2271 }
2272
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002273 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
2274 if (mInteractive) {
2275 return false;
2276 }
2277 if (mLastAlarmDeliveryTime <= 0) {
2278 return false;
2279 }
minho.choo649acab2014-12-12 16:13:55 +09002280 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002281 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
2282 // and the next delivery time is in the past, then just deliver them all. This
2283 // avoids bugs where we get stuck in a loop trying to poll for alarms.
2284 return false;
2285 }
2286 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
2287 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
2288 }
2289
2290 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
2291 mLastAlarmDeliveryTime = nowELAPSED;
2292 for (int i=0; i<triggerList.size(); i++) {
2293 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07002294 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002295 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07002296 if (localLOGV) {
2297 Slog.v(TAG, "sending alarm " + alarm);
2298 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07002299 if (RECORD_ALARMS_IN_HISTORY) {
2300 if (alarm.workSource != null && alarm.workSource.size() > 0) {
2301 for (int wi=0; wi<alarm.workSource.size(); wi++) {
2302 ActivityManagerNative.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002303 alarm.operation, alarm.workSource.get(wi), alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002304 }
2305 } else {
2306 ActivityManagerNative.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002307 alarm.operation, alarm.uid, alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002308 }
2309 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002310 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002311 } catch (RuntimeException e) {
2312 Slog.w(TAG, "Failure sending alarm.", e);
2313 }
2314 }
2315 }
2316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002317 private class AlarmThread extends Thread
2318 {
2319 public AlarmThread()
2320 {
2321 super("AlarmManager");
2322 }
2323
2324 public void run()
2325 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002326 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2327
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002328 while (true)
2329 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002330 int result = waitForAlarm(mNativeData);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002331
2332 triggerList.clear();
2333
Dianne Hackbornc3527222015-05-13 14:03:20 -07002334 final long nowRTC = System.currentTimeMillis();
2335 final long nowELAPSED = SystemClock.elapsedRealtime();
2336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002337 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002338 // The kernel can give us spurious time change notifications due to
2339 // small adjustments it makes internally; we want to filter those out.
2340 final long lastTimeChangeClockTime;
2341 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07002342 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002343 lastTimeChangeClockTime = mLastTimeChangeClockTime;
2344 expectedClockTime = lastTimeChangeClockTime
2345 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07002346 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002347 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-500)
2348 || nowRTC > (expectedClockTime+500)) {
2349 // The change is by at least +/- 500 ms (or this is the first change),
2350 // let's do it!
2351 if (DEBUG_BATCH) {
2352 Slog.v(TAG, "Time changed notification from kernel; rebatching");
2353 }
2354 removeImpl(mTimeTickSender);
2355 rebatchAllAlarms();
2356 mClockReceiver.scheduleTimeTickEvent();
2357 synchronized (mLock) {
2358 mNumTimeChanged++;
2359 mLastTimeChangeClockTime = nowRTC;
2360 mLastTimeChangeRealtime = nowELAPSED;
2361 }
2362 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
2363 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
2364 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2365 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
2366
2367 // The world has changed on us, so we need to re-evaluate alarms
2368 // regardless of whether the kernel has told us one went off.
2369 result |= IS_WAKEUP_MASK;
2370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002371 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002372
Dianne Hackbornc3527222015-05-13 14:03:20 -07002373 if (result != TIME_CHANGED_MASK) {
2374 // If this was anything besides just a time change, then figure what if
2375 // anything to do about alarms.
2376 synchronized (mLock) {
2377 if (localLOGV) Slog.v(
2378 TAG, "Checking for alarms... rtc=" + nowRTC
2379 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07002380
Dianne Hackbornc3527222015-05-13 14:03:20 -07002381 if (WAKEUP_STATS) {
2382 if ((result & IS_WAKEUP_MASK) != 0) {
2383 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
2384 int n = 0;
2385 for (WakeupEvent event : mRecentWakeups) {
2386 if (event.when > newEarliest) break;
2387 n++; // number of now-stale entries at the list head
2388 }
2389 for (int i = 0; i < n; i++) {
2390 mRecentWakeups.remove();
2391 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002392
Dianne Hackbornc3527222015-05-13 14:03:20 -07002393 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002394 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002395 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002396
2397 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2398 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
2399 // if there are no wakeup alarms and the screen is off, we can
2400 // delay what we have so far until the future.
2401 if (mPendingNonWakeupAlarms.size() == 0) {
2402 mStartCurrentDelayTime = nowELAPSED;
2403 mNextNonWakeupDeliveryTime = nowELAPSED
2404 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
2405 }
2406 mPendingNonWakeupAlarms.addAll(triggerList);
2407 mNumDelayedAlarms += triggerList.size();
2408 rescheduleKernelAlarmsLocked();
2409 updateNextAlarmClockLocked();
2410 } else {
2411 // now deliver the alarm intents; if there are pending non-wakeup
2412 // alarms, we need to merge them in to the list. note we don't
2413 // just deliver them first because we generally want non-wakeup
2414 // alarms delivered after wakeup alarms.
2415 rescheduleKernelAlarmsLocked();
2416 updateNextAlarmClockLocked();
2417 if (mPendingNonWakeupAlarms.size() > 0) {
2418 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
2419 triggerList.addAll(mPendingNonWakeupAlarms);
2420 Collections.sort(triggerList, mAlarmDispatchComparator);
2421 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2422 mTotalDelayTime += thisDelayTime;
2423 if (mMaxDelayTime < thisDelayTime) {
2424 mMaxDelayTime = thisDelayTime;
2425 }
2426 mPendingNonWakeupAlarms.clear();
2427 }
2428 deliverAlarmsLocked(triggerList, nowELAPSED);
2429 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430 }
2431 }
2432 }
2433 }
2434 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002435
David Christieebe51fc2013-07-26 13:23:29 -07002436 /**
2437 * Attribute blame for a WakeLock.
2438 * @param pi PendingIntent to attribute blame to if ws is null.
2439 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002440 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07002441 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002442 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002443 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07002444 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002445 final boolean unimportant = pi == mTimeTickSender;
2446 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002447 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002448 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002449 } else {
2450 mWakeLock.setHistoryTag(null);
2451 }
2452 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07002453 if (ws != null) {
2454 mWakeLock.setWorkSource(ws);
2455 return;
2456 }
2457
Christopher Tate14a7bb02015-10-01 10:24:31 -07002458 final int uid = (knownUid >= 0)
2459 ? knownUid
2460 : ActivityManagerNative.getDefault().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07002461 if (uid >= 0) {
2462 mWakeLock.setWorkSource(new WorkSource(uid));
2463 return;
2464 }
2465 } catch (Exception e) {
2466 }
2467
2468 // Something went wrong; fall back to attributing the lock to the OS
2469 mWakeLock.setWorkSource(null);
2470 }
2471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002472 private class AlarmHandler extends Handler {
2473 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002474 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
2475 public static final int LISTENER_TIMEOUT = 3;
2476 public static final int REPORT_ALARMS_ACTIVE = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002477
2478 public AlarmHandler() {
2479 }
2480
2481 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002482 switch (msg.what) {
2483 case ALARM_EVENT: {
2484 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2485 synchronized (mLock) {
2486 final long nowRTC = System.currentTimeMillis();
2487 final long nowELAPSED = SystemClock.elapsedRealtime();
2488 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2489 updateNextAlarmClockLocked();
2490 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002491
Christopher Tate14a7bb02015-10-01 10:24:31 -07002492 // now trigger the alarms without the lock held
2493 for (int i=0; i<triggerList.size(); i++) {
2494 Alarm alarm = triggerList.get(i);
2495 try {
2496 alarm.operation.send();
2497 } catch (PendingIntent.CanceledException e) {
2498 if (alarm.repeatInterval > 0) {
2499 // This IntentSender is no longer valid, but this
2500 // is a repeating alarm, so toss the hoser.
2501 removeImpl(alarm.operation);
2502 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002503 }
2504 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002505 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002506 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002507
2508 case SEND_NEXT_ALARM_CLOCK_CHANGED:
2509 sendNextAlarmClockChanged();
2510 break;
2511
2512 case LISTENER_TIMEOUT:
2513 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
2514 break;
2515
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002516 case REPORT_ALARMS_ACTIVE:
2517 if (mLocalDeviceIdleController != null) {
2518 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
2519 }
2520 break;
2521
Christopher Tate14a7bb02015-10-01 10:24:31 -07002522 default:
2523 // nope, just ignore it
2524 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 }
2526 }
2527 }
2528
2529 class ClockReceiver extends BroadcastReceiver {
2530 public ClockReceiver() {
2531 IntentFilter filter = new IntentFilter();
2532 filter.addAction(Intent.ACTION_TIME_TICK);
2533 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002534 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002535 }
2536
2537 @Override
2538 public void onReceive(Context context, Intent intent) {
2539 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07002540 if (DEBUG_BATCH) {
2541 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
2542 }
2543 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
2545 // Since the kernel does not keep track of DST, we need to
2546 // reset the TZ information at the beginning of each day
2547 // based off of the current Zone gmt offset + userspace tracked
2548 // daylight savings information.
2549 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02002550 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002551 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07002552 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002553 }
2554 }
2555
2556 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07002557 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09002558 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07002559
2560 // Schedule this event for the amount of time that it would take to get to
2561 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09002562 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07002563
David Christieebe51fc2013-07-26 13:23:29 -07002564 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002565 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002566 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
2567 null, Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002568 }
Christopher Tate385e4982013-07-23 18:22:29 -07002569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002570 public void scheduleDateChangedEvent() {
2571 Calendar calendar = Calendar.getInstance();
2572 calendar.setTimeInMillis(System.currentTimeMillis());
2573 calendar.set(Calendar.HOUR, 0);
2574 calendar.set(Calendar.MINUTE, 0);
2575 calendar.set(Calendar.SECOND, 0);
2576 calendar.set(Calendar.MILLISECOND, 0);
2577 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07002578
2579 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002580 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
2581 AlarmManager.FLAG_STANDALONE, workSource, null,
2582 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002583 }
2584 }
2585
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002586 class InteractiveStateReceiver extends BroadcastReceiver {
2587 public InteractiveStateReceiver() {
2588 IntentFilter filter = new IntentFilter();
2589 filter.addAction(Intent.ACTION_SCREEN_OFF);
2590 filter.addAction(Intent.ACTION_SCREEN_ON);
2591 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
2592 getContext().registerReceiver(this, filter);
2593 }
2594
2595 @Override
2596 public void onReceive(Context context, Intent intent) {
2597 synchronized (mLock) {
2598 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
2599 }
2600 }
2601 }
2602
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002603 class UninstallReceiver extends BroadcastReceiver {
2604 public UninstallReceiver() {
2605 IntentFilter filter = new IntentFilter();
2606 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2607 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002608 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002609 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08002610 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002611 // Register for events related to sdcard installation.
2612 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08002613 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002614 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002615 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002616 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002617 }
2618
2619 @Override
2620 public void onReceive(Context context, Intent intent) {
2621 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002622 String action = intent.getAction();
2623 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002624 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
2625 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
2626 for (String packageName : pkgList) {
2627 if (lookForPackageLocked(packageName)) {
2628 setResultCode(Activity.RESULT_OK);
2629 return;
2630 }
2631 }
2632 return;
2633 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002634 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002635 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
2636 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
2637 if (userHandle >= 0) {
2638 removeUserLocked(userHandle);
2639 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002640 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
2641 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
2642 if (uid >= 0) {
2643 mLastAllowWhileIdleDispatch.delete(uid);
2644 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002645 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08002646 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
2647 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
2648 // This package is being updated; don't kill its alarms.
2649 return;
2650 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002651 Uri data = intent.getData();
2652 if (data != null) {
2653 String pkg = data.getSchemeSpecificPart();
2654 if (pkg != null) {
2655 pkgList = new String[]{pkg};
2656 }
2657 }
2658 }
2659 if (pkgList != null && (pkgList.length > 0)) {
2660 for (String pkg : pkgList) {
2661 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07002662 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002663 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
2664 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
2665 if (uidStats.remove(pkg) != null) {
2666 if (uidStats.size() <= 0) {
2667 mBroadcastStats.removeAt(i);
2668 }
2669 }
2670 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002671 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002672 }
2673 }
2674 }
2675 }
2676
2677 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002678 String pkg = pi.getCreatorPackage();
2679 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002680 return getStatsLocked(uid, pkg);
2681 }
2682
2683 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002684 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
2685 if (uidStats == null) {
2686 uidStats = new ArrayMap<String, BroadcastStats>();
2687 mBroadcastStats.put(uid, uidStats);
2688 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002689 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002690 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002691 bs = new BroadcastStats(uid, pkgName);
2692 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002693 }
2694 return bs;
2695 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002696
Christopher Tate14a7bb02015-10-01 10:24:31 -07002697 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
2698 private InFlight removeLocked(PendingIntent pi, Intent intent) {
2699 for (int i = 0; i < mInFlight.size(); i++) {
2700 if (mInFlight.get(i).mPendingIntent == pi) {
2701 return mInFlight.remove(i);
2702 }
2703 }
2704 mLog.w("No in-flight alarm for " + pi + " " + intent);
2705 return null;
2706 }
2707
2708 private InFlight removeLocked(IBinder listener) {
2709 for (int i = 0; i < mInFlight.size(); i++) {
2710 if (mInFlight.get(i).mListener == listener) {
2711 return mInFlight.remove(i);
2712 }
2713 }
2714 mLog.w("No in-flight alarm for listener " + listener);
2715 return null;
2716 }
2717
2718 private void updateStatsLocked(InFlight inflight) {
2719 final long nowELAPSED = SystemClock.elapsedRealtime();
2720 BroadcastStats bs = inflight.mBroadcastStats;
2721 bs.nesting--;
2722 if (bs.nesting <= 0) {
2723 bs.nesting = 0;
2724 bs.aggregateTime += nowELAPSED - bs.startTime;
2725 }
2726 FilterStats fs = inflight.mFilterStats;
2727 fs.nesting--;
2728 if (fs.nesting <= 0) {
2729 fs.nesting = 0;
2730 fs.aggregateTime += nowELAPSED - fs.startTime;
2731 }
2732 if (RECORD_ALARMS_IN_HISTORY) {
2733 if (inflight.mWorkSource != null && inflight.mWorkSource.size() > 0) {
2734 for (int wi=0; wi<inflight.mWorkSource.size(); wi++) {
2735 ActivityManagerNative.noteAlarmFinish(
2736 inflight.mPendingIntent, inflight.mWorkSource.get(wi), inflight.mTag);
2737 }
2738 } else {
2739 ActivityManagerNative.noteAlarmFinish(
2740 inflight.mPendingIntent, inflight.mUid, inflight.mTag);
2741 }
2742 }
2743 }
2744
2745 private void updateTrackingLocked(InFlight inflight) {
2746 if (inflight != null) {
2747 updateStatsLocked(inflight);
2748 }
2749 mBroadcastRefCount--;
2750 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002751 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002752 mWakeLock.release();
2753 if (mInFlight.size() > 0) {
2754 mLog.w("Finished all dispatches with " + mInFlight.size()
2755 + " remaining inflights");
2756 for (int i=0; i<mInFlight.size(); i++) {
2757 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
2758 }
2759 mInFlight.clear();
2760 }
2761 } else {
2762 // the next of our alarms is now in flight. reattribute the wakelock.
2763 if (mInFlight.size() > 0) {
2764 InFlight inFlight = mInFlight.get(0);
2765 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
2766 inFlight.mAlarmType, inFlight.mTag, -1, false);
2767 } else {
2768 // should never happen
2769 mLog.w("Alarm wakelock still held but sent queue empty");
2770 mWakeLock.setWorkSource(null);
2771 }
2772 }
2773 }
2774
2775 /**
2776 * Callback that arrives when a direct-call alarm reports that delivery has finished
2777 */
2778 @Override
2779 public void alarmComplete(IBinder who) {
2780 if (who == null) {
2781 Slog.w(TAG, "Invalid alarmComplete: uid=" + Binder.getCallingUid()
2782 + " pid=" + Binder.getCallingPid());
2783 return;
2784 }
2785
2786 final long ident = Binder.clearCallingIdentity();
2787 try {
2788 synchronized (mLock) {
2789 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
2790 InFlight inflight = removeLocked(who);
2791 if (inflight != null) {
2792 if (DEBUG_LISTENER_CALLBACK) {
2793 Slog.i(TAG, "alarmComplete() from " + who);
2794 }
2795 updateTrackingLocked(inflight);
2796 } else {
2797 // Delivery timed out, and the timeout handling already took care of
2798 // updating our tracking here, so we needn't do anything further.
2799 if (DEBUG_LISTENER_CALLBACK) {
2800 Slog.i(TAG, "Late alarmComplete() from " + who);
2801 }
2802 }
2803 }
2804 } finally {
2805 Binder.restoreCallingIdentity(ident);
2806 }
2807 }
2808
2809 /**
2810 * Callback that arrives when a PendingIntent alarm has finished delivery
2811 */
2812 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002813 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
2814 String resultData, Bundle resultExtras) {
2815 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002816 updateTrackingLocked(removeLocked(pi, intent));
2817 }
2818 }
2819
2820 /**
2821 * Timeout of a direct-call alarm delivery
2822 */
2823 public void alarmTimedOut(IBinder who) {
2824 synchronized (mLock) {
2825 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08002826 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002827 // TODO: implement ANR policy for the target
2828 if (DEBUG_LISTENER_CALLBACK) {
2829 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002830 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002831 updateTrackingLocked(inflight);
Dianne Hackborn81038902012-11-26 17:04:09 -08002832 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002833 if (DEBUG_LISTENER_CALLBACK) {
2834 Slog.i(TAG, "Spurious timeout of listener " + who);
2835 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002836 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002837 }
2838 }
2839
2840 /**
2841 * Deliver an alarm and set up the post-delivery handling appropriately
2842 */
2843 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
2844 if (alarm.operation != null) {
2845 // PendingIntent alarm
2846 try {
2847 alarm.operation.send(getContext(), 0,
2848 mBackgroundIntent.putExtra(
2849 Intent.EXTRA_ALARM_COUNT, alarm.count),
2850 mDeliveryTracker, mHandler, null,
2851 allowWhileIdle ? mIdleOptions : null);
2852 } catch (PendingIntent.CanceledException e) {
2853 if (alarm.repeatInterval > 0) {
2854 // This IntentSender is no longer valid, but this
2855 // is a repeating alarm, so toss it
2856 removeImpl(alarm.operation);
2857 }
2858 }
2859 } else {
2860 // Direct listener callback alarm
2861 try {
2862 if (DEBUG_LISTENER_CALLBACK) {
2863 Slog.v(TAG, "Alarm to uid=" + alarm.uid
2864 + " listener=" + alarm.listener.asBinder());
2865 }
2866 alarm.listener.doAlarm(this);
2867 mHandler.sendMessageDelayed(
2868 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
2869 alarm.listener.asBinder()),
2870 mConstants.LISTENER_TIMEOUT);
2871 } catch (Exception e) {
2872 if (DEBUG_LISTENER_CALLBACK) {
2873 Slog.i(TAG, "Alarm undeliverable to listener "
2874 + alarm.listener.asBinder(), e);
2875 }
2876 }
2877 }
2878
2879 // The alarm is now in flight; now arrange wakelock and stats tracking
2880 if (mBroadcastRefCount == 0) {
2881 setWakelockWorkSource(alarm.operation, alarm.workSource,
2882 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
2883 true);
2884 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002885 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002886 }
2887 final InFlight inflight = new InFlight(AlarmManagerService.this,
2888 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
2889 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
2890 mInFlight.add(inflight);
2891 mBroadcastRefCount++;
2892
2893 if (allowWhileIdle) {
2894 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
2895 mLastAllowWhileIdleDispatch.put(alarm.uid, nowELAPSED);
2896 if (RECORD_DEVICE_IDLE_ALARMS) {
2897 IdleDispatchEntry ent = new IdleDispatchEntry();
2898 ent.uid = alarm.uid;
2899 ent.pkg = alarm.packageName;
2900 ent.tag = alarm.statsTag;
2901 ent.op = "DELIVER";
2902 ent.elapsedRealtime = nowELAPSED;
2903 mAllowWhileIdleDispatches.add(ent);
2904 }
2905 }
2906
2907 final BroadcastStats bs = inflight.mBroadcastStats;
2908 bs.count++;
2909 if (bs.nesting == 0) {
2910 bs.nesting = 1;
2911 bs.startTime = nowELAPSED;
2912 } else {
2913 bs.nesting++;
2914 }
2915 final FilterStats fs = inflight.mFilterStats;
2916 fs.count++;
2917 if (fs.nesting == 0) {
2918 fs.nesting = 1;
2919 fs.startTime = nowELAPSED;
2920 } else {
2921 fs.nesting++;
2922 }
2923 if (alarm.type == ELAPSED_REALTIME_WAKEUP
2924 || alarm.type == RTC_WAKEUP) {
2925 bs.numWakeup++;
2926 fs.numWakeup++;
2927 if (alarm.workSource != null && alarm.workSource.size() > 0) {
2928 for (int wi=0; wi<alarm.workSource.size(); wi++) {
2929 ActivityManagerNative.noteWakeupAlarm(
2930 alarm.operation, alarm.workSource.get(wi),
2931 alarm.workSource.getName(wi), alarm.statsTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08002932 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002933 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002934 ActivityManagerNative.noteWakeupAlarm(
2935 alarm.operation, -1, alarm.packageName, alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002936 }
2937 }
2938 }
2939 }
2940}