blob: 8d02b689960c7638a8fb85aaedd96123bfb27ca4 [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;
Dianne Hackborna750a632015-06-16 17:18:23 -070023import android.app.BroadcastOptions;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.app.IAlarmManager;
25import android.app.PendingIntent;
26import android.content.BroadcastReceiver;
Dianne Hackborna750a632015-06-16 17:18:23 -070027import android.content.ContentResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.content.Context;
29import android.content.Intent;
30import android.content.IntentFilter;
31import android.content.pm.PackageManager;
Dianne Hackborna750a632015-06-16 17:18:23 -070032import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.net.Uri;
34import android.os.Binder;
35import android.os.Bundle;
36import android.os.Handler;
Adam Lesinski182f73f2013-12-05 16:48:06 -080037import android.os.IBinder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.os.Message;
39import android.os.PowerManager;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070040import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.os.SystemClock;
42import android.os.SystemProperties;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070043import android.os.UserHandle;
Christopher Tatec4a07d12012-04-06 14:19:13 -070044import android.os.WorkSource;
Adrian Roosc42a1e12014-07-07 23:35:53 +020045import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.text.TextUtils;
Adrian Roosc42a1e12014-07-07 23:35:53 +020047import android.text.format.DateFormat;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080048import android.util.ArrayMap;
Dianne Hackborna750a632015-06-16 17:18:23 -070049import android.util.KeyValueListParser;
Adrian Roosc42a1e12014-07-07 23:35:53 +020050import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080051import android.util.Slog;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080052import android.util.SparseArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +020053import android.util.SparseBooleanArray;
Dianne Hackborn3d1933c2015-06-10 16:25:57 -070054import android.util.SparseLongArray;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070055import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056
Christopher Tate4cb338d2013-07-26 13:11:31 -070057import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import java.io.FileDescriptor;
59import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070060import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -080062import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import java.util.Calendar;
64import java.util.Collections;
65import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -050066import java.util.Date;
Christopher Tate1590f1e2014-10-02 17:27:57 -070067import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -070068import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +020069import java.util.Locale;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070070import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import java.util.TimeZone;
John Spurlock604a5ee2015-06-01 12:27:22 -040072import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073
Christopher Tatee0a22b32013-07-11 14:43:13 -070074import static android.app.AlarmManager.RTC_WAKEUP;
75import static android.app.AlarmManager.RTC;
76import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
77import static android.app.AlarmManager.ELAPSED_REALTIME;
78
Dianne Hackborn81038902012-11-26 17:04:09 -080079import com.android.internal.util.LocalLog;
80
Adam Lesinski182f73f2013-12-05 16:48:06 -080081class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -070082 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
83 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -080084 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -070085 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -080086 static final int TIME_CHANGED_MASK = 1 << 16;
87 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -080088
Christopher Tatee0a22b32013-07-11 14:43:13 -070089 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -080090 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -080091
Adam Lesinski182f73f2013-12-05 16:48:06 -080092 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -080093 static final boolean localLOGV = false;
94 static final boolean DEBUG_BATCH = localLOGV || false;
95 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +020096 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -070097 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Adam Lesinski182f73f2013-12-05 16:48:06 -080098 static final int ALARM_EVENT = 1;
99 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200100
Adam Lesinski182f73f2013-12-05 16:48:06 -0800101 static final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800103 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104
Adam Lesinski182f73f2013-12-05 16:48:06 -0800105 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700106
Adrian Roosc42a1e12014-07-07 23:35:53 +0200107 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT = new Intent(
108 AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED);
109
Adam Lesinski182f73f2013-12-05 16:48:06 -0800110 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800111
Adam Lesinski182f73f2013-12-05 16:48:06 -0800112 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800113
Susheel Yadagiri6837e452015-07-09 13:01:39 -0700114 private final ArrayList<Integer> mTriggeredUids = new ArrayList<Integer>();
115 private final ArrayList<Integer> mBlockedUids = new ArrayList<Integer>();
116
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800117 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800118 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700119 private long mNextNonWakeup;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800120 int mBroadcastRefCount = 0;
121 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700122 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c2015-06-10 16:25:57 -0700123 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
124 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800125 final AlarmHandler mHandler = new AlarmHandler();
126 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700127 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 private UninstallReceiver mUninstallReceiver;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800129 final ResultReceiver mResultReceiver = new ResultReceiver();
130 PendingIntent mTimeTickSender;
131 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700132 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700133 boolean mInteractive = true;
134 long mNonInteractiveStartTime;
135 long mNonInteractiveTime;
136 long mLastAlarmDeliveryTime;
137 long mStartCurrentDelayTime;
138 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700139 long mLastTimeChangeClockTime;
140 long mLastTimeChangeRealtime;
Dianne Hackborna750a632015-06-16 17:18:23 -0700141 long mAllowWhileIdleMinTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700142 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800143
Dianne Hackborn3d1933c2015-06-10 16:25:57 -0700144 /**
145 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
146 * used to determine the earliest we can dispatch the next such alarm.
147 */
148 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
149
Dianne Hackborna750a632015-06-16 17:18:23 -0700150 /**
151 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
152 */
153 Bundle mIdleOptions;
154
Jose Lima235510e2014-08-13 12:50:01 -0700155 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
156 new SparseArray<>();
157 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
158 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200159 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
160 new SparseBooleanArray();
161 private boolean mNextAlarmClockMayChange;
162
163 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700164 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
165 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200166
Dianne Hackborna750a632015-06-16 17:18:23 -0700167 /**
168 * All times are in milliseconds. These constants are kept synchronized with the system
169 * global Settings. Any access to this class or its fields should be done while
170 * holding the AlarmManagerService.mLock lock.
171 */
172 private final class Constants extends ContentObserver {
173 // Key names stored in the settings value.
174 private static final String KEY_MIN_FUTURITY = "min_futurity";
175 private static final String KEY_MIN_INTERVAL = "min_interval";
176 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
177 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
178 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
179 = "allow_while_idle_whitelist_duration";
180
181 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
182 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tate30396782015-08-27 15:57:57 -0700183 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborna750a632015-06-16 17:18:23 -0700184 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 15*60*1000;
185 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
186
187 // Minimum futurity of a new alarm
188 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
189
190 // Minimum alarm recurrence interval
191 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
192
193 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
194 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
195
196 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
197 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
198
199 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
200 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
201 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
202
203 private ContentResolver mResolver;
204 private final KeyValueListParser mParser = new KeyValueListParser(',');
205 private long mLastAllowWhileIdleWhitelistDuration = -1;
206
207 public Constants(Handler handler) {
208 super(handler);
209 updateAllowWhileIdleMinTimeLocked();
210 updateAllowWhileIdleWhitelistDurationLocked();
211 }
212
213 public void start(ContentResolver resolver) {
214 mResolver = resolver;
215 mResolver.registerContentObserver(Settings.Global.getUriFor(
216 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
217 updateConstants();
218 }
219
220 public void updateAllowWhileIdleMinTimeLocked() {
221 mAllowWhileIdleMinTime = mPendingIdleUntil != null
222 ? ALLOW_WHILE_IDLE_LONG_TIME : ALLOW_WHILE_IDLE_SHORT_TIME;
223 }
224
225 public void updateAllowWhileIdleWhitelistDurationLocked() {
226 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
227 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
228 BroadcastOptions opts = BroadcastOptions.makeBasic();
229 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
230 mIdleOptions = opts.toBundle();
231 }
232 }
233
234 @Override
235 public void onChange(boolean selfChange, Uri uri) {
236 updateConstants();
237 }
238
239 private void updateConstants() {
240 synchronized (mLock) {
241 try {
242 mParser.setString(Settings.Global.getString(mResolver,
243 Settings.Global.ALARM_MANAGER_CONSTANTS));
244 } catch (IllegalArgumentException e) {
245 // Failed to parse the settings string, log this and move on
246 // with defaults.
247 Slog.e(TAG, "Bad device idle settings", e);
248 }
249
250 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
251 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
252 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
253 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
254 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
255 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
256 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
257 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
258 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
259
260 updateAllowWhileIdleMinTimeLocked();
261 updateAllowWhileIdleWhitelistDurationLocked();
262 }
263 }
264
265 void dump(PrintWriter pw) {
266 pw.println(" Settings:");
267
268 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
269 TimeUtils.formatDuration(MIN_FUTURITY, pw);
270 pw.println();
271
272 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
273 TimeUtils.formatDuration(MIN_INTERVAL, pw);
274 pw.println();
275
276 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
277 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
278 pw.println();
279
280 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
281 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
282 pw.println();
283
284 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
285 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
286 pw.println();
287 }
288 }
289
290 final Constants mConstants;
291
Christopher Tate1590f1e2014-10-02 17:27:57 -0700292 // Alarm delivery ordering bookkeeping
293 static final int PRIO_TICK = 0;
294 static final int PRIO_WAKEUP = 1;
295 static final int PRIO_NORMAL = 2;
296
Dianne Hackborna750a632015-06-16 17:18:23 -0700297 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700298 int seq;
299 int priority;
300
301 PriorityClass() {
302 seq = mCurrentSeq - 1;
303 priority = PRIO_NORMAL;
304 }
305 }
306
Dianne Hackborna750a632015-06-16 17:18:23 -0700307 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700308 int mCurrentSeq = 0;
309
Dianne Hackborna750a632015-06-16 17:18:23 -0700310 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700311 public long when;
312 public int uid;
313 public String action;
314
315 public WakeupEvent(long theTime, int theUid, String theAction) {
316 when = theTime;
317 uid = theUid;
318 action = theAction;
319 }
320 }
321
Adam Lesinski182f73f2013-12-05 16:48:06 -0800322 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
323 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700324
Adrian Roosc42a1e12014-07-07 23:35:53 +0200325 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700326 long start; // These endpoints are always in ELAPSED
327 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700328 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700329
330 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
331
332 Batch() {
333 start = 0;
334 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700335 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700336 }
337
338 Batch(Alarm seed) {
339 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700340 end = seed.maxWhenElapsed;
341 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700342 alarms.add(seed);
343 }
344
345 int size() {
346 return alarms.size();
347 }
348
349 Alarm get(int index) {
350 return alarms.get(index);
351 }
352
353 boolean canHold(long whenElapsed, long maxWhen) {
354 return (end >= whenElapsed) && (start <= maxWhen);
355 }
356
357 boolean add(Alarm alarm) {
358 boolean newStart = false;
359 // narrows the batch if necessary; presumes that canHold(alarm) is true
360 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
361 if (index < 0) {
362 index = 0 - index - 1;
363 }
364 alarms.add(index, alarm);
365 if (DEBUG_BATCH) {
366 Slog.v(TAG, "Adding " + alarm + " to " + this);
367 }
368 if (alarm.whenElapsed > start) {
369 start = alarm.whenElapsed;
370 newStart = true;
371 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700372 if (alarm.maxWhenElapsed < end) {
373 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700374 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700375 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700376
377 if (DEBUG_BATCH) {
378 Slog.v(TAG, " => now " + this);
379 }
380 return newStart;
381 }
382
383 boolean remove(final PendingIntent operation) {
384 boolean didRemove = false;
385 long newStart = 0; // recalculate endpoints as we go
386 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700387 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700388 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700389 Alarm alarm = alarms.get(i);
390 if (alarm.operation.equals(operation)) {
391 alarms.remove(i);
392 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200393 if (alarm.alarmClock != null) {
394 mNextAlarmClockMayChange = true;
395 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700396 } else {
397 if (alarm.whenElapsed > newStart) {
398 newStart = alarm.whenElapsed;
399 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700400 if (alarm.maxWhenElapsed < newEnd) {
401 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700402 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700403 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700404 i++;
405 }
406 }
407 if (didRemove) {
408 // commit the new batch bounds
409 start = newStart;
410 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700411 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700412 }
413 return didRemove;
414 }
415
416 boolean remove(final String packageName) {
417 boolean didRemove = false;
418 long newStart = 0; // recalculate endpoints as we go
419 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700420 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700421 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700422 Alarm alarm = alarms.get(i);
423 if (alarm.operation.getTargetPackage().equals(packageName)) {
424 alarms.remove(i);
425 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200426 if (alarm.alarmClock != null) {
427 mNextAlarmClockMayChange = true;
428 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700429 } else {
430 if (alarm.whenElapsed > newStart) {
431 newStart = alarm.whenElapsed;
432 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700433 if (alarm.maxWhenElapsed < newEnd) {
434 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700435 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700436 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700437 i++;
438 }
439 }
440 if (didRemove) {
441 // commit the new batch bounds
442 start = newStart;
443 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700444 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700445 }
446 return didRemove;
447 }
448
449 boolean remove(final int userHandle) {
450 boolean didRemove = false;
451 long newStart = 0; // recalculate endpoints as we go
452 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700453 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700454 Alarm alarm = alarms.get(i);
455 if (UserHandle.getUserId(alarm.operation.getCreatorUid()) == userHandle) {
456 alarms.remove(i);
457 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200458 if (alarm.alarmClock != null) {
459 mNextAlarmClockMayChange = true;
460 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700461 } else {
462 if (alarm.whenElapsed > newStart) {
463 newStart = alarm.whenElapsed;
464 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700465 if (alarm.maxWhenElapsed < newEnd) {
466 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700467 }
468 i++;
469 }
470 }
471 if (didRemove) {
472 // commit the new batch bounds
473 start = newStart;
474 end = newEnd;
475 }
476 return didRemove;
477 }
478
479 boolean hasPackage(final String packageName) {
480 final int N = alarms.size();
481 for (int i = 0; i < N; i++) {
482 Alarm a = alarms.get(i);
483 if (a.operation.getTargetPackage().equals(packageName)) {
484 return true;
485 }
486 }
487 return false;
488 }
489
490 boolean hasWakeups() {
491 final int N = alarms.size();
492 for (int i = 0; i < N; i++) {
493 Alarm a = alarms.get(i);
494 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
495 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
496 return true;
497 }
498 }
499 return false;
500 }
501
502 @Override
503 public String toString() {
504 StringBuilder b = new StringBuilder(40);
505 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
506 b.append(" num="); b.append(size());
507 b.append(" start="); b.append(start);
508 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700509 if (flags != 0) {
510 b.append(" flgs=0x");
511 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700512 }
513 b.append('}');
514 return b.toString();
515 }
516 }
517
518 static class BatchTimeOrder implements Comparator<Batch> {
519 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800520 long when1 = b1.start;
521 long when2 = b2.start;
522 if (when1 - when2 > 0) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700523 return 1;
524 }
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800525 if (when1 - when2 < 0) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700526 return -1;
527 }
528 return 0;
529 }
530 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800531
532 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
533 @Override
534 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700535 // priority class trumps everything. TICK < WAKEUP < NORMAL
536 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
537 return -1;
538 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
539 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800540 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700541
542 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800543 if (lhs.whenElapsed < rhs.whenElapsed) {
544 return -1;
545 } else if (lhs.whenElapsed > rhs.whenElapsed) {
546 return 1;
547 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700548
549 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800550 return 0;
551 }
552 };
553
Christopher Tate1590f1e2014-10-02 17:27:57 -0700554 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
555 final int N = alarms.size();
556 for (int i = 0; i < N; i++) {
557 Alarm a = alarms.get(i);
558
559 final int alarmPrio;
560 if (Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
561 alarmPrio = PRIO_TICK;
562 } else if (a.wakeup) {
563 alarmPrio = PRIO_WAKEUP;
564 } else {
565 alarmPrio = PRIO_NORMAL;
566 }
567
568 PriorityClass packagePrio = a.priorityClass;
569 if (packagePrio == null) packagePrio = mPriorities.get(a.operation.getCreatorPackage());
570 if (packagePrio == null) {
571 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
572 mPriorities.put(a.operation.getCreatorPackage(), packagePrio);
573 }
574 a.priorityClass = packagePrio;
575
576 if (packagePrio.seq != mCurrentSeq) {
577 // first alarm we've seen in the current delivery generation from this package
578 packagePrio.priority = alarmPrio;
579 packagePrio.seq = mCurrentSeq;
580 } else {
581 // Multiple alarms from this package being delivered in this generation;
582 // bump the package's delivery class if it's warranted.
583 // TICK < WAKEUP < NORMAL
584 if (alarmPrio < packagePrio.priority) {
585 packagePrio.priority = alarmPrio;
586 }
587 }
588 }
589 }
590
Christopher Tatee0a22b32013-07-11 14:43:13 -0700591 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800592 static final long MIN_FUZZABLE_INTERVAL = 10000;
593 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700594 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
595
596 // set to null if in idle mode; while in this mode, any alarms we don't want
597 // to run during this time are placed in mPendingWhileIdleAlarms
598 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700599 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700600 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700601
Jeff Brownb880d882014-02-10 19:47:07 -0800602 public AlarmManagerService(Context context) {
603 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700604 mConstants = new Constants(mHandler);
Jeff Brownb880d882014-02-10 19:47:07 -0800605 }
606
Christopher Tatee0a22b32013-07-11 14:43:13 -0700607 static long convertToElapsed(long when, int type) {
608 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
609 if (isRtc) {
610 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
611 }
612 return when;
613 }
614
615 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
616 // calculate the end of our nominal delivery window for the alarm.
617 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
618 // Current heuristic: batchable window is 75% of either the recurrence interval
619 // [for a periodic alarm] or of the time from now to the desired delivery time,
620 // with a minimum delay/interval of 10 seconds, under which we will simply not
621 // defer the alarm.
622 long futurity = (interval == 0)
623 ? (triggerAtTime - now)
624 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700625 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700626 futurity = 0;
627 }
628 return triggerAtTime + (long)(.75 * futurity);
629 }
630
631 // returns true if the batch was added at the head
632 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
633 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
634 if (index < 0) {
635 index = 0 - index - 1;
636 }
637 list.add(index, newBatch);
638 return (index == 0);
639 }
640
Christopher Tate385e4982013-07-23 18:22:29 -0700641 // Return the index of the matching batch, or -1 if none found.
642 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700643 final int N = mAlarmBatches.size();
644 for (int i = 0; i < N; i++) {
645 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700646 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700647 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700648 }
649 }
Christopher Tate385e4982013-07-23 18:22:29 -0700650 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700651 }
652
653 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
654 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700655 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700656 rebatchAllAlarmsLocked(true);
657 }
658 }
659
660 void rebatchAllAlarmsLocked(boolean doValidate) {
661 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
662 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700663 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700664 final long nowElapsed = SystemClock.elapsedRealtime();
665 final int oldBatches = oldSet.size();
666 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
667 Batch batch = oldSet.get(batchNum);
668 final int N = batch.size();
669 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700670 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700671 }
672 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700673 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
674 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
675 + " to " + mPendingIdleUntil);
676 if (mPendingIdleUntil == null) {
677 // Somehow we lost this... we need to restore all of the pending alarms.
678 restorePendingWhileIdleAlarmsLocked();
679 }
680 }
681 rescheduleKernelAlarmsLocked();
682 updateNextAlarmClockLocked();
683 }
684
685 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
686 a.when = a.origWhen;
687 long whenElapsed = convertToElapsed(a.when, a.type);
688 final long maxElapsed;
Dianne Hackborn3d1933c2015-06-10 16:25:57 -0700689 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700690 // Exact
691 maxElapsed = whenElapsed;
692 } else {
693 // Not exact. Preserve any explicit window, otherwise recalculate
694 // the window based on the alarm's new futurity. Note that this
695 // reflects a policy of preferring timely to deferred delivery.
696 maxElapsed = (a.windowLength > 0)
697 ? (whenElapsed + a.windowLength)
698 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
699 }
700 a.whenElapsed = whenElapsed;
701 a.maxWhenElapsed = maxElapsed;
702 setImplLocked(a, true, doValidate);
703 }
704
705 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackborn35d54032015-04-23 10:30:43 -0700706 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700707 if (mPendingWhileIdleAlarms.size() > 0) {
708 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
709 mPendingWhileIdleAlarms = new ArrayList<>();
710 final long nowElapsed = SystemClock.elapsedRealtime();
711 for (int i=alarms.size() - 1; i >= 0; i--) {
712 Alarm a = alarms.get(i);
713 reAddAlarmLocked(a, nowElapsed, false);
714 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700715 }
Dianne Hackborn35d54032015-04-23 10:30:43 -0700716
Dianne Hackborn3d1933c2015-06-10 16:25:57 -0700717 // Make sure we are using the correct ALLOW_WHILE_IDLE min time.
Dianne Hackborna750a632015-06-16 17:18:23 -0700718 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn3d1933c2015-06-10 16:25:57 -0700719
Dianne Hackborn35d54032015-04-23 10:30:43 -0700720 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700721 rescheduleKernelAlarmsLocked();
722 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -0700723
724 // And send a TIME_TICK right now, since it is important to get the UI updated.
725 try {
726 mTimeTickSender.send();
727 } catch (PendingIntent.CanceledException e) {
728 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700729 }
730
Adam Lesinski182f73f2013-12-05 16:48:06 -0800731 static final class InFlight extends Intent {
Dianne Hackborn81038902012-11-26 17:04:09 -0800732 final PendingIntent mPendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700733 final WorkSource mWorkSource;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700734 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800735 final BroadcastStats mBroadcastStats;
736 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800737 final int mAlarmType;
Susheel Yadagiri6837e452015-07-09 13:01:39 -0700738 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800739
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800740 InFlight(AlarmManagerService service, PendingIntent pendingIntent, WorkSource workSource,
Susheel Yadagiri6837e452015-07-09 13:01:39 -0700741 int alarmType, String tag, long nowELAPSED, int uid) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800742 mPendingIntent = pendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700743 mWorkSource = workSource;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700744 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800745 mBroadcastStats = service.getStatsLocked(pendingIntent);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700746 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -0800747 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700748 fs = new FilterStats(mBroadcastStats, mTag);
749 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -0800750 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700751 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -0800752 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800753 mAlarmType = alarmType;
Susheel Yadagiri6837e452015-07-09 13:01:39 -0700754 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800755 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800757
Adam Lesinski182f73f2013-12-05 16:48:06 -0800758 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -0800759 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700760 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800761
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700762 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800763 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800764 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 int numWakeup;
766 long startTime;
767 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -0800768
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700769 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800770 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700771 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800772 }
773 }
Dianne Hackborn3d1933c2015-06-10 16:25:57 -0700774
Adam Lesinski182f73f2013-12-05 16:48:06 -0800775 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800776 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800777 final String mPackageName;
778
779 long aggregateTime;
780 int count;
781 int numWakeup;
782 long startTime;
783 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700784 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -0800785
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800786 BroadcastStats(int uid, String packageName) {
787 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800788 mPackageName = packageName;
789 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790 }
Dianne Hackborn3d1933c2015-06-10 16:25:57 -0700791
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800792 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
793 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700794
795 int mNumDelayedAlarms = 0;
796 long mTotalDelayTime = 0;
797 long mMaxDelayTime = 0;
798
Adam Lesinski182f73f2013-12-05 16:48:06 -0800799 @Override
800 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800801 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800802 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800803
804 // We have to set current TimeZone info to kernel
805 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -0800806 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800807
Adam Lesinski182f73f2013-12-05 16:48:06 -0800808 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800809 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800810
Adam Lesinski182f73f2013-12-05 16:48:06 -0800811 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700813 Intent.FLAG_RECEIVER_REGISTERED_ONLY
814 | Intent.FLAG_RECEIVER_FOREGROUND), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700815 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800816 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
817 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800818 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700819 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820
821 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -0800822 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 mClockReceiver.scheduleTimeTickEvent();
824 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700825 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 mUninstallReceiver = new UninstallReceiver();
827
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800828 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800829 AlarmThread waitThread = new AlarmThread();
830 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800832 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800834
835 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800837
838 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -0700839 public void onBootPhase(int phase) {
840 if (phase == PHASE_SYSTEM_SERVICES_READY) {
841 mConstants.start(getContext().getContentResolver());
842 }
843 }
844
845 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 protected void finalize() throws Throwable {
847 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800848 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 } finally {
850 super.finalize();
851 }
852 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700853
Adam Lesinski182f73f2013-12-05 16:48:06 -0800854 void setTimeZoneImpl(String tz) {
855 if (TextUtils.isEmpty(tz)) {
856 return;
David Christieebe51fc2013-07-26 13:23:29 -0700857 }
858
Adam Lesinski182f73f2013-12-05 16:48:06 -0800859 TimeZone zone = TimeZone.getTimeZone(tz);
860 // Prevent reentrant calls from stepping on each other when writing
861 // the time zone property
862 boolean timeZoneWasChanged = false;
863 synchronized (this) {
864 String current = SystemProperties.get(TIMEZONE_PROPERTY);
865 if (current == null || !current.equals(zone.getID())) {
866 if (localLOGV) {
867 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
868 }
869 timeZoneWasChanged = true;
870 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
871 }
872
873 // Update the kernel timezone information
874 // Kernel tracks time offsets as 'minutes west of GMT'
875 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800876 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -0800877 }
878
879 TimeZone.setDefault(null);
880
881 if (timeZoneWasChanged) {
882 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
883 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
884 intent.putExtra("time-zone", zone.getID());
885 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
886 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700888
Adam Lesinski182f73f2013-12-05 16:48:06 -0800889 void removeImpl(PendingIntent operation) {
890 if (operation == null) {
891 return;
892 }
893 synchronized (mLock) {
894 removeLocked(operation);
895 }
896 }
897
898 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700899 PendingIntent operation, int flags, WorkSource workSource,
Dianne Hackborn3d1933c2015-06-10 16:25:57 -0700900 AlarmManager.AlarmClockInfo alarmClock, int callingUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 if (operation == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800902 Slog.w(TAG, "set/setRepeating ignored because there is no intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 return;
904 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700905
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700906 // Sanity check the window length. This will catch people mistakenly
907 // trying to pass an end-of-window timestamp rather than a duration.
908 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
909 Slog.w(TAG, "Window length " + windowLength
910 + "ms suspiciously long; limiting to 1 hour");
911 windowLength = AlarmManager.INTERVAL_HOUR;
912 }
913
Christopher Tate498c6cb2014-11-17 16:09:27 -0800914 // Sanity check the recurrence interval. This will catch people who supply
915 // seconds when the API expects milliseconds.
Dianne Hackborna750a632015-06-16 17:18:23 -0700916 final long minInterval = mConstants.MIN_INTERVAL;
917 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -0800918 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -0700919 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -0800920 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -0700921 interval = minInterval;
Christopher Tate498c6cb2014-11-17 16:09:27 -0800922 }
923
Christopher Tatee0a22b32013-07-11 14:43:13 -0700924 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
925 throw new IllegalArgumentException("Invalid alarm type " + type);
926 }
927
Christopher Tate5f221e82013-07-30 17:13:15 -0700928 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -0700929 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c2015-06-10 16:25:57 -0700930 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -0700931 + " pid=" + what);
932 triggerAtTime = 0;
933 }
934
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700935 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -0800936 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
937 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -0700938 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -0800939 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
940
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700941 final long maxElapsed;
942 if (windowLength == AlarmManager.WINDOW_EXACT) {
943 maxElapsed = triggerElapsed;
944 } else if (windowLength < 0) {
945 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c2015-06-10 16:25:57 -0700946 // Fix this window in place, so that as time approaches we don't collapse it.
947 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700948 } else {
949 maxElapsed = triggerElapsed + windowLength;
950 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700951
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700953 if (DEBUG_BATCH) {
954 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700955 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -0700956 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700957 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958 }
Christopher Tate3e04b472013-10-21 17:51:31 -0700959 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Dianne Hackborn3d1933c2015-06-10 16:25:57 -0700960 interval, operation, flags, true, workSource, alarmClock, callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800961 }
962 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963
Christopher Tate3e04b472013-10-21 17:51:31 -0700964 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700965 long maxWhen, long interval, PendingIntent operation, int flags,
Jose Lima235510e2014-08-13 12:50:01 -0700966 boolean doValidate, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
Dianne Hackborn3d1933c2015-06-10 16:25:57 -0700967 int uid) {
Christopher Tate3e04b472013-10-21 17:51:31 -0700968 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Dianne Hackborn3d1933c2015-06-10 16:25:57 -0700969 operation, workSource, flags, alarmClock, uid);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700970 removeLocked(operation);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700971 setImplLocked(a, false, doValidate);
972 }
Christopher Tateb8849c12011-02-08 13:39:01 -0800973
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700974 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
975 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700976 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700977 // The caller has given the time they want this to happen at, however we need
978 // to pull that earlier if there are existing alarms that have requested to
979 // bring us out of idle.
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700980 if (mNextWakeFromIdle != null) {
981 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700982 }
983 // Add fuzz to make the alarm go off some time before the actual desired time.
984 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700985 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700986 if (fuzz > 0) {
987 if (mRandom == null) {
988 mRandom = new Random();
989 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700990 final int delta = mRandom.nextInt(fuzz);
991 a.whenElapsed -= delta;
992 if (false) {
993 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
994 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
995 Slog.d(TAG, "Applied fuzz: " + fuzz);
996 Slog.d(TAG, "Final delta: " + delta);
997 Slog.d(TAG, "Final when: " + a.whenElapsed);
998 }
999 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001000 }
1001
1002 } else if (mPendingIdleUntil != null) {
1003 // We currently have an idle until alarm scheduled; if the new alarm has
1004 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07001005 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1006 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1007 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001008 == 0) {
1009 mPendingWhileIdleAlarms.add(a);
1010 return;
1011 }
1012 }
1013
1014 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
1015 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -07001016 if (whichBatch < 0) {
1017 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001018 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 } else {
Christopher Tate385e4982013-07-23 18:22:29 -07001020 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001021 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001022 // The start time of this batch advanced, so batch ordering may
1023 // have just been broken. Move it to where it now belongs.
1024 mAlarmBatches.remove(whichBatch);
1025 addBatchLocked(mAlarmBatches, batch);
1026 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 }
1028
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001029 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001030 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001031 }
1032
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001033 boolean needRebatch = false;
1034
1035 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
1036 mPendingIdleUntil = a;
Dianne Hackborna750a632015-06-16 17:18:23 -07001037 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001038 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001039 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1040 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1041 mNextWakeFromIdle = a;
1042 // If this wake from idle is earlier than whatever was previously scheduled,
1043 // and we are currently idling, then we need to rebatch alarms in case the idle
1044 // until time needs to be updated.
1045 if (mPendingIdleUntil != null) {
1046 needRebatch = true;
1047 }
1048 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001049 }
1050
1051 if (!rebatching) {
1052 if (DEBUG_VALIDATE) {
1053 if (doValidate && !validateConsistencyLocked()) {
1054 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1055 + " when(hex)=" + Long.toHexString(a.when)
1056 + " whenElapsed=" + a.whenElapsed
1057 + " maxWhenElapsed=" + a.maxWhenElapsed
1058 + " interval=" + a.repeatInterval + " op=" + a.operation
1059 + " flags=0x" + Integer.toHexString(a.flags));
1060 rebatchAllAlarmsLocked(false);
1061 needRebatch = false;
1062 }
1063 }
1064
1065 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001066 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001067 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001068
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001069 rescheduleKernelAlarmsLocked();
1070 updateNextAlarmClockLocked();
1071 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001072 }
1073
Adam Lesinski182f73f2013-12-05 16:48:06 -08001074 private final IBinder mService = new IAlarmManager.Stub() {
1075 @Override
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001076 public void set(int type, long triggerAtTime, long windowLength, long interval, int flags,
Jose Lima235510e2014-08-13 12:50:01 -07001077 PendingIntent operation, WorkSource workSource,
1078 AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07001079 final int callingUid = Binder.getCallingUid();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001080 if (workSource != null) {
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07001081 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001082 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07001083 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001084 }
1085
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07001086 // No incoming callers can request either WAKE_FROM_IDLE or
1087 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1088 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1089 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1090
1091 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1092 // manager when to come out of idle mode, which is only for DeviceIdleController.
1093 if (callingUid != Process.SYSTEM_UID) {
1094 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1095 }
1096
1097 // If the caller is a core system component, and not calling to do work on behalf
1098 // of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED. This means we
1099 // will allow these alarms to go off as normal even while idle, with no timing
1100 // restrictions.
1101 if (callingUid < Process.FIRST_APPLICATION_UID && workSource == null) {
1102 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1103 }
1104
1105 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001106 if (windowLength == AlarmManager.WINDOW_EXACT) {
1107 flags |= AlarmManager.FLAG_STANDALONE;
1108 }
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07001109
1110 // If this alarm is for an alarm clock, then it must be standalone and we will
1111 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001112 if (alarmClock != null) {
1113 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
1114 }
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07001115
Adam Lesinski182f73f2013-12-05 16:48:06 -08001116 setImpl(type, triggerAtTime, windowLength, interval, operation,
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07001117 flags, workSource, alarmClock, callingUid);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001118 }
Christopher Tate89779822012-08-31 14:40:03 -07001119
Adam Lesinski182f73f2013-12-05 16:48:06 -08001120 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001121 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001122 getContext().enforceCallingOrSelfPermission(
1123 "android.permission.SET_TIME",
1124 "setTime");
1125
Greg Hackmann0cab8962014-02-21 16:35:52 -08001126 if (mNativeData == 0) {
1127 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1128 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001129 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001130
1131 synchronized (mLock) {
1132 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001135
1136 @Override
1137 public void setTimeZone(String tz) {
1138 getContext().enforceCallingOrSelfPermission(
1139 "android.permission.SET_TIME_ZONE",
1140 "setTimeZone");
1141
1142 final long oldId = Binder.clearCallingIdentity();
1143 try {
1144 setTimeZoneImpl(tz);
1145 } finally {
1146 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 }
1148 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001149
Adam Lesinski182f73f2013-12-05 16:48:06 -08001150 @Override
1151 public void remove(PendingIntent operation) {
1152 removeImpl(operation);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001153
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001155
Adam Lesinski182f73f2013-12-05 16:48:06 -08001156 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001157 public long getNextWakeFromIdleTime() {
1158 return getNextWakeFromIdleTimeImpl();
1159 }
1160
1161 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001162 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001163 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1164 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1165 "getNextAlarmClock", null);
1166
1167 return getNextAlarmClockImpl(userId);
1168 }
1169
1170 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001171 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1172 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1173 != PackageManager.PERMISSION_GRANTED) {
1174 pw.println("Permission Denial: can't dump AlarmManager from from pid="
1175 + Binder.getCallingPid()
1176 + ", uid=" + Binder.getCallingUid());
1177 return;
Christopher Tate4cb338d2013-07-26 13:11:31 -07001178 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001179
Adam Lesinski182f73f2013-12-05 16:48:06 -08001180 dumpImpl(pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001181 }
Susheel Yadagiri6837e452015-07-09 13:01:39 -07001182
1183 @Override
1184 /* updates the blocked uids, so if a wake lock is acquired to only fire
1185 * alarm for it, it can be released.
1186 */
1187 public void updateBlockedUids(int uid, boolean isBlocked) {
1188
1189 if (localLOGV) Slog.v(TAG, "UpdateBlockedUids: uid = " + uid +
1190 " isBlocked = " + isBlocked);
1191
1192 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
1193 if (localLOGV) Slog.v(TAG, "UpdateBlockedUids is not allowed");
1194 return;
1195 }
1196
1197 synchronized(mLock) {
1198 if(isBlocked) {
1199 mBlockedUids.add(new Integer(uid));
1200 if (checkReleaseWakeLock()) {
1201 /* all the uids for which the alarms are triggered
1202 * are either blocked or have called onSendFinished.
1203 */
1204 if (mWakeLock.isHeld()) {
1205 mWakeLock.release();
1206 if (localLOGV)
1207 Slog.v(TAG, "AM WakeLock Released Internally in updateBlockedUids");
1208 }
1209 }
1210 } else {
1211 mBlockedUids.clear();
1212 }
1213 }
1214 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001215 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001216
Adam Lesinski182f73f2013-12-05 16:48:06 -08001217 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 synchronized (mLock) {
1219 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001220 mConstants.dump(pw);
1221 pw.println();
1222
Christopher Tatee0a22b32013-07-11 14:43:13 -07001223 final long nowRTC = System.currentTimeMillis();
1224 final long nowELAPSED = SystemClock.elapsedRealtime();
1225 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1226
Dianne Hackborna750a632015-06-16 17:18:23 -07001227 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001228 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001229 pw.print(" nowELAPSED="); TimeUtils.formatDuration(nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001230 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001231 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001232 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001233 pw.print(" mLastTimeChangeRealtime=");
Dianne Hackbornc3527222015-05-13 14:03:20 -07001234 TimeUtils.formatDuration(mLastTimeChangeRealtime, pw);
1235 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001236 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001237 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001238 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1239 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001240 pw.print(" Max wakeup delay: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001241 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1242 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001243 pw.print(" Time since last dispatch: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001244 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1245 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001246 pw.print(" Next non-wakeup delivery time: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001247 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1248 pw.println();
1249 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001250
1251 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1252 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001253 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001254 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001255 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001256 pw.print(" Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001257 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001258 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001259
John Spurlock604a5ee2015-06-01 12:27:22 -04001260 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001261 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001262 final TreeSet<Integer> users = new TreeSet<>();
1263 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1264 users.add(mNextAlarmClockForUser.keyAt(i));
1265 }
1266 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1267 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1268 }
1269 for (int user : users) {
1270 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1271 final long time = next != null ? next.getTriggerTime() : 0;
1272 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001273 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001274 pw.print(" pendingSend:"); pw.print(pendingSend);
1275 pw.print(" time:"); pw.print(time);
1276 if (time > 0) {
1277 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1278 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1279 }
1280 pw.println();
1281 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001282 if (mAlarmBatches.size() > 0) {
1283 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001284 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001285 pw.println(mAlarmBatches.size());
1286 for (Batch b : mAlarmBatches) {
1287 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001288 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001289 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001291 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001292 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001293 pw.println(" Idle mode state:");
1294 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001295 if (mPendingIdleUntil != null) {
1296 pw.println(mPendingIdleUntil);
1297 mPendingIdleUntil.dump(pw, " ", nowRTC, nowELAPSED, sdf);
1298 } else {
1299 pw.println("null");
1300 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001301 pw.println(" Pending alarms:");
1302 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001303 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001304 if (mNextWakeFromIdle != null) {
1305 pw.println();
1306 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
1307 mNextWakeFromIdle.dump(pw, " ", nowRTC, nowELAPSED, sdf);
1308 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001309
1310 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001311 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001312 if (mPendingNonWakeupAlarms.size() > 0) {
1313 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001314 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001315 } else {
1316 pw.println("(none)");
1317 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001318 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001319 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1320 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001321 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001322 pw.print(", max non-interactive time: ");
1323 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1324 pw.println();
1325
1326 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001327 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001328 pw.println();
1329
Dianne Hackborna750a632015-06-16 17:18:23 -07001330 pw.print(" mAllowWhileIdleMinTime=");
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07001331 TimeUtils.formatDuration(mAllowWhileIdleMinTime, pw);
1332 pw.println();
1333 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001334 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07001335 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
1336 pw.print(" UID ");
1337 UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
1338 pw.print(": ");
1339 TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i),
1340 nowELAPSED, pw);
1341 pw.println();
1342 }
1343 }
1344 pw.println();
1345
Dianne Hackborn81038902012-11-26 17:04:09 -08001346 if (mLog.dump(pw, " Recent problems", " ")) {
1347 pw.println();
1348 }
1349
1350 final FilterStats[] topFilters = new FilterStats[10];
1351 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1352 @Override
1353 public int compare(FilterStats lhs, FilterStats rhs) {
1354 if (lhs.aggregateTime < rhs.aggregateTime) {
1355 return 1;
1356 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1357 return -1;
1358 }
1359 return 0;
1360 }
1361 };
1362 int len = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001363 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1364 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1365 for (int ip=0; ip<uidStats.size(); ip++) {
1366 BroadcastStats bs = uidStats.valueAt(ip);
1367 for (int is=0; is<bs.filterStats.size(); is++) {
1368 FilterStats fs = bs.filterStats.valueAt(is);
1369 int pos = len > 0
1370 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1371 if (pos < 0) {
1372 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001373 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001374 if (pos < topFilters.length) {
1375 int copylen = topFilters.length - pos - 1;
1376 if (copylen > 0) {
1377 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1378 }
1379 topFilters[pos] = fs;
1380 if (len < topFilters.length) {
1381 len++;
1382 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001383 }
1384 }
1385 }
1386 }
1387 if (len > 0) {
1388 pw.println(" Top Alarms:");
1389 for (int i=0; i<len; i++) {
1390 FilterStats fs = topFilters[i];
1391 pw.print(" ");
1392 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1393 TimeUtils.formatDuration(fs.aggregateTime, pw);
1394 pw.print(" running, "); pw.print(fs.numWakeup);
1395 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001396 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1397 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001398 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001399 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001400 pw.println();
1401 }
1402 }
1403
1404 pw.println(" ");
1405 pw.println(" Alarm Stats:");
1406 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001407 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1408 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1409 for (int ip=0; ip<uidStats.size(); ip++) {
1410 BroadcastStats bs = uidStats.valueAt(ip);
1411 pw.print(" ");
1412 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1413 UserHandle.formatUid(pw, bs.mUid);
1414 pw.print(":");
1415 pw.print(bs.mPackageName);
1416 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1417 pw.print(" running, "); pw.print(bs.numWakeup);
1418 pw.println(" wakeups:");
1419 tmpFilters.clear();
1420 for (int is=0; is<bs.filterStats.size(); is++) {
1421 tmpFilters.add(bs.filterStats.valueAt(is));
1422 }
1423 Collections.sort(tmpFilters, comparator);
1424 for (int i=0; i<tmpFilters.size(); i++) {
1425 FilterStats fs = tmpFilters.get(i);
1426 pw.print(" ");
1427 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1428 TimeUtils.formatDuration(fs.aggregateTime, pw);
1429 pw.print(" "); pw.print(fs.numWakeup);
1430 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001431 pw.print(" alarms, last ");
1432 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1433 pw.println(":");
1434 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001435 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001436 pw.println();
1437 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 }
1439 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001440
1441 if (WAKEUP_STATS) {
1442 pw.println();
1443 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001444 long last = -1;
1445 for (WakeupEvent event : mRecentWakeups) {
1446 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1447 pw.print('|');
1448 if (last < 0) {
1449 pw.print('0');
1450 } else {
1451 pw.print(event.when - last);
1452 }
1453 last = event.when;
1454 pw.print('|'); pw.print(event.uid);
1455 pw.print('|'); pw.print(event.action);
1456 pw.println();
1457 }
1458 pw.println();
1459 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001460 }
1461 }
1462
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001463 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001464 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
1465 PrintWriter pw = new PrintWriter(bs);
1466 final long nowRTC = System.currentTimeMillis();
1467 final long nowELAPSED = SystemClock.elapsedRealtime();
1468 final int NZ = mAlarmBatches.size();
1469 for (int iz = 0; iz < NZ; iz++) {
1470 Batch bz = mAlarmBatches.get(iz);
1471 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001472 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001473 pw.flush();
1474 Slog.v(TAG, bs.toString());
1475 bs.reset();
1476 }
1477 }
1478
1479 private boolean validateConsistencyLocked() {
1480 if (DEBUG_VALIDATE) {
1481 long lastTime = Long.MIN_VALUE;
1482 final int N = mAlarmBatches.size();
1483 for (int i = 0; i < N; i++) {
1484 Batch b = mAlarmBatches.get(i);
1485 if (b.start >= lastTime) {
1486 // duplicate start times are okay because of standalone batches
1487 lastTime = b.start;
1488 } else {
1489 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001490 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1491 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001492 return false;
1493 }
1494 }
1495 }
1496 return true;
1497 }
1498
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001499 private Batch findFirstWakeupBatchLocked() {
1500 final int N = mAlarmBatches.size();
1501 for (int i = 0; i < N; i++) {
1502 Batch b = mAlarmBatches.get(i);
1503 if (b.hasWakeups()) {
1504 return b;
1505 }
1506 }
1507 return null;
1508 }
1509
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001510 long getNextWakeFromIdleTimeImpl() {
1511 synchronized (mLock) {
1512 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
1513 }
1514 }
1515
1516 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001517 synchronized (mLock) {
1518 return mNextAlarmClockForUser.get(userId);
1519 }
1520 }
1521
1522 /**
1523 * Recomputes the next alarm clock for all users.
1524 */
1525 private void updateNextAlarmClockLocked() {
1526 if (!mNextAlarmClockMayChange) {
1527 return;
1528 }
1529 mNextAlarmClockMayChange = false;
1530
Jose Lima235510e2014-08-13 12:50:01 -07001531 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001532 nextForUser.clear();
1533
1534 final int N = mAlarmBatches.size();
1535 for (int i = 0; i < N; i++) {
1536 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
1537 final int M = alarms.size();
1538
1539 for (int j = 0; j < M; j++) {
1540 Alarm a = alarms.get(j);
1541 if (a.alarmClock != null) {
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07001542 final int userId = UserHandle.getUserId(a.uid);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001543
1544 if (DEBUG_ALARM_CLOCK) {
1545 Log.v(TAG, "Found AlarmClockInfo at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001546 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02001547 " for user " + userId);
1548 }
1549
1550 // Alarms and batches are sorted by time, no need to compare times here.
1551 if (nextForUser.get(userId) == null) {
1552 nextForUser.put(userId, a.alarmClock);
1553 }
1554 }
1555 }
1556 }
1557
1558 // Update mNextAlarmForUser with new values.
1559 final int NN = nextForUser.size();
1560 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07001561 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001562 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001563 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001564 if (!newAlarm.equals(currentAlarm)) {
1565 updateNextAlarmInfoForUserLocked(userId, newAlarm);
1566 }
1567 }
1568
1569 // Remove users without any alarm clocks scheduled.
1570 final int NNN = mNextAlarmClockForUser.size();
1571 for (int i = NNN - 1; i >= 0; i--) {
1572 int userId = mNextAlarmClockForUser.keyAt(i);
1573 if (nextForUser.get(userId) == null) {
1574 updateNextAlarmInfoForUserLocked(userId, null);
1575 }
1576 }
1577 }
1578
Jose Lima235510e2014-08-13 12:50:01 -07001579 private void updateNextAlarmInfoForUserLocked(int userId,
1580 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001581 if (alarmClock != null) {
1582 if (DEBUG_ALARM_CLOCK) {
1583 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001584 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02001585 }
1586 mNextAlarmClockForUser.put(userId, alarmClock);
1587 } else {
1588 if (DEBUG_ALARM_CLOCK) {
1589 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
1590 }
1591 mNextAlarmClockForUser.remove(userId);
1592 }
1593
1594 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
1595 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1596 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1597 }
1598
1599 /**
1600 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
1601 * for which alarm clocks have changed since the last call to this.
1602 *
1603 * Do not call with a lock held. Only call from mHandler's thread.
1604 *
1605 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
1606 */
1607 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07001608 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001609 pendingUsers.clear();
1610
1611 synchronized (mLock) {
1612 final int N = mPendingSendNextAlarmClockChangedForUser.size();
1613 for (int i = 0; i < N; i++) {
1614 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
1615 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
1616 }
1617 mPendingSendNextAlarmClockChangedForUser.clear();
1618 }
1619
1620 final int N = pendingUsers.size();
1621 for (int i = 0; i < N; i++) {
1622 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001623 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001624 Settings.System.putStringForUser(getContext().getContentResolver(),
1625 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01001626 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02001627 userId);
1628
1629 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
1630 new UserHandle(userId));
1631 }
1632 }
1633
1634 /**
1635 * Formats an alarm like platform/packages/apps/DeskClock used to.
1636 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01001637 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
1638 int userId) {
1639 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02001640 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
1641 return (info == null) ? "" :
1642 DateFormat.format(pattern, info.getTriggerTime()).toString();
1643 }
1644
Adam Lesinski182f73f2013-12-05 16:48:06 -08001645 void rescheduleKernelAlarmsLocked() {
1646 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
1647 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001648 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001649 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001650 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001651 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07001652 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001653 mNextWakeup = firstWakeup.start;
1654 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001655 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001656 if (firstBatch != firstWakeup) {
1657 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001658 }
1659 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001660 if (mPendingNonWakeupAlarms.size() > 0) {
1661 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
1662 nextNonWakeup = mNextNonWakeupDeliveryTime;
1663 }
1664 }
Prashant Malani753e9e02015-06-10 17:43:49 -07001665 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001666 mNextNonWakeup = nextNonWakeup;
1667 setLocked(ELAPSED_REALTIME, nextNonWakeup);
1668 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001669 }
1670
Susheel Yadagiri6837e452015-07-09 13:01:39 -07001671 boolean checkReleaseWakeLock() {
1672 if (mTriggeredUids.size() == 0 || mBlockedUids.size() == 0)
1673 return false;
1674
1675 int uid;
1676 for (int i = 0; i < mTriggeredUids.size(); i++) {
1677 uid = mTriggeredUids.get(i);
1678 if (!mBlockedUids.contains(uid)) {
1679 return false;
1680 }
1681 }
1682 return true;
1683 }
1684
Adam Lesinski182f73f2013-12-05 16:48:06 -08001685 private void removeLocked(PendingIntent operation) {
1686 boolean didRemove = false;
1687 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1688 Batch b = mAlarmBatches.get(i);
1689 didRemove |= b.remove(operation);
1690 if (b.size() == 0) {
1691 mAlarmBatches.remove(i);
1692 }
1693 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001694 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1695 if (mPendingWhileIdleAlarms.get(i).operation.equals(operation)) {
1696 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1697 mPendingWhileIdleAlarms.remove(i);
1698 }
1699 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001700
1701 if (didRemove) {
1702 if (DEBUG_BATCH) {
1703 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
1704 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001705 boolean restorePending = false;
1706 if (mPendingIdleUntil != null && mPendingIdleUntil.operation.equals(operation)) {
1707 mPendingIdleUntil = null;
1708 restorePending = true;
1709 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001710 if (mNextWakeFromIdle != null && mNextWakeFromIdle.operation.equals(operation)) {
1711 mNextWakeFromIdle = null;
1712 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001713 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001714 if (restorePending) {
1715 restorePendingWhileIdleAlarmsLocked();
1716 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001717 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001718 }
1719 }
1720
1721 void removeLocked(String packageName) {
1722 boolean didRemove = false;
1723 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1724 Batch b = mAlarmBatches.get(i);
1725 didRemove |= b.remove(packageName);
1726 if (b.size() == 0) {
1727 mAlarmBatches.remove(i);
1728 }
1729 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001730 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1731 if (mPendingWhileIdleAlarms.get(i).operation.getTargetPackage().equals(packageName)) {
1732 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1733 mPendingWhileIdleAlarms.remove(i);
1734 }
1735 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001736
1737 if (didRemove) {
1738 if (DEBUG_BATCH) {
1739 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1740 }
1741 rebatchAllAlarmsLocked(true);
1742 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001743 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001744 }
1745 }
1746
1747 void removeUserLocked(int userHandle) {
1748 boolean didRemove = false;
1749 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1750 Batch b = mAlarmBatches.get(i);
1751 didRemove |= b.remove(userHandle);
1752 if (b.size() == 0) {
1753 mAlarmBatches.remove(i);
1754 }
1755 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001756 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1757 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).operation.getCreatorUid())
1758 == userHandle) {
1759 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1760 mPendingWhileIdleAlarms.remove(i);
1761 }
1762 }
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07001763 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
1764 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
1765 mLastAllowWhileIdleDispatch.removeAt(i);
1766 }
1767 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001768
1769 if (didRemove) {
1770 if (DEBUG_BATCH) {
1771 Slog.v(TAG, "remove(user) changed bounds; rebatching");
1772 }
1773 rebatchAllAlarmsLocked(true);
1774 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001775 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001776 }
1777 }
1778
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001779 void interactiveStateChangedLocked(boolean interactive) {
1780 if (mInteractive != interactive) {
1781 mInteractive = interactive;
1782 final long nowELAPSED = SystemClock.elapsedRealtime();
1783 if (interactive) {
1784 if (mPendingNonWakeupAlarms.size() > 0) {
1785 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1786 mTotalDelayTime += thisDelayTime;
1787 if (mMaxDelayTime < thisDelayTime) {
1788 mMaxDelayTime = thisDelayTime;
1789 }
1790 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
1791 mPendingNonWakeupAlarms.clear();
1792 }
1793 if (mNonInteractiveStartTime > 0) {
1794 long dur = nowELAPSED - mNonInteractiveStartTime;
1795 if (dur > mNonInteractiveTime) {
1796 mNonInteractiveTime = dur;
1797 }
1798 }
1799 } else {
1800 mNonInteractiveStartTime = nowELAPSED;
1801 }
1802 }
1803 }
1804
Adam Lesinski182f73f2013-12-05 16:48:06 -08001805 boolean lookForPackageLocked(String packageName) {
1806 for (int i = 0; i < mAlarmBatches.size(); i++) {
1807 Batch b = mAlarmBatches.get(i);
1808 if (b.hasPackage(packageName)) {
1809 return true;
1810 }
1811 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001812 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
1813 if (mPendingWhileIdleAlarms.get(i).operation.getTargetPackage().equals(packageName)) {
1814 return true;
1815 }
1816 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001817 return false;
1818 }
1819
1820 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001821 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001822 // The kernel never triggers alarms with negative wakeup times
1823 // so we ensure they are positive.
1824 long alarmSeconds, alarmNanoseconds;
1825 if (when < 0) {
1826 alarmSeconds = 0;
1827 alarmNanoseconds = 0;
1828 } else {
1829 alarmSeconds = when / 1000;
1830 alarmNanoseconds = (when % 1000) * 1000 * 1000;
1831 }
1832
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001833 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001834 } else {
1835 Message msg = Message.obtain();
1836 msg.what = ALARM_EVENT;
1837
1838 mHandler.removeMessages(ALARM_EVENT);
1839 mHandler.sendMessageAtTime(msg, when);
1840 }
1841 }
1842
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001843 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001844 String prefix, String label, long nowRTC, long nowELAPSED, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 for (int i=list.size()-1; i>=0; i--) {
1846 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001847 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1848 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001849 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850 }
1851 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001852
1853 private static final String labelForType(int type) {
1854 switch (type) {
1855 case RTC: return "RTC";
1856 case RTC_WAKEUP : return "RTC_WAKEUP";
1857 case ELAPSED_REALTIME : return "ELAPSED";
1858 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
1859 default:
1860 break;
1861 }
1862 return "--unknown--";
1863 }
1864
1865 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001866 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001867 for (int i=list.size()-1; i>=0; i--) {
1868 Alarm a = list.get(i);
1869 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001870 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1871 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001872 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001873 }
1874 }
1875
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001876 private native long init();
1877 private native void close(long nativeData);
1878 private native void set(long nativeData, int type, long seconds, long nanoseconds);
1879 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08001880 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001881 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001882
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001883 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001884 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001885 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001886 // batches are temporally sorted, so we need only pull from the
1887 // start of the list until we either empty it or hit a batch
1888 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07001889 while (mAlarmBatches.size() > 0) {
1890 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001891 if (batch.start > nowELAPSED) {
1892 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 break;
1894 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001895
Christopher Tatee0a22b32013-07-11 14:43:13 -07001896 // We will (re)schedule some alarms now; don't let that interfere
1897 // with delivery of this current batch
1898 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001899
Christopher Tatee0a22b32013-07-11 14:43:13 -07001900 final int N = batch.size();
1901 for (int i = 0; i < N; i++) {
1902 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07001903
1904 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1905 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
1906 // schedule such alarms.
1907 long lastTime = mLastAllowWhileIdleDispatch.get(alarm.uid, 0);
1908 long minTime = lastTime + mAllowWhileIdleMinTime;
1909 if (nowELAPSED < minTime) {
1910 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
1911 // alarm went off for this app. Reschedule the alarm to be in the
1912 // correct time period.
1913 alarm.whenElapsed = minTime;
1914 if (alarm.maxWhenElapsed < minTime) {
1915 alarm.maxWhenElapsed = minTime;
1916 }
1917 setImplLocked(alarm, true, false);
1918 continue;
1919 }
1920 }
1921
Christopher Tatee0a22b32013-07-11 14:43:13 -07001922 alarm.count = 1;
1923 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001924 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1925 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
1926 alarm.tag);
1927 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001928 if (mPendingIdleUntil == alarm) {
1929 mPendingIdleUntil = null;
1930 rebatchAllAlarmsLocked(false);
1931 restorePendingWhileIdleAlarmsLocked();
1932 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001933 if (mNextWakeFromIdle == alarm) {
1934 mNextWakeFromIdle = null;
1935 rebatchAllAlarmsLocked(false);
1936 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001937
1938 // Recurring alarms may have passed several alarm intervals while the
1939 // phone was asleep or off, so pass a trigger count when sending them.
1940 if (alarm.repeatInterval > 0) {
1941 // this adjustment will be zero if we're late by
1942 // less than one full repeat interval
1943 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
1944
1945 // Also schedule its next recurrence
1946 final long delta = alarm.count * alarm.repeatInterval;
1947 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07001948 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07001949 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001950 alarm.repeatInterval, alarm.operation, alarm.flags, true,
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07001951 alarm.workSource, alarm.alarmClock, alarm.uid);
Christopher Tate864d42e2014-12-02 11:48:53 -08001952 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001953
Christopher Tate864d42e2014-12-02 11:48:53 -08001954 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001955 hasWakeup = true;
1956 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001957
1958 // We removed an alarm clock. Let the caller recompute the next alarm clock.
1959 if (alarm.alarmClock != null) {
1960 mNextAlarmClockMayChange = true;
1961 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07001962 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001963 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001964
Christopher Tate1590f1e2014-10-02 17:27:57 -07001965 // This is a new alarm delivery set; bump the sequence number to indicate that
1966 // all apps' alarm delivery classes should be recalculated.
1967 mCurrentSeq++;
1968 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001969 Collections.sort(triggerList, mAlarmDispatchComparator);
1970
1971 if (localLOGV) {
1972 for (int i=0; i<triggerList.size(); i++) {
1973 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
1974 }
1975 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001976
1977 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980 /**
1981 * This Comparator sorts Alarms into increasing time order.
1982 */
1983 public static class IncreasingTimeOrder implements Comparator<Alarm> {
1984 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09001985 long when1 = a1.whenElapsed;
1986 long when2 = a2.whenElapsed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 if (when1 - when2 > 0) {
1988 return 1;
1989 }
1990 if (when1 - when2 < 0) {
1991 return -1;
1992 }
1993 return 0;
1994 }
1995 }
1996
1997 private static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001998 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001999 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002000 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002001 public final PendingIntent operation;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002002 public final String tag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002003 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002004 public final int flags;
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07002005 public final AlarmManager.AlarmClockInfo alarmClock;
2006 public final int uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 public int count;
2008 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07002009 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002010 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002011 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002012 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07002013 public PriorityClass priorityClass;
Susheel Yadagiri6837e452015-07-09 13:01:39 -07002014 public int pid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002015
Christopher Tate3e04b472013-10-21 17:51:31 -07002016 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002017 long _interval, PendingIntent _op, WorkSource _ws, int _flags,
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07002018 AlarmManager.AlarmClockInfo _info, int _uid) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002019 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002020 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002021 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
2022 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002023 when = _when;
2024 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07002025 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002026 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002027 repeatInterval = _interval;
2028 operation = _op;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002029 tag = makeTag(_op, _type);
David Christieebe51fc2013-07-26 13:23:29 -07002030 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002031 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002032 alarmClock = _info;
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07002033 uid = _uid;
Susheel Yadagiri6837e452015-07-09 13:01:39 -07002034 pid = Binder.getCallingPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002036
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002037 public static String makeTag(PendingIntent pi, int type) {
2038 return pi.getTag(type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
2039 ? "*walarm*:" : "*alarm*:");
2040 }
2041
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002042 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002043 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002044 StringBuilder sb = new StringBuilder(128);
2045 sb.append("Alarm{");
2046 sb.append(Integer.toHexString(System.identityHashCode(this)));
2047 sb.append(" type ");
2048 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002049 sb.append(" when ");
2050 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002051 sb.append(" ");
2052 sb.append(operation.getTargetPackage());
2053 sb.append('}');
2054 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002055 }
2056
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002057 public void dump(PrintWriter pw, String prefix, long nowRTC, long nowELAPSED,
2058 SimpleDateFormat sdf) {
2059 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
2060 pw.print(prefix); pw.print("tag="); pw.println(tag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002061 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002062 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
2063 nowELAPSED, pw);
2064 if (isRtc) {
2065 pw.print(" when="); pw.print(sdf.format(new Date(when)));
2066 } else {
2067 pw.print(" when="); TimeUtils.formatDuration(when, nowELAPSED, pw);
2068 }
2069 pw.println();
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07002070 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002071 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002072 pw.print(" count="); pw.print(count);
2073 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002074 if (alarmClock != null) {
2075 pw.print(prefix); pw.println("Alarm clock:");
2076 pw.print(prefix); pw.print(" triggerTime=");
2077 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
2078 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
2079 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002080 pw.print(prefix); pw.print("operation="); pw.println(operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081 }
2082 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002083
Christopher Tatee0a22b32013-07-11 14:43:13 -07002084 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
2085 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002086 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
2087 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002088 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07002089 break;
2090 }
2091
Christopher Tatee0a22b32013-07-11 14:43:13 -07002092 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002093 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
2094 Alarm a = b.alarms.get(nextAlarm);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002095 WakeupEvent e = new WakeupEvent(nowRTC,
2096 a.operation.getCreatorUid(),
2097 a.operation.getIntent().getAction());
2098 mRecentWakeups.add(e);
2099 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002100 }
2101 }
2102
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002103 long currentNonWakeupFuzzLocked(long nowELAPSED) {
2104 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
2105 if (timeSinceOn < 5*60*1000) {
2106 // If the screen has been off for 5 minutes, only delay by at most two minutes.
2107 return 2*60*1000;
2108 } else if (timeSinceOn < 30*60*1000) {
2109 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
2110 return 15*60*1000;
2111 } else {
2112 // Otherwise, we will delay by at most an hour.
2113 return 60*60*1000;
2114 }
2115 }
2116
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002117 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002118 if (duration < 15*60*1000) {
2119 // If the duration until the time is less than 15 minutes, the maximum fuzz
2120 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002121 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002122 } else if (duration < 90*60*1000) {
2123 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
2124 return 15*60*1000;
2125 } else {
2126 // Otherwise, we will fuzz by at most half an hour.
2127 return 30*60*1000;
2128 }
2129 }
2130
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002131 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
2132 if (mInteractive) {
2133 return false;
2134 }
2135 if (mLastAlarmDeliveryTime <= 0) {
2136 return false;
2137 }
minho.choo649acab2014-12-12 16:13:55 +09002138 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002139 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
2140 // and the next delivery time is in the past, then just deliver them all. This
2141 // avoids bugs where we get stuck in a loop trying to poll for alarms.
2142 return false;
2143 }
2144 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
2145 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
2146 }
2147
2148 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
2149 mLastAlarmDeliveryTime = nowELAPSED;
2150 for (int i=0; i<triggerList.size(); i++) {
2151 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07002152 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002153 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07002154 if (localLOGV) {
2155 Slog.v(TAG, "sending alarm " + alarm);
2156 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07002157 if (RECORD_ALARMS_IN_HISTORY) {
2158 if (alarm.workSource != null && alarm.workSource.size() > 0) {
2159 for (int wi=0; wi<alarm.workSource.size(); wi++) {
2160 ActivityManagerNative.noteAlarmStart(
2161 alarm.operation, alarm.workSource.get(wi), alarm.tag);
2162 }
2163 } else {
2164 ActivityManagerNative.noteAlarmStart(
2165 alarm.operation, -1, alarm.tag);
2166 }
2167 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002168 alarm.operation.send(getContext(), 0,
2169 mBackgroundIntent.putExtra(
2170 Intent.EXTRA_ALARM_COUNT, alarm.count),
Dianne Hackborna750a632015-06-16 17:18:23 -07002171 mResultReceiver, mHandler, null, allowWhileIdle ? mIdleOptions : null);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002172
2173 // we have an active broadcast so stay awake.
Susheel Yadagiri6837e452015-07-09 13:01:39 -07002174 if (mBroadcastRefCount == 0 || !mWakeLock.isHeld()) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002175 setWakelockWorkSource(alarm.operation, alarm.workSource,
2176 alarm.type, alarm.tag, true);
2177 mWakeLock.acquire();
2178 }
2179 final InFlight inflight = new InFlight(AlarmManagerService.this,
Susheel Yadagiri6837e452015-07-09 13:01:39 -07002180 alarm.operation,
2181 alarm.workSource,
2182 alarm.type, alarm.tag,
2183 nowELAPSED, alarm.uid);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002184 mInFlight.add(inflight);
2185 mBroadcastRefCount++;
Susheel Yadagiri6837e452015-07-09 13:01:39 -07002186 mTriggeredUids.add(new Integer(alarm.uid));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002187
Dianne Hackborna750a632015-06-16 17:18:23 -07002188 if (allowWhileIdle) {
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07002189 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
2190 mLastAllowWhileIdleDispatch.put(alarm.uid, nowELAPSED);
2191 }
2192
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002193 final BroadcastStats bs = inflight.mBroadcastStats;
2194 bs.count++;
2195 if (bs.nesting == 0) {
2196 bs.nesting = 1;
2197 bs.startTime = nowELAPSED;
2198 } else {
2199 bs.nesting++;
2200 }
2201 final FilterStats fs = inflight.mFilterStats;
2202 fs.count++;
2203 if (fs.nesting == 0) {
2204 fs.nesting = 1;
2205 fs.startTime = nowELAPSED;
2206 } else {
2207 fs.nesting++;
2208 }
2209 if (alarm.type == ELAPSED_REALTIME_WAKEUP
2210 || alarm.type == RTC_WAKEUP) {
2211 bs.numWakeup++;
2212 fs.numWakeup++;
2213 if (alarm.workSource != null && alarm.workSource.size() > 0) {
2214 for (int wi=0; wi<alarm.workSource.size(); wi++) {
2215 ActivityManagerNative.noteWakeupAlarm(
2216 alarm.operation, alarm.workSource.get(wi),
Dianne Hackborn1e383822015-04-10 14:02:33 -07002217 alarm.workSource.getName(wi), alarm.tag);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002218 }
2219 } else {
2220 ActivityManagerNative.noteWakeupAlarm(
Dianne Hackborn1e383822015-04-10 14:02:33 -07002221 alarm.operation, -1, null, alarm.tag);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002222 }
2223 }
2224 } catch (PendingIntent.CanceledException e) {
2225 if (alarm.repeatInterval > 0) {
2226 // This IntentSender is no longer valid, but this
2227 // is a repeating alarm, so toss the hoser.
2228 removeImpl(alarm.operation);
2229 }
2230 } catch (RuntimeException e) {
2231 Slog.w(TAG, "Failure sending alarm.", e);
2232 }
2233 }
2234 }
2235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002236 private class AlarmThread extends Thread
2237 {
2238 public AlarmThread()
2239 {
2240 super("AlarmManager");
2241 }
2242
2243 public void run()
2244 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002245 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002247 while (true)
2248 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002249 int result = waitForAlarm(mNativeData);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002250
2251 triggerList.clear();
2252
Dianne Hackbornc3527222015-05-13 14:03:20 -07002253 final long nowRTC = System.currentTimeMillis();
2254 final long nowELAPSED = SystemClock.elapsedRealtime();
2255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002256 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002257 // The kernel can give us spurious time change notifications due to
2258 // small adjustments it makes internally; we want to filter those out.
2259 final long lastTimeChangeClockTime;
2260 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07002261 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002262 lastTimeChangeClockTime = mLastTimeChangeClockTime;
2263 expectedClockTime = lastTimeChangeClockTime
2264 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07002265 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002266 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-500)
2267 || nowRTC > (expectedClockTime+500)) {
2268 // The change is by at least +/- 500 ms (or this is the first change),
2269 // let's do it!
2270 if (DEBUG_BATCH) {
2271 Slog.v(TAG, "Time changed notification from kernel; rebatching");
2272 }
2273 removeImpl(mTimeTickSender);
2274 rebatchAllAlarms();
2275 mClockReceiver.scheduleTimeTickEvent();
2276 synchronized (mLock) {
2277 mNumTimeChanged++;
2278 mLastTimeChangeClockTime = nowRTC;
2279 mLastTimeChangeRealtime = nowELAPSED;
2280 }
2281 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
2282 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
2283 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2284 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
2285
2286 // The world has changed on us, so we need to re-evaluate alarms
2287 // regardless of whether the kernel has told us one went off.
2288 result |= IS_WAKEUP_MASK;
2289 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002291
Dianne Hackbornc3527222015-05-13 14:03:20 -07002292 if (result != TIME_CHANGED_MASK) {
2293 // If this was anything besides just a time change, then figure what if
2294 // anything to do about alarms.
2295 synchronized (mLock) {
2296 if (localLOGV) Slog.v(
2297 TAG, "Checking for alarms... rtc=" + nowRTC
2298 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07002299
Dianne Hackbornc3527222015-05-13 14:03:20 -07002300 if (WAKEUP_STATS) {
2301 if ((result & IS_WAKEUP_MASK) != 0) {
2302 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
2303 int n = 0;
2304 for (WakeupEvent event : mRecentWakeups) {
2305 if (event.when > newEarliest) break;
2306 n++; // number of now-stale entries at the list head
2307 }
2308 for (int i = 0; i < n; i++) {
2309 mRecentWakeups.remove();
2310 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002311
Dianne Hackbornc3527222015-05-13 14:03:20 -07002312 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002313 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002314 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002315
2316 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2317 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
2318 // if there are no wakeup alarms and the screen is off, we can
2319 // delay what we have so far until the future.
2320 if (mPendingNonWakeupAlarms.size() == 0) {
2321 mStartCurrentDelayTime = nowELAPSED;
2322 mNextNonWakeupDeliveryTime = nowELAPSED
2323 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
2324 }
2325 mPendingNonWakeupAlarms.addAll(triggerList);
2326 mNumDelayedAlarms += triggerList.size();
2327 rescheduleKernelAlarmsLocked();
2328 updateNextAlarmClockLocked();
2329 } else {
2330 // now deliver the alarm intents; if there are pending non-wakeup
2331 // alarms, we need to merge them in to the list. note we don't
2332 // just deliver them first because we generally want non-wakeup
2333 // alarms delivered after wakeup alarms.
2334 rescheduleKernelAlarmsLocked();
2335 updateNextAlarmClockLocked();
2336 if (mPendingNonWakeupAlarms.size() > 0) {
2337 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
2338 triggerList.addAll(mPendingNonWakeupAlarms);
2339 Collections.sort(triggerList, mAlarmDispatchComparator);
2340 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2341 mTotalDelayTime += thisDelayTime;
2342 if (mMaxDelayTime < thisDelayTime) {
2343 mMaxDelayTime = thisDelayTime;
2344 }
2345 mPendingNonWakeupAlarms.clear();
2346 }
2347 deliverAlarmsLocked(triggerList, nowELAPSED);
2348 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002349 }
2350 }
2351 }
2352 }
2353 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002354
David Christieebe51fc2013-07-26 13:23:29 -07002355 /**
2356 * Attribute blame for a WakeLock.
2357 * @param pi PendingIntent to attribute blame to if ws is null.
2358 * @param ws WorkSource to attribute blame.
2359 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002360 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
2361 boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07002362 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002363 final boolean unimportant = pi == mTimeTickSender;
2364 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002365 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002366 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002367 } else {
2368 mWakeLock.setHistoryTag(null);
2369 }
2370 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07002371 if (ws != null) {
2372 mWakeLock.setWorkSource(ws);
2373 return;
2374 }
2375
Christopher Tatec4a07d12012-04-06 14:19:13 -07002376 final int uid = ActivityManagerNative.getDefault()
2377 .getUidForIntentSender(pi.getTarget());
2378 if (uid >= 0) {
2379 mWakeLock.setWorkSource(new WorkSource(uid));
2380 return;
2381 }
Susheel Yadagiri6837e452015-07-09 13:01:39 -07002382 // Something went wrong; fall back to attributing the lock to the OS
2383 mWakeLock.setWorkSource(null);
Christopher Tatec4a07d12012-04-06 14:19:13 -07002384 } catch (Exception e) {
2385 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002386 }
2387
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002388 private class AlarmHandler extends Handler {
2389 public static final int ALARM_EVENT = 1;
2390 public static final int MINUTE_CHANGE_EVENT = 2;
2391 public static final int DATE_CHANGE_EVENT = 3;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002392 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002393
2394 public AlarmHandler() {
2395 }
2396
2397 public void handleMessage(Message msg) {
2398 if (msg.what == ALARM_EVENT) {
2399 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2400 synchronized (mLock) {
2401 final long nowRTC = System.currentTimeMillis();
Christopher Tatee0a22b32013-07-11 14:43:13 -07002402 final long nowELAPSED = SystemClock.elapsedRealtime();
2403 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002404 updateNextAlarmClockLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002405 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002406
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002407 // now trigger the alarms without the lock held
Dianne Hackborn390517b2013-05-30 15:03:32 -07002408 for (int i=0; i<triggerList.size(); i++) {
2409 Alarm alarm = triggerList.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002410 try {
2411 alarm.operation.send();
2412 } catch (PendingIntent.CanceledException e) {
2413 if (alarm.repeatInterval > 0) {
2414 // This IntentSender is no longer valid, but this
2415 // is a repeating alarm, so toss the hoser.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002416 removeImpl(alarm.operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002417 }
2418 }
2419 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002420 } else if (msg.what == SEND_NEXT_ALARM_CLOCK_CHANGED) {
2421 sendNextAlarmClockChanged();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002422 }
2423 }
2424 }
2425
2426 class ClockReceiver extends BroadcastReceiver {
2427 public ClockReceiver() {
2428 IntentFilter filter = new IntentFilter();
2429 filter.addAction(Intent.ACTION_TIME_TICK);
2430 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002431 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 }
2433
2434 @Override
2435 public void onReceive(Context context, Intent intent) {
2436 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07002437 if (DEBUG_BATCH) {
2438 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
2439 }
2440 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002441 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
2442 // Since the kernel does not keep track of DST, we need to
2443 // reset the TZ information at the beginning of each day
2444 // based off of the current Zone gmt offset + userspace tracked
2445 // daylight savings information.
2446 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02002447 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002448 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07002449 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450 }
2451 }
2452
2453 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07002454 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09002455 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07002456
2457 // Schedule this event for the amount of time that it would take to get to
2458 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09002459 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07002460
David Christieebe51fc2013-07-26 13:23:29 -07002461 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002462 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07002463 0, mTimeTickSender, AlarmManager.FLAG_STANDALONE, workSource, null,
2464 Process.myUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002465 }
Christopher Tate385e4982013-07-23 18:22:29 -07002466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002467 public void scheduleDateChangedEvent() {
2468 Calendar calendar = Calendar.getInstance();
2469 calendar.setTimeInMillis(System.currentTimeMillis());
2470 calendar.set(Calendar.HOUR, 0);
2471 calendar.set(Calendar.MINUTE, 0);
2472 calendar.set(Calendar.SECOND, 0);
2473 calendar.set(Calendar.MILLISECOND, 0);
2474 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07002475
2476 final WorkSource workSource = null; // Let system take blame for date change events.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002477 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender,
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07002478 AlarmManager.FLAG_STANDALONE, workSource, null, Process.myUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002479 }
2480 }
2481
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002482 class InteractiveStateReceiver extends BroadcastReceiver {
2483 public InteractiveStateReceiver() {
2484 IntentFilter filter = new IntentFilter();
2485 filter.addAction(Intent.ACTION_SCREEN_OFF);
2486 filter.addAction(Intent.ACTION_SCREEN_ON);
2487 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
2488 getContext().registerReceiver(this, filter);
2489 }
2490
2491 @Override
2492 public void onReceive(Context context, Intent intent) {
2493 synchronized (mLock) {
2494 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
2495 }
2496 }
2497 }
2498
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499 class UninstallReceiver extends BroadcastReceiver {
2500 public UninstallReceiver() {
2501 IntentFilter filter = new IntentFilter();
2502 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2503 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002504 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002505 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08002506 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002507 // Register for events related to sdcard installation.
2508 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08002509 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002510 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07002511 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002512 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002513 }
2514
2515 @Override
2516 public void onReceive(Context context, Intent intent) {
2517 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002518 String action = intent.getAction();
2519 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002520 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
2521 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
2522 for (String packageName : pkgList) {
2523 if (lookForPackageLocked(packageName)) {
2524 setResultCode(Activity.RESULT_OK);
2525 return;
2526 }
2527 }
2528 return;
2529 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002530 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002531 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
2532 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
2533 if (userHandle >= 0) {
2534 removeUserLocked(userHandle);
2535 }
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07002536 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
2537 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
2538 if (uid >= 0) {
2539 mLastAllowWhileIdleDispatch.delete(uid);
2540 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002541 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08002542 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
2543 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
2544 // This package is being updated; don't kill its alarms.
2545 return;
2546 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002547 Uri data = intent.getData();
2548 if (data != null) {
2549 String pkg = data.getSchemeSpecificPart();
2550 if (pkg != null) {
2551 pkgList = new String[]{pkg};
2552 }
2553 }
2554 }
2555 if (pkgList != null && (pkgList.length > 0)) {
2556 for (String pkg : pkgList) {
2557 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07002558 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002559 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
2560 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
2561 if (uidStats.remove(pkg) != null) {
2562 if (uidStats.size() <= 0) {
2563 mBroadcastStats.removeAt(i);
2564 }
2565 }
2566 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002567 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002568 }
2569 }
2570 }
2571 }
2572
2573 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002574 String pkg = pi.getCreatorPackage();
2575 int uid = pi.getCreatorUid();
2576 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
2577 if (uidStats == null) {
2578 uidStats = new ArrayMap<String, BroadcastStats>();
2579 mBroadcastStats.put(uid, uidStats);
2580 }
2581 BroadcastStats bs = uidStats.get(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002582 if (bs == null) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002583 bs = new BroadcastStats(uid, pkg);
2584 uidStats.put(pkg, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002585 }
2586 return bs;
2587 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 class ResultReceiver implements PendingIntent.OnFinished {
2590 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
2591 String resultData, Bundle resultExtras) {
2592 synchronized (mLock) {
Susheel Yadagiri6837e452015-07-09 13:01:39 -07002593 int uid = 0;
Dianne Hackborn81038902012-11-26 17:04:09 -08002594 InFlight inflight = null;
2595 for (int i=0; i<mInFlight.size(); i++) {
2596 if (mInFlight.get(i).mPendingIntent == pi) {
Susheel Yadagiri6837e452015-07-09 13:01:39 -07002597 uid = mInFlight.get(i).mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -08002598 inflight = mInFlight.remove(i);
2599 break;
2600 }
2601 }
2602 if (inflight != null) {
2603 final long nowELAPSED = SystemClock.elapsedRealtime();
2604 BroadcastStats bs = inflight.mBroadcastStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002605 bs.nesting--;
2606 if (bs.nesting <= 0) {
2607 bs.nesting = 0;
Dianne Hackborn81038902012-11-26 17:04:09 -08002608 bs.aggregateTime += nowELAPSED - bs.startTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002609 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002610 FilterStats fs = inflight.mFilterStats;
2611 fs.nesting--;
2612 if (fs.nesting <= 0) {
2613 fs.nesting = 0;
2614 fs.aggregateTime += nowELAPSED - fs.startTime;
2615 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07002616 if (RECORD_ALARMS_IN_HISTORY) {
2617 if (inflight.mWorkSource != null && inflight.mWorkSource.size() > 0) {
2618 for (int wi=0; wi<inflight.mWorkSource.size(); wi++) {
2619 ActivityManagerNative.noteAlarmFinish(
2620 pi, inflight.mWorkSource.get(wi), inflight.mTag);
2621 }
2622 } else {
2623 ActivityManagerNative.noteAlarmFinish(
2624 pi, -1, inflight.mTag);
2625 }
2626 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002627 } else {
2628 mLog.w("No in-flight alarm for " + pi + " " + intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002629 }
2630 mBroadcastRefCount--;
Susheel Yadagiri6837e452015-07-09 13:01:39 -07002631 mTriggeredUids.remove(new Integer(uid));
2632
2633 if (checkReleaseWakeLock()) {
2634 if (mWakeLock.isHeld()) {
2635 mWakeLock.release();
2636 if (localLOGV) Slog.v(TAG, "AM WakeLock Released Internally onSendFinish");
2637 }
2638 }
2639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002640 if (mBroadcastRefCount == 0) {
Susheel Yadagiri6837e452015-07-09 13:01:39 -07002641 if (mWakeLock.isHeld()) {
2642 mWakeLock.release();
2643 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002644 if (mInFlight.size() > 0) {
2645 mLog.w("Finished all broadcasts with " + mInFlight.size()
2646 + " remaining inflights");
2647 for (int i=0; i<mInFlight.size(); i++) {
2648 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
2649 }
2650 mInFlight.clear();
2651 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002652 } else {
2653 // the next of our alarms is now in flight. reattribute the wakelock.
Dianne Hackborn81038902012-11-26 17:04:09 -08002654 if (mInFlight.size() > 0) {
David Christieebe51fc2013-07-26 13:23:29 -07002655 InFlight inFlight = mInFlight.get(0);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08002656 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002657 inFlight.mAlarmType, inFlight.mTag, false);
Christopher Tatec4a07d12012-04-06 14:19:13 -07002658 } else {
2659 // should never happen
Dianne Hackborn81038902012-11-26 17:04:09 -08002660 mLog.w("Alarm wakelock still held but sent queue empty");
Christopher Tatec4a07d12012-04-06 14:19:13 -07002661 mWakeLock.setWorkSource(null);
2662 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002663 }
2664 }
2665 }
2666 }
2667}