blob: 9de6f2ab4cd32aaa211904490c33a427dfa3deec [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;
Mao Jinlong77b0ec72015-08-31 17:25:04 +080078import static android.app.AlarmManager.RTC_POWEROFF_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -070079
Dianne Hackborn81038902012-11-26 17:04:09 -080080import com.android.internal.util.LocalLog;
81
Adam Lesinski182f73f2013-12-05 16:48:06 -080082class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -070083 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
84 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -080085 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -070086 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Mao Jinlong77b0ec72015-08-31 17:25:04 +080087 private static final int RTC_POWEROFF_WAKEUP_MASK = 1 << RTC_POWEROFF_WAKEUP;
Adam Lesinski182f73f2013-12-05 16:48:06 -080088 static final int TIME_CHANGED_MASK = 1 << 16;
Mao Jinlong77b0ec72015-08-31 17:25:04 +080089 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK
90 |RTC_POWEROFF_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -080091
Christopher Tatee0a22b32013-07-11 14:43:13 -070092 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -080093 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -080094
Adam Lesinski182f73f2013-12-05 16:48:06 -080095 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -080096 static final boolean localLOGV = false;
97 static final boolean DEBUG_BATCH = localLOGV || false;
98 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +020099 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700100 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800101 static final int ALARM_EVENT = 1;
102 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200103
Adam Lesinski182f73f2013-12-05 16:48:06 -0800104 static final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800106 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107
Adam Lesinski182f73f2013-12-05 16:48:06 -0800108 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700109
Adrian Roosc42a1e12014-07-07 23:35:53 +0200110 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT = new Intent(
111 AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED);
112
Adam Lesinski182f73f2013-12-05 16:48:06 -0800113 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800114
Adam Lesinski182f73f2013-12-05 16:48:06 -0800115 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800116
Susheel Yadagiri6837e452015-07-09 13:01:39 -0700117 private final ArrayList<Integer> mTriggeredUids = new ArrayList<Integer>();
118 private final ArrayList<Integer> mBlockedUids = new ArrayList<Integer>();
119
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800120 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800121 private long mNextWakeup;
Mao Jinlong77b0ec72015-08-31 17:25:04 +0800122 private long mNextRtcWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700123 private long mNextNonWakeup;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800124 int mBroadcastRefCount = 0;
125 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700126 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c2015-06-10 16:25:57 -0700127 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
128 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800129 final AlarmHandler mHandler = new AlarmHandler();
130 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700131 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132 private UninstallReceiver mUninstallReceiver;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800133 final ResultReceiver mResultReceiver = new ResultReceiver();
134 PendingIntent mTimeTickSender;
135 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700136 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700137 boolean mInteractive = true;
138 long mNonInteractiveStartTime;
139 long mNonInteractiveTime;
140 long mLastAlarmDeliveryTime;
141 long mStartCurrentDelayTime;
142 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700143 long mLastTimeChangeClockTime;
144 long mLastTimeChangeRealtime;
Dianne Hackborna750a632015-06-16 17:18:23 -0700145 long mAllowWhileIdleMinTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700146 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800147
Dianne Hackborn3d1933c2015-06-10 16:25:57 -0700148 /**
149 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
150 * used to determine the earliest we can dispatch the next such alarm.
151 */
152 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
153
Dianne Hackborna750a632015-06-16 17:18:23 -0700154 /**
155 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
156 */
157 Bundle mIdleOptions;
158
Jose Lima235510e2014-08-13 12:50:01 -0700159 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
160 new SparseArray<>();
161 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
162 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200163 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
164 new SparseBooleanArray();
165 private boolean mNextAlarmClockMayChange;
166
167 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700168 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
169 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200170
Dianne Hackborna750a632015-06-16 17:18:23 -0700171 /**
172 * All times are in milliseconds. These constants are kept synchronized with the system
173 * global Settings. Any access to this class or its fields should be done while
174 * holding the AlarmManagerService.mLock lock.
175 */
176 private final class Constants extends ContentObserver {
177 // Key names stored in the settings value.
178 private static final String KEY_MIN_FUTURITY = "min_futurity";
179 private static final String KEY_MIN_INTERVAL = "min_interval";
180 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
181 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
182 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
183 = "allow_while_idle_whitelist_duration";
184
185 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
186 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tate30396782015-08-27 15:57:57 -0700187 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborna750a632015-06-16 17:18:23 -0700188 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 15*60*1000;
189 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
190
191 // Minimum futurity of a new alarm
192 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
193
194 // Minimum alarm recurrence interval
195 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
196
197 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
198 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
199
200 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
201 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
202
203 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
204 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
205 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
206
207 private ContentResolver mResolver;
208 private final KeyValueListParser mParser = new KeyValueListParser(',');
209 private long mLastAllowWhileIdleWhitelistDuration = -1;
210
211 public Constants(Handler handler) {
212 super(handler);
213 updateAllowWhileIdleMinTimeLocked();
214 updateAllowWhileIdleWhitelistDurationLocked();
215 }
216
217 public void start(ContentResolver resolver) {
218 mResolver = resolver;
219 mResolver.registerContentObserver(Settings.Global.getUriFor(
220 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
221 updateConstants();
222 }
223
224 public void updateAllowWhileIdleMinTimeLocked() {
225 mAllowWhileIdleMinTime = mPendingIdleUntil != null
226 ? ALLOW_WHILE_IDLE_LONG_TIME : ALLOW_WHILE_IDLE_SHORT_TIME;
227 }
228
229 public void updateAllowWhileIdleWhitelistDurationLocked() {
230 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
231 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
232 BroadcastOptions opts = BroadcastOptions.makeBasic();
233 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
234 mIdleOptions = opts.toBundle();
235 }
236 }
237
238 @Override
239 public void onChange(boolean selfChange, Uri uri) {
240 updateConstants();
241 }
242
243 private void updateConstants() {
244 synchronized (mLock) {
245 try {
246 mParser.setString(Settings.Global.getString(mResolver,
247 Settings.Global.ALARM_MANAGER_CONSTANTS));
248 } catch (IllegalArgumentException e) {
249 // Failed to parse the settings string, log this and move on
250 // with defaults.
251 Slog.e(TAG, "Bad device idle settings", e);
252 }
253
254 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
255 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
256 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
257 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
258 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
259 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
260 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
261 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
262 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
263
264 updateAllowWhileIdleMinTimeLocked();
265 updateAllowWhileIdleWhitelistDurationLocked();
266 }
267 }
268
269 void dump(PrintWriter pw) {
270 pw.println(" Settings:");
271
272 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
273 TimeUtils.formatDuration(MIN_FUTURITY, pw);
274 pw.println();
275
276 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
277 TimeUtils.formatDuration(MIN_INTERVAL, pw);
278 pw.println();
279
280 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
281 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
282 pw.println();
283
284 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
285 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
286 pw.println();
287
288 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
289 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
290 pw.println();
291 }
292 }
293
294 final Constants mConstants;
295
Christopher Tate1590f1e2014-10-02 17:27:57 -0700296 // Alarm delivery ordering bookkeeping
297 static final int PRIO_TICK = 0;
298 static final int PRIO_WAKEUP = 1;
299 static final int PRIO_NORMAL = 2;
300
Dianne Hackborna750a632015-06-16 17:18:23 -0700301 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700302 int seq;
303 int priority;
304
305 PriorityClass() {
306 seq = mCurrentSeq - 1;
307 priority = PRIO_NORMAL;
308 }
309 }
310
Dianne Hackborna750a632015-06-16 17:18:23 -0700311 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700312 int mCurrentSeq = 0;
313
Dianne Hackborna750a632015-06-16 17:18:23 -0700314 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700315 public long when;
316 public int uid;
317 public String action;
318
319 public WakeupEvent(long theTime, int theUid, String theAction) {
320 when = theTime;
321 uid = theUid;
322 action = theAction;
323 }
324 }
325
Adam Lesinski182f73f2013-12-05 16:48:06 -0800326 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
327 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700328
Adrian Roosc42a1e12014-07-07 23:35:53 +0200329 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700330 long start; // These endpoints are always in ELAPSED
331 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700332 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700333
334 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
335
336 Batch() {
337 start = 0;
338 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700339 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700340 }
341
342 Batch(Alarm seed) {
343 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700344 end = seed.maxWhenElapsed;
345 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700346 alarms.add(seed);
347 }
348
349 int size() {
350 return alarms.size();
351 }
352
353 Alarm get(int index) {
354 return alarms.get(index);
355 }
356
Mao Jinlong77b0ec72015-08-31 17:25:04 +0800357 long getWhenByElapsedTime(long whenElapsed) {
358 for(int i=0;i< alarms.size();i++) {
359 if(alarms.get(i).whenElapsed == whenElapsed)
360 return alarms.get(i).when;
361 }
362 return 0;
363 }
364
Christopher Tatee0a22b32013-07-11 14:43:13 -0700365 boolean canHold(long whenElapsed, long maxWhen) {
366 return (end >= whenElapsed) && (start <= maxWhen);
367 }
368
369 boolean add(Alarm alarm) {
370 boolean newStart = false;
371 // narrows the batch if necessary; presumes that canHold(alarm) is true
372 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
373 if (index < 0) {
374 index = 0 - index - 1;
375 }
376 alarms.add(index, alarm);
377 if (DEBUG_BATCH) {
378 Slog.v(TAG, "Adding " + alarm + " to " + this);
379 }
380 if (alarm.whenElapsed > start) {
381 start = alarm.whenElapsed;
382 newStart = true;
383 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700384 if (alarm.maxWhenElapsed < end) {
385 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700386 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700387 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700388
389 if (DEBUG_BATCH) {
390 Slog.v(TAG, " => now " + this);
391 }
392 return newStart;
393 }
394
395 boolean remove(final PendingIntent operation) {
396 boolean didRemove = false;
397 long newStart = 0; // recalculate endpoints as we go
398 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700399 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700400 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700401 Alarm alarm = alarms.get(i);
402 if (alarm.operation.equals(operation)) {
403 alarms.remove(i);
404 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200405 if (alarm.alarmClock != null) {
406 mNextAlarmClockMayChange = true;
407 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700408 } else {
409 if (alarm.whenElapsed > newStart) {
410 newStart = alarm.whenElapsed;
411 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700412 if (alarm.maxWhenElapsed < newEnd) {
413 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700414 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700415 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700416 i++;
417 }
418 }
419 if (didRemove) {
420 // commit the new batch bounds
421 start = newStart;
422 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700423 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700424 }
425 return didRemove;
426 }
427
428 boolean remove(final String packageName) {
429 boolean didRemove = false;
430 long newStart = 0; // recalculate endpoints as we go
431 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700432 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700433 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700434 Alarm alarm = alarms.get(i);
435 if (alarm.operation.getTargetPackage().equals(packageName)) {
436 alarms.remove(i);
437 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200438 if (alarm.alarmClock != null) {
439 mNextAlarmClockMayChange = true;
440 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700441 } else {
442 if (alarm.whenElapsed > newStart) {
443 newStart = alarm.whenElapsed;
444 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700445 if (alarm.maxWhenElapsed < newEnd) {
446 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700447 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700448 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700449 i++;
450 }
451 }
452 if (didRemove) {
453 // commit the new batch bounds
454 start = newStart;
455 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700456 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700457 }
458 return didRemove;
459 }
460
461 boolean remove(final int userHandle) {
462 boolean didRemove = false;
463 long newStart = 0; // recalculate endpoints as we go
464 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700465 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700466 Alarm alarm = alarms.get(i);
467 if (UserHandle.getUserId(alarm.operation.getCreatorUid()) == userHandle) {
468 alarms.remove(i);
469 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200470 if (alarm.alarmClock != null) {
471 mNextAlarmClockMayChange = true;
472 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700473 } else {
474 if (alarm.whenElapsed > newStart) {
475 newStart = alarm.whenElapsed;
476 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700477 if (alarm.maxWhenElapsed < newEnd) {
478 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700479 }
480 i++;
481 }
482 }
483 if (didRemove) {
484 // commit the new batch bounds
485 start = newStart;
486 end = newEnd;
487 }
488 return didRemove;
489 }
490
491 boolean hasPackage(final String packageName) {
492 final int N = alarms.size();
493 for (int i = 0; i < N; i++) {
494 Alarm a = alarms.get(i);
495 if (a.operation.getTargetPackage().equals(packageName)) {
496 return true;
497 }
498 }
499 return false;
500 }
501
502 boolean hasWakeups() {
503 final int N = alarms.size();
504 for (int i = 0; i < N; i++) {
505 Alarm a = alarms.get(i);
506 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
507 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
508 return true;
509 }
510 }
511 return false;
512 }
513
Mao Jinlong77b0ec72015-08-31 17:25:04 +0800514 boolean isRtcPowerOffWakeup() {
515 final int N = alarms.size();
516 for (int i = 0; i < N; i++) {
517 Alarm a = alarms.get(i);
518 if (a.type == RTC_POWEROFF_WAKEUP) {
519 return true;
520 }
521 }
522 return false;
523 }
524
Christopher Tatee0a22b32013-07-11 14:43:13 -0700525 @Override
526 public String toString() {
527 StringBuilder b = new StringBuilder(40);
528 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
529 b.append(" num="); b.append(size());
530 b.append(" start="); b.append(start);
531 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700532 if (flags != 0) {
533 b.append(" flgs=0x");
534 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700535 }
536 b.append('}');
537 return b.toString();
538 }
539 }
540
541 static class BatchTimeOrder implements Comparator<Batch> {
542 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800543 long when1 = b1.start;
544 long when2 = b2.start;
545 if (when1 - when2 > 0) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700546 return 1;
547 }
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800548 if (when1 - when2 < 0) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700549 return -1;
550 }
551 return 0;
552 }
553 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800554
555 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
556 @Override
557 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700558 // priority class trumps everything. TICK < WAKEUP < NORMAL
559 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
560 return -1;
561 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
562 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800563 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700564
565 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800566 if (lhs.whenElapsed < rhs.whenElapsed) {
567 return -1;
568 } else if (lhs.whenElapsed > rhs.whenElapsed) {
569 return 1;
570 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700571
572 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800573 return 0;
574 }
575 };
576
Christopher Tate1590f1e2014-10-02 17:27:57 -0700577 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
578 final int N = alarms.size();
579 for (int i = 0; i < N; i++) {
580 Alarm a = alarms.get(i);
581
582 final int alarmPrio;
583 if (Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
584 alarmPrio = PRIO_TICK;
585 } else if (a.wakeup) {
586 alarmPrio = PRIO_WAKEUP;
587 } else {
588 alarmPrio = PRIO_NORMAL;
589 }
590
591 PriorityClass packagePrio = a.priorityClass;
592 if (packagePrio == null) packagePrio = mPriorities.get(a.operation.getCreatorPackage());
593 if (packagePrio == null) {
594 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
595 mPriorities.put(a.operation.getCreatorPackage(), packagePrio);
596 }
597 a.priorityClass = packagePrio;
598
599 if (packagePrio.seq != mCurrentSeq) {
600 // first alarm we've seen in the current delivery generation from this package
601 packagePrio.priority = alarmPrio;
602 packagePrio.seq = mCurrentSeq;
603 } else {
604 // Multiple alarms from this package being delivered in this generation;
605 // bump the package's delivery class if it's warranted.
606 // TICK < WAKEUP < NORMAL
607 if (alarmPrio < packagePrio.priority) {
608 packagePrio.priority = alarmPrio;
609 }
610 }
611 }
612 }
613
Christopher Tatee0a22b32013-07-11 14:43:13 -0700614 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800615 static final long MIN_FUZZABLE_INTERVAL = 10000;
616 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700617 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
618
619 // set to null if in idle mode; while in this mode, any alarms we don't want
620 // to run during this time are placed in mPendingWhileIdleAlarms
621 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700622 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700623 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700624
Jeff Brownb880d882014-02-10 19:47:07 -0800625 public AlarmManagerService(Context context) {
626 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700627 mConstants = new Constants(mHandler);
Jeff Brownb880d882014-02-10 19:47:07 -0800628 }
629
Christopher Tatee0a22b32013-07-11 14:43:13 -0700630 static long convertToElapsed(long when, int type) {
Mao Jinlong77b0ec72015-08-31 17:25:04 +0800631 final boolean isRtc = (type == RTC || type == RTC_WAKEUP
632 || type == RTC_POWEROFF_WAKEUP);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700633 if (isRtc) {
634 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
635 }
636 return when;
637 }
638
639 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
640 // calculate the end of our nominal delivery window for the alarm.
641 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
642 // Current heuristic: batchable window is 75% of either the recurrence interval
643 // [for a periodic alarm] or of the time from now to the desired delivery time,
644 // with a minimum delay/interval of 10 seconds, under which we will simply not
645 // defer the alarm.
646 long futurity = (interval == 0)
647 ? (triggerAtTime - now)
648 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700649 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700650 futurity = 0;
651 }
652 return triggerAtTime + (long)(.75 * futurity);
653 }
654
655 // returns true if the batch was added at the head
656 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
657 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
658 if (index < 0) {
659 index = 0 - index - 1;
660 }
661 list.add(index, newBatch);
662 return (index == 0);
663 }
664
Christopher Tate385e4982013-07-23 18:22:29 -0700665 // Return the index of the matching batch, or -1 if none found.
666 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700667 final int N = mAlarmBatches.size();
668 for (int i = 0; i < N; i++) {
669 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700670 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700671 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700672 }
673 }
Christopher Tate385e4982013-07-23 18:22:29 -0700674 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700675 }
676
677 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
678 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700679 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700680 rebatchAllAlarmsLocked(true);
681 }
682 }
683
684 void rebatchAllAlarmsLocked(boolean doValidate) {
685 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
686 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700687 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700688 final long nowElapsed = SystemClock.elapsedRealtime();
689 final int oldBatches = oldSet.size();
690 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
691 Batch batch = oldSet.get(batchNum);
692 final int N = batch.size();
693 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700694 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700695 }
696 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700697 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
698 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
699 + " to " + mPendingIdleUntil);
700 if (mPendingIdleUntil == null) {
701 // Somehow we lost this... we need to restore all of the pending alarms.
702 restorePendingWhileIdleAlarmsLocked();
703 }
704 }
705 rescheduleKernelAlarmsLocked();
706 updateNextAlarmClockLocked();
707 }
708
709 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
710 a.when = a.origWhen;
711 long whenElapsed = convertToElapsed(a.when, a.type);
712 final long maxElapsed;
Dianne Hackborn3d1933c2015-06-10 16:25:57 -0700713 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700714 // Exact
715 maxElapsed = whenElapsed;
716 } else {
717 // Not exact. Preserve any explicit window, otherwise recalculate
718 // the window based on the alarm's new futurity. Note that this
719 // reflects a policy of preferring timely to deferred delivery.
720 maxElapsed = (a.windowLength > 0)
721 ? (whenElapsed + a.windowLength)
722 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
723 }
724 a.whenElapsed = whenElapsed;
725 a.maxWhenElapsed = maxElapsed;
726 setImplLocked(a, true, doValidate);
727 }
728
729 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackborn35d54032015-04-23 10:30:43 -0700730 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700731 if (mPendingWhileIdleAlarms.size() > 0) {
732 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
733 mPendingWhileIdleAlarms = new ArrayList<>();
734 final long nowElapsed = SystemClock.elapsedRealtime();
735 for (int i=alarms.size() - 1; i >= 0; i--) {
736 Alarm a = alarms.get(i);
737 reAddAlarmLocked(a, nowElapsed, false);
738 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700739 }
Dianne Hackborn35d54032015-04-23 10:30:43 -0700740
Dianne Hackborn3d1933c2015-06-10 16:25:57 -0700741 // Make sure we are using the correct ALLOW_WHILE_IDLE min time.
Dianne Hackborna750a632015-06-16 17:18:23 -0700742 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn3d1933c2015-06-10 16:25:57 -0700743
Dianne Hackborn35d54032015-04-23 10:30:43 -0700744 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700745 rescheduleKernelAlarmsLocked();
746 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -0700747
748 // And send a TIME_TICK right now, since it is important to get the UI updated.
749 try {
750 mTimeTickSender.send();
751 } catch (PendingIntent.CanceledException e) {
752 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700753 }
754
Adam Lesinski182f73f2013-12-05 16:48:06 -0800755 static final class InFlight extends Intent {
Dianne Hackborn81038902012-11-26 17:04:09 -0800756 final PendingIntent mPendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700757 final WorkSource mWorkSource;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700758 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800759 final BroadcastStats mBroadcastStats;
760 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800761 final int mAlarmType;
Susheel Yadagiri6837e452015-07-09 13:01:39 -0700762 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800763
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800764 InFlight(AlarmManagerService service, PendingIntent pendingIntent, WorkSource workSource,
Susheel Yadagiri6837e452015-07-09 13:01:39 -0700765 int alarmType, String tag, long nowELAPSED, int uid) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800766 mPendingIntent = pendingIntent;
David Christieebe51fc2013-07-26 13:23:29 -0700767 mWorkSource = workSource;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700768 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800769 mBroadcastStats = service.getStatsLocked(pendingIntent);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700770 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -0800771 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700772 fs = new FilterStats(mBroadcastStats, mTag);
773 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -0800774 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700775 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -0800776 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800777 mAlarmType = alarmType;
Susheel Yadagiri6837e452015-07-09 13:01:39 -0700778 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800779 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800780 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800781
Adam Lesinski182f73f2013-12-05 16:48:06 -0800782 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -0800783 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700784 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800785
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700786 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800788 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 int numWakeup;
790 long startTime;
791 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -0800792
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700793 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800794 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700795 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800796 }
797 }
Dianne Hackborn3d1933c2015-06-10 16:25:57 -0700798
Adam Lesinski182f73f2013-12-05 16:48:06 -0800799 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800800 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800801 final String mPackageName;
802
803 long aggregateTime;
804 int count;
805 int numWakeup;
806 long startTime;
807 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700808 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -0800809
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800810 BroadcastStats(int uid, String packageName) {
811 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800812 mPackageName = packageName;
813 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 }
Dianne Hackborn3d1933c2015-06-10 16:25:57 -0700815
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800816 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
817 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700818
819 int mNumDelayedAlarms = 0;
820 long mTotalDelayTime = 0;
821 long mMaxDelayTime = 0;
822
Adam Lesinski182f73f2013-12-05 16:48:06 -0800823 @Override
824 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800825 mNativeData = init();
Mao Jinlong77b0ec72015-08-31 17:25:04 +0800826 mNextWakeup = mNextRtcWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800827
828 // We have to set current TimeZone info to kernel
829 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -0800830 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800831
Adam Lesinski182f73f2013-12-05 16:48:06 -0800832 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800833 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800834
Adam Lesinski182f73f2013-12-05 16:48:06 -0800835 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700837 Intent.FLAG_RECEIVER_REGISTERED_ONLY
838 | Intent.FLAG_RECEIVER_FOREGROUND), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700839 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800840 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
841 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800842 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700843 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844
845 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -0800846 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 mClockReceiver.scheduleTimeTickEvent();
848 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700849 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 mUninstallReceiver = new UninstallReceiver();
851
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800852 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800853 AlarmThread waitThread = new AlarmThread();
854 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800856 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800858
859 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800861
862 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -0700863 public void onBootPhase(int phase) {
864 if (phase == PHASE_SYSTEM_SERVICES_READY) {
865 mConstants.start(getContext().getContentResolver());
866 }
867 }
868
869 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 protected void finalize() throws Throwable {
871 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800872 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 } finally {
874 super.finalize();
875 }
876 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700877
Adam Lesinski182f73f2013-12-05 16:48:06 -0800878 void setTimeZoneImpl(String tz) {
879 if (TextUtils.isEmpty(tz)) {
880 return;
David Christieebe51fc2013-07-26 13:23:29 -0700881 }
882
Adam Lesinski182f73f2013-12-05 16:48:06 -0800883 TimeZone zone = TimeZone.getTimeZone(tz);
884 // Prevent reentrant calls from stepping on each other when writing
885 // the time zone property
886 boolean timeZoneWasChanged = false;
887 synchronized (this) {
888 String current = SystemProperties.get(TIMEZONE_PROPERTY);
889 if (current == null || !current.equals(zone.getID())) {
890 if (localLOGV) {
891 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
892 }
893 timeZoneWasChanged = true;
894 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
895 }
896
897 // Update the kernel timezone information
898 // Kernel tracks time offsets as 'minutes west of GMT'
899 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800900 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -0800901 }
902
903 TimeZone.setDefault(null);
904
905 if (timeZoneWasChanged) {
906 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
907 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
908 intent.putExtra("time-zone", zone.getID());
909 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
910 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800911 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700912
Adam Lesinski182f73f2013-12-05 16:48:06 -0800913 void removeImpl(PendingIntent operation) {
914 if (operation == null) {
915 return;
916 }
917 synchronized (mLock) {
918 removeLocked(operation);
919 }
920 }
921
922 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700923 PendingIntent operation, int flags, WorkSource workSource,
Dianne Hackborn3d1933c2015-06-10 16:25:57 -0700924 AlarmManager.AlarmClockInfo alarmClock, int callingUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 if (operation == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800926 Slog.w(TAG, "set/setRepeating ignored because there is no intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 return;
928 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700929
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700930 // Sanity check the window length. This will catch people mistakenly
931 // trying to pass an end-of-window timestamp rather than a duration.
932 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
933 Slog.w(TAG, "Window length " + windowLength
934 + "ms suspiciously long; limiting to 1 hour");
935 windowLength = AlarmManager.INTERVAL_HOUR;
936 }
937
Christopher Tate498c6cb2014-11-17 16:09:27 -0800938 // Sanity check the recurrence interval. This will catch people who supply
939 // seconds when the API expects milliseconds.
Dianne Hackborna750a632015-06-16 17:18:23 -0700940 final long minInterval = mConstants.MIN_INTERVAL;
941 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -0800942 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -0700943 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -0800944 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -0700945 interval = minInterval;
Christopher Tate498c6cb2014-11-17 16:09:27 -0800946 }
947
Mao Jinlong77b0ec72015-08-31 17:25:04 +0800948 if (type < RTC_WAKEUP || type > RTC_POWEROFF_WAKEUP) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700949 throw new IllegalArgumentException("Invalid alarm type " + type);
950 }
951
Christopher Tate5f221e82013-07-30 17:13:15 -0700952 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -0700953 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c2015-06-10 16:25:57 -0700954 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -0700955 + " pid=" + what);
956 triggerAtTime = 0;
957 }
958
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700959 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -0800960 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
961 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -0700962 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -0800963 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
964
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700965 final long maxElapsed;
966 if (windowLength == AlarmManager.WINDOW_EXACT) {
967 maxElapsed = triggerElapsed;
968 } else if (windowLength < 0) {
969 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c2015-06-10 16:25:57 -0700970 // Fix this window in place, so that as time approaches we don't collapse it.
971 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700972 } else {
973 maxElapsed = triggerElapsed + windowLength;
974 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700975
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700977 if (DEBUG_BATCH) {
978 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700979 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -0700980 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700981 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 }
Christopher Tate3e04b472013-10-21 17:51:31 -0700983 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Dianne Hackborn3d1933c2015-06-10 16:25:57 -0700984 interval, operation, flags, true, workSource, alarmClock, callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 }
986 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987
Christopher Tate3e04b472013-10-21 17:51:31 -0700988 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700989 long maxWhen, long interval, PendingIntent operation, int flags,
Jose Lima235510e2014-08-13 12:50:01 -0700990 boolean doValidate, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
Dianne Hackborn3d1933c2015-06-10 16:25:57 -0700991 int uid) {
Christopher Tate3e04b472013-10-21 17:51:31 -0700992 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Dianne Hackborn3d1933c2015-06-10 16:25:57 -0700993 operation, workSource, flags, alarmClock, uid);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700994 removeLocked(operation);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700995 setImplLocked(a, false, doValidate);
996 }
Christopher Tateb8849c12011-02-08 13:39:01 -0800997
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700998 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
999 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001000 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001001 // The caller has given the time they want this to happen at, however we need
1002 // to pull that earlier if there are existing alarms that have requested to
1003 // bring us out of idle.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001004 if (mNextWakeFromIdle != null) {
1005 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001006 }
1007 // Add fuzz to make the alarm go off some time before the actual desired time.
1008 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001009 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001010 if (fuzz > 0) {
1011 if (mRandom == null) {
1012 mRandom = new Random();
1013 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001014 final int delta = mRandom.nextInt(fuzz);
1015 a.whenElapsed -= delta;
1016 if (false) {
1017 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1018 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1019 Slog.d(TAG, "Applied fuzz: " + fuzz);
1020 Slog.d(TAG, "Final delta: " + delta);
1021 Slog.d(TAG, "Final when: " + a.whenElapsed);
1022 }
1023 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001024 }
1025
1026 } else if (mPendingIdleUntil != null) {
1027 // We currently have an idle until alarm scheduled; if the new alarm has
1028 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07001029 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1030 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1031 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001032 == 0) {
1033 mPendingWhileIdleAlarms.add(a);
1034 return;
1035 }
1036 }
1037
1038 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
1039 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -07001040 if (whichBatch < 0) {
1041 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001042 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 } else {
Christopher Tate385e4982013-07-23 18:22:29 -07001044 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001045 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001046 // The start time of this batch advanced, so batch ordering may
1047 // have just been broken. Move it to where it now belongs.
1048 mAlarmBatches.remove(whichBatch);
1049 addBatchLocked(mAlarmBatches, batch);
1050 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 }
1052
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001053 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001054 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001055 }
1056
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001057 boolean needRebatch = false;
1058
1059 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
1060 mPendingIdleUntil = a;
Dianne Hackborna750a632015-06-16 17:18:23 -07001061 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001062 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001063 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1064 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1065 mNextWakeFromIdle = a;
1066 // If this wake from idle is earlier than whatever was previously scheduled,
1067 // and we are currently idling, then we need to rebatch alarms in case the idle
1068 // until time needs to be updated.
1069 if (mPendingIdleUntil != null) {
1070 needRebatch = true;
1071 }
1072 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001073 }
1074
1075 if (!rebatching) {
1076 if (DEBUG_VALIDATE) {
1077 if (doValidate && !validateConsistencyLocked()) {
1078 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1079 + " when(hex)=" + Long.toHexString(a.when)
1080 + " whenElapsed=" + a.whenElapsed
1081 + " maxWhenElapsed=" + a.maxWhenElapsed
1082 + " interval=" + a.repeatInterval + " op=" + a.operation
1083 + " flags=0x" + Integer.toHexString(a.flags));
1084 rebatchAllAlarmsLocked(false);
1085 needRebatch = false;
1086 }
1087 }
1088
1089 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001090 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001091 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001092
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001093 rescheduleKernelAlarmsLocked();
1094 updateNextAlarmClockLocked();
1095 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001096 }
1097
Adam Lesinski182f73f2013-12-05 16:48:06 -08001098 private final IBinder mService = new IAlarmManager.Stub() {
1099 @Override
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001100 public void set(int type, long triggerAtTime, long windowLength, long interval, int flags,
Jose Lima235510e2014-08-13 12:50:01 -07001101 PendingIntent operation, WorkSource workSource,
1102 AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07001103 final int callingUid = Binder.getCallingUid();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001104 if (workSource != null) {
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07001105 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001106 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07001107 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001108 }
1109
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07001110 // No incoming callers can request either WAKE_FROM_IDLE or
1111 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1112 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1113 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1114
1115 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1116 // manager when to come out of idle mode, which is only for DeviceIdleController.
1117 if (callingUid != Process.SYSTEM_UID) {
1118 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1119 }
1120
1121 // If the caller is a core system component, and not calling to do work on behalf
1122 // of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED. This means we
1123 // will allow these alarms to go off as normal even while idle, with no timing
1124 // restrictions.
1125 if (callingUid < Process.FIRST_APPLICATION_UID && workSource == null) {
1126 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1127 }
1128
1129 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001130 if (windowLength == AlarmManager.WINDOW_EXACT) {
1131 flags |= AlarmManager.FLAG_STANDALONE;
1132 }
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07001133
1134 // If this alarm is for an alarm clock, then it must be standalone and we will
1135 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001136 if (alarmClock != null) {
1137 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
1138 }
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07001139
Adam Lesinski182f73f2013-12-05 16:48:06 -08001140 setImpl(type, triggerAtTime, windowLength, interval, operation,
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07001141 flags, workSource, alarmClock, callingUid);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001142 }
Christopher Tate89779822012-08-31 14:40:03 -07001143
Adam Lesinski182f73f2013-12-05 16:48:06 -08001144 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001145 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001146 getContext().enforceCallingOrSelfPermission(
1147 "android.permission.SET_TIME",
1148 "setTime");
1149
Greg Hackmann0cab8962014-02-21 16:35:52 -08001150 if (mNativeData == 0) {
1151 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1152 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001153 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001154
1155 synchronized (mLock) {
1156 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001159
1160 @Override
1161 public void setTimeZone(String tz) {
1162 getContext().enforceCallingOrSelfPermission(
1163 "android.permission.SET_TIME_ZONE",
1164 "setTimeZone");
1165
1166 final long oldId = Binder.clearCallingIdentity();
1167 try {
1168 setTimeZoneImpl(tz);
1169 } finally {
1170 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171 }
1172 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001173
Adam Lesinski182f73f2013-12-05 16:48:06 -08001174 @Override
1175 public void remove(PendingIntent operation) {
1176 removeImpl(operation);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001177
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001179
Adam Lesinski182f73f2013-12-05 16:48:06 -08001180 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001181 public long getNextWakeFromIdleTime() {
1182 return getNextWakeFromIdleTimeImpl();
1183 }
1184
1185 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001186 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001187 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1188 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1189 "getNextAlarmClock", null);
1190
1191 return getNextAlarmClockImpl(userId);
1192 }
1193
1194 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001195 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1196 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1197 != PackageManager.PERMISSION_GRANTED) {
1198 pw.println("Permission Denial: can't dump AlarmManager from from pid="
1199 + Binder.getCallingPid()
1200 + ", uid=" + Binder.getCallingUid());
1201 return;
Christopher Tate4cb338d2013-07-26 13:11:31 -07001202 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001203
Adam Lesinski182f73f2013-12-05 16:48:06 -08001204 dumpImpl(pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001205 }
Susheel Yadagiri6837e452015-07-09 13:01:39 -07001206
1207 @Override
1208 /* updates the blocked uids, so if a wake lock is acquired to only fire
1209 * alarm for it, it can be released.
1210 */
1211 public void updateBlockedUids(int uid, boolean isBlocked) {
1212
1213 if (localLOGV) Slog.v(TAG, "UpdateBlockedUids: uid = " + uid +
1214 " isBlocked = " + isBlocked);
1215
1216 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
1217 if (localLOGV) Slog.v(TAG, "UpdateBlockedUids is not allowed");
1218 return;
1219 }
1220
1221 synchronized(mLock) {
1222 if(isBlocked) {
1223 mBlockedUids.add(new Integer(uid));
1224 if (checkReleaseWakeLock()) {
1225 /* all the uids for which the alarms are triggered
1226 * are either blocked or have called onSendFinished.
1227 */
1228 if (mWakeLock.isHeld()) {
1229 mWakeLock.release();
1230 if (localLOGV)
1231 Slog.v(TAG, "AM WakeLock Released Internally in updateBlockedUids");
1232 }
1233 }
1234 } else {
1235 mBlockedUids.clear();
1236 }
1237 }
1238 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001239 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001240
Adam Lesinski182f73f2013-12-05 16:48:06 -08001241 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001242 synchronized (mLock) {
1243 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001244 mConstants.dump(pw);
1245 pw.println();
1246
Christopher Tatee0a22b32013-07-11 14:43:13 -07001247 final long nowRTC = System.currentTimeMillis();
1248 final long nowELAPSED = SystemClock.elapsedRealtime();
1249 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1250
Dianne Hackborna750a632015-06-16 17:18:23 -07001251 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001252 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001253 pw.print(" nowELAPSED="); TimeUtils.formatDuration(nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001254 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001255 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001256 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001257 pw.print(" mLastTimeChangeRealtime=");
Dianne Hackbornc3527222015-05-13 14:03:20 -07001258 TimeUtils.formatDuration(mLastTimeChangeRealtime, pw);
1259 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001260 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001261 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001262 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1263 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001264 pw.print(" Max wakeup delay: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001265 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1266 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001267 pw.print(" Time since last dispatch: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001268 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1269 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001270 pw.print(" Next non-wakeup delivery time: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001271 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1272 pw.println();
1273 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001274
1275 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1276 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001277 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001278 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001279 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001280 pw.print(" Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001281 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001282 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001283
John Spurlock604a5ee2015-06-01 12:27:22 -04001284 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001285 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001286 final TreeSet<Integer> users = new TreeSet<>();
1287 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1288 users.add(mNextAlarmClockForUser.keyAt(i));
1289 }
1290 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1291 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1292 }
1293 for (int user : users) {
1294 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1295 final long time = next != null ? next.getTriggerTime() : 0;
1296 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001297 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001298 pw.print(" pendingSend:"); pw.print(pendingSend);
1299 pw.print(" time:"); pw.print(time);
1300 if (time > 0) {
1301 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1302 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1303 }
1304 pw.println();
1305 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001306 if (mAlarmBatches.size() > 0) {
1307 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001308 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001309 pw.println(mAlarmBatches.size());
1310 for (Batch b : mAlarmBatches) {
1311 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001312 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001313 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001315 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001316 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001317 pw.println(" Idle mode state:");
1318 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001319 if (mPendingIdleUntil != null) {
1320 pw.println(mPendingIdleUntil);
1321 mPendingIdleUntil.dump(pw, " ", nowRTC, nowELAPSED, sdf);
1322 } else {
1323 pw.println("null");
1324 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001325 pw.println(" Pending alarms:");
1326 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001327 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001328 if (mNextWakeFromIdle != null) {
1329 pw.println();
1330 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
1331 mNextWakeFromIdle.dump(pw, " ", nowRTC, nowELAPSED, sdf);
1332 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001333
1334 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001335 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001336 if (mPendingNonWakeupAlarms.size() > 0) {
1337 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001338 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001339 } else {
1340 pw.println("(none)");
1341 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001342 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001343 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1344 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001345 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001346 pw.print(", max non-interactive time: ");
1347 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1348 pw.println();
1349
1350 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001351 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001352 pw.println();
1353
Dianne Hackborna750a632015-06-16 17:18:23 -07001354 pw.print(" mAllowWhileIdleMinTime=");
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07001355 TimeUtils.formatDuration(mAllowWhileIdleMinTime, pw);
1356 pw.println();
1357 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001358 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07001359 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
1360 pw.print(" UID ");
1361 UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
1362 pw.print(": ");
1363 TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i),
1364 nowELAPSED, pw);
1365 pw.println();
1366 }
1367 }
1368 pw.println();
1369
Dianne Hackborn81038902012-11-26 17:04:09 -08001370 if (mLog.dump(pw, " Recent problems", " ")) {
1371 pw.println();
1372 }
1373
1374 final FilterStats[] topFilters = new FilterStats[10];
1375 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1376 @Override
1377 public int compare(FilterStats lhs, FilterStats rhs) {
1378 if (lhs.aggregateTime < rhs.aggregateTime) {
1379 return 1;
1380 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1381 return -1;
1382 }
1383 return 0;
1384 }
1385 };
1386 int len = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001387 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1388 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1389 for (int ip=0; ip<uidStats.size(); ip++) {
1390 BroadcastStats bs = uidStats.valueAt(ip);
1391 for (int is=0; is<bs.filterStats.size(); is++) {
1392 FilterStats fs = bs.filterStats.valueAt(is);
1393 int pos = len > 0
1394 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1395 if (pos < 0) {
1396 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001397 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001398 if (pos < topFilters.length) {
1399 int copylen = topFilters.length - pos - 1;
1400 if (copylen > 0) {
1401 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1402 }
1403 topFilters[pos] = fs;
1404 if (len < topFilters.length) {
1405 len++;
1406 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001407 }
1408 }
1409 }
1410 }
1411 if (len > 0) {
1412 pw.println(" Top Alarms:");
1413 for (int i=0; i<len; i++) {
1414 FilterStats fs = topFilters[i];
1415 pw.print(" ");
1416 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1417 TimeUtils.formatDuration(fs.aggregateTime, pw);
1418 pw.print(" running, "); pw.print(fs.numWakeup);
1419 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001420 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1421 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001422 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001423 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001424 pw.println();
1425 }
1426 }
1427
1428 pw.println(" ");
1429 pw.println(" Alarm Stats:");
1430 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001431 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1432 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1433 for (int ip=0; ip<uidStats.size(); ip++) {
1434 BroadcastStats bs = uidStats.valueAt(ip);
1435 pw.print(" ");
1436 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1437 UserHandle.formatUid(pw, bs.mUid);
1438 pw.print(":");
1439 pw.print(bs.mPackageName);
1440 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1441 pw.print(" running, "); pw.print(bs.numWakeup);
1442 pw.println(" wakeups:");
1443 tmpFilters.clear();
1444 for (int is=0; is<bs.filterStats.size(); is++) {
1445 tmpFilters.add(bs.filterStats.valueAt(is));
1446 }
1447 Collections.sort(tmpFilters, comparator);
1448 for (int i=0; i<tmpFilters.size(); i++) {
1449 FilterStats fs = tmpFilters.get(i);
1450 pw.print(" ");
1451 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1452 TimeUtils.formatDuration(fs.aggregateTime, pw);
1453 pw.print(" "); pw.print(fs.numWakeup);
1454 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001455 pw.print(" alarms, last ");
1456 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1457 pw.println(":");
1458 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001459 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001460 pw.println();
1461 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 }
1463 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001464
1465 if (WAKEUP_STATS) {
1466 pw.println();
1467 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001468 long last = -1;
1469 for (WakeupEvent event : mRecentWakeups) {
1470 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1471 pw.print('|');
1472 if (last < 0) {
1473 pw.print('0');
1474 } else {
1475 pw.print(event.when - last);
1476 }
1477 last = event.when;
1478 pw.print('|'); pw.print(event.uid);
1479 pw.print('|'); pw.print(event.action);
1480 pw.println();
1481 }
1482 pw.println();
1483 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484 }
1485 }
1486
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001487 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001488 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
1489 PrintWriter pw = new PrintWriter(bs);
1490 final long nowRTC = System.currentTimeMillis();
1491 final long nowELAPSED = SystemClock.elapsedRealtime();
1492 final int NZ = mAlarmBatches.size();
1493 for (int iz = 0; iz < NZ; iz++) {
1494 Batch bz = mAlarmBatches.get(iz);
1495 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001496 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001497 pw.flush();
1498 Slog.v(TAG, bs.toString());
1499 bs.reset();
1500 }
1501 }
1502
1503 private boolean validateConsistencyLocked() {
1504 if (DEBUG_VALIDATE) {
1505 long lastTime = Long.MIN_VALUE;
1506 final int N = mAlarmBatches.size();
1507 for (int i = 0; i < N; i++) {
1508 Batch b = mAlarmBatches.get(i);
1509 if (b.start >= lastTime) {
1510 // duplicate start times are okay because of standalone batches
1511 lastTime = b.start;
1512 } else {
1513 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001514 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1515 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001516 return false;
1517 }
1518 }
1519 }
1520 return true;
1521 }
1522
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001523 private Batch findFirstWakeupBatchLocked() {
1524 final int N = mAlarmBatches.size();
1525 for (int i = 0; i < N; i++) {
1526 Batch b = mAlarmBatches.get(i);
1527 if (b.hasWakeups()) {
1528 return b;
1529 }
1530 }
1531 return null;
1532 }
1533
Mao Jinlong77b0ec72015-08-31 17:25:04 +08001534 private Batch findFirstRtcWakeupBatchLocked() {
1535 final int N = mAlarmBatches.size();
1536 for (int i = 0; i < N; i++) {
1537 Batch b = mAlarmBatches.get(i);
1538 long intervalTime = b.start - SystemClock.elapsedRealtime();
1539 if (b.isRtcPowerOffWakeup()) {
1540 return b;
1541 }
1542 }
1543 return null;
1544 }
1545
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001546 long getNextWakeFromIdleTimeImpl() {
1547 synchronized (mLock) {
1548 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
1549 }
1550 }
1551
1552 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001553 synchronized (mLock) {
1554 return mNextAlarmClockForUser.get(userId);
1555 }
1556 }
1557
1558 /**
1559 * Recomputes the next alarm clock for all users.
1560 */
1561 private void updateNextAlarmClockLocked() {
1562 if (!mNextAlarmClockMayChange) {
1563 return;
1564 }
1565 mNextAlarmClockMayChange = false;
1566
Jose Lima235510e2014-08-13 12:50:01 -07001567 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001568 nextForUser.clear();
1569
1570 final int N = mAlarmBatches.size();
1571 for (int i = 0; i < N; i++) {
1572 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
1573 final int M = alarms.size();
1574
1575 for (int j = 0; j < M; j++) {
1576 Alarm a = alarms.get(j);
1577 if (a.alarmClock != null) {
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07001578 final int userId = UserHandle.getUserId(a.uid);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001579
1580 if (DEBUG_ALARM_CLOCK) {
1581 Log.v(TAG, "Found AlarmClockInfo at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001582 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02001583 " for user " + userId);
1584 }
1585
1586 // Alarms and batches are sorted by time, no need to compare times here.
1587 if (nextForUser.get(userId) == null) {
1588 nextForUser.put(userId, a.alarmClock);
1589 }
1590 }
1591 }
1592 }
1593
1594 // Update mNextAlarmForUser with new values.
1595 final int NN = nextForUser.size();
1596 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07001597 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001598 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001599 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001600 if (!newAlarm.equals(currentAlarm)) {
1601 updateNextAlarmInfoForUserLocked(userId, newAlarm);
1602 }
1603 }
1604
1605 // Remove users without any alarm clocks scheduled.
1606 final int NNN = mNextAlarmClockForUser.size();
1607 for (int i = NNN - 1; i >= 0; i--) {
1608 int userId = mNextAlarmClockForUser.keyAt(i);
1609 if (nextForUser.get(userId) == null) {
1610 updateNextAlarmInfoForUserLocked(userId, null);
1611 }
1612 }
1613 }
1614
Jose Lima235510e2014-08-13 12:50:01 -07001615 private void updateNextAlarmInfoForUserLocked(int userId,
1616 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001617 if (alarmClock != null) {
1618 if (DEBUG_ALARM_CLOCK) {
1619 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001620 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02001621 }
1622 mNextAlarmClockForUser.put(userId, alarmClock);
1623 } else {
1624 if (DEBUG_ALARM_CLOCK) {
1625 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
1626 }
1627 mNextAlarmClockForUser.remove(userId);
1628 }
1629
1630 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
1631 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1632 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1633 }
1634
1635 /**
1636 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
1637 * for which alarm clocks have changed since the last call to this.
1638 *
1639 * Do not call with a lock held. Only call from mHandler's thread.
1640 *
1641 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
1642 */
1643 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07001644 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001645 pendingUsers.clear();
1646
1647 synchronized (mLock) {
1648 final int N = mPendingSendNextAlarmClockChangedForUser.size();
1649 for (int i = 0; i < N; i++) {
1650 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
1651 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
1652 }
1653 mPendingSendNextAlarmClockChangedForUser.clear();
1654 }
1655
1656 final int N = pendingUsers.size();
1657 for (int i = 0; i < N; i++) {
1658 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001659 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001660 Settings.System.putStringForUser(getContext().getContentResolver(),
1661 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01001662 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02001663 userId);
1664
1665 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
1666 new UserHandle(userId));
1667 }
1668 }
1669
1670 /**
1671 * Formats an alarm like platform/packages/apps/DeskClock used to.
1672 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01001673 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
1674 int userId) {
1675 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02001676 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
1677 return (info == null) ? "" :
1678 DateFormat.format(pattern, info.getTriggerTime()).toString();
1679 }
1680
Adam Lesinski182f73f2013-12-05 16:48:06 -08001681 void rescheduleKernelAlarmsLocked() {
1682 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
1683 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001684 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001685 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001686 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001687 final Batch firstBatch = mAlarmBatches.get(0);
Mao Jinlong77b0ec72015-08-31 17:25:04 +08001688 final Batch firstRtcWakeup = findFirstRtcWakeupBatchLocked();
Prashant Malani753e9e02015-06-10 17:43:49 -07001689 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001690 mNextWakeup = firstWakeup.start;
1691 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001692 }
Mao Jinlong77b0ec72015-08-31 17:25:04 +08001693 if (firstRtcWakeup != null && mNextRtcWakeup != firstRtcWakeup.start) {
1694 mNextRtcWakeup = firstRtcWakeup.start;
1695 long when = firstRtcWakeup.getWhenByElapsedTime(mNextRtcWakeup);
1696 if (when != 0) {
1697 setLocked(RTC_POWEROFF_WAKEUP, when);
1698 }
1699 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001700 if (firstBatch != firstWakeup) {
1701 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001702 }
1703 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001704 if (mPendingNonWakeupAlarms.size() > 0) {
1705 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
1706 nextNonWakeup = mNextNonWakeupDeliveryTime;
1707 }
1708 }
Prashant Malani753e9e02015-06-10 17:43:49 -07001709 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001710 mNextNonWakeup = nextNonWakeup;
1711 setLocked(ELAPSED_REALTIME, nextNonWakeup);
1712 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001713 }
1714
Susheel Yadagiri6837e452015-07-09 13:01:39 -07001715 boolean checkReleaseWakeLock() {
1716 if (mTriggeredUids.size() == 0 || mBlockedUids.size() == 0)
1717 return false;
1718
1719 int uid;
1720 for (int i = 0; i < mTriggeredUids.size(); i++) {
1721 uid = mTriggeredUids.get(i);
1722 if (!mBlockedUids.contains(uid)) {
1723 return false;
1724 }
1725 }
1726 return true;
1727 }
1728
Adam Lesinski182f73f2013-12-05 16:48:06 -08001729 private void removeLocked(PendingIntent operation) {
1730 boolean didRemove = false;
1731 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1732 Batch b = mAlarmBatches.get(i);
Mao Jinlong77b0ec72015-08-31 17:25:04 +08001733 ArrayList<Alarm> alarmList = b.alarms;
1734 Alarm alarm = null;
1735 for (int j = alarmList.size() - 1; j >= 0; j--) {
1736 alarm = alarmList.get(j);
1737 if (alarm.type == RTC_POWEROFF_WAKEUP && alarm.operation.equals(operation)) {
1738 long alarmSeconds, alarmNanoseconds;
1739 alarmSeconds = alarm.when / 1000;
1740 alarmNanoseconds = (alarm.when % 1000) * 1000 * 1000;
1741 clear(mNativeData, alarm.type, alarmSeconds, alarmNanoseconds);
1742 mNextRtcWakeup = 0;
1743 }
1744 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001745 didRemove |= b.remove(operation);
1746 if (b.size() == 0) {
1747 mAlarmBatches.remove(i);
1748 }
1749 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001750 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1751 if (mPendingWhileIdleAlarms.get(i).operation.equals(operation)) {
1752 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1753 mPendingWhileIdleAlarms.remove(i);
1754 }
1755 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001756
1757 if (didRemove) {
1758 if (DEBUG_BATCH) {
1759 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
1760 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001761 boolean restorePending = false;
1762 if (mPendingIdleUntil != null && mPendingIdleUntil.operation.equals(operation)) {
1763 mPendingIdleUntil = null;
1764 restorePending = true;
1765 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001766 if (mNextWakeFromIdle != null && mNextWakeFromIdle.operation.equals(operation)) {
1767 mNextWakeFromIdle = null;
1768 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001769 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001770 if (restorePending) {
1771 restorePendingWhileIdleAlarmsLocked();
1772 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001773 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001774 }
1775 }
1776
1777 void removeLocked(String packageName) {
1778 boolean didRemove = false;
1779 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1780 Batch b = mAlarmBatches.get(i);
1781 didRemove |= b.remove(packageName);
1782 if (b.size() == 0) {
1783 mAlarmBatches.remove(i);
1784 }
1785 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001786 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1787 if (mPendingWhileIdleAlarms.get(i).operation.getTargetPackage().equals(packageName)) {
1788 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1789 mPendingWhileIdleAlarms.remove(i);
1790 }
1791 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001792
1793 if (didRemove) {
1794 if (DEBUG_BATCH) {
1795 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1796 }
1797 rebatchAllAlarmsLocked(true);
1798 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001799 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001800 }
1801 }
1802
1803 void removeUserLocked(int userHandle) {
1804 boolean didRemove = false;
1805 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1806 Batch b = mAlarmBatches.get(i);
1807 didRemove |= b.remove(userHandle);
1808 if (b.size() == 0) {
1809 mAlarmBatches.remove(i);
1810 }
1811 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001812 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1813 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).operation.getCreatorUid())
1814 == userHandle) {
1815 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1816 mPendingWhileIdleAlarms.remove(i);
1817 }
1818 }
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07001819 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
1820 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
1821 mLastAllowWhileIdleDispatch.removeAt(i);
1822 }
1823 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001824
1825 if (didRemove) {
1826 if (DEBUG_BATCH) {
1827 Slog.v(TAG, "remove(user) changed bounds; rebatching");
1828 }
1829 rebatchAllAlarmsLocked(true);
1830 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001831 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001832 }
1833 }
1834
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001835 void interactiveStateChangedLocked(boolean interactive) {
1836 if (mInteractive != interactive) {
1837 mInteractive = interactive;
1838 final long nowELAPSED = SystemClock.elapsedRealtime();
1839 if (interactive) {
1840 if (mPendingNonWakeupAlarms.size() > 0) {
1841 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1842 mTotalDelayTime += thisDelayTime;
1843 if (mMaxDelayTime < thisDelayTime) {
1844 mMaxDelayTime = thisDelayTime;
1845 }
1846 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
1847 mPendingNonWakeupAlarms.clear();
1848 }
1849 if (mNonInteractiveStartTime > 0) {
1850 long dur = nowELAPSED - mNonInteractiveStartTime;
1851 if (dur > mNonInteractiveTime) {
1852 mNonInteractiveTime = dur;
1853 }
1854 }
1855 } else {
1856 mNonInteractiveStartTime = nowELAPSED;
1857 }
1858 }
1859 }
1860
Adam Lesinski182f73f2013-12-05 16:48:06 -08001861 boolean lookForPackageLocked(String packageName) {
1862 for (int i = 0; i < mAlarmBatches.size(); i++) {
1863 Batch b = mAlarmBatches.get(i);
1864 if (b.hasPackage(packageName)) {
1865 return true;
1866 }
1867 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001868 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
1869 if (mPendingWhileIdleAlarms.get(i).operation.getTargetPackage().equals(packageName)) {
1870 return true;
1871 }
1872 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001873 return false;
1874 }
1875
1876 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001877 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001878 // The kernel never triggers alarms with negative wakeup times
1879 // so we ensure they are positive.
1880 long alarmSeconds, alarmNanoseconds;
1881 if (when < 0) {
1882 alarmSeconds = 0;
1883 alarmNanoseconds = 0;
1884 } else {
1885 alarmSeconds = when / 1000;
1886 alarmNanoseconds = (when % 1000) * 1000 * 1000;
1887 }
1888
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001889 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001890 } else {
1891 Message msg = Message.obtain();
1892 msg.what = ALARM_EVENT;
1893
1894 mHandler.removeMessages(ALARM_EVENT);
1895 mHandler.sendMessageAtTime(msg, when);
1896 }
1897 }
1898
Dianne Hackborn043fcd92010-10-06 14:27:34 -07001899 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001900 String prefix, String label, long nowRTC, long nowELAPSED, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 for (int i=list.size()-1; i>=0; i--) {
1902 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001903 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1904 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001905 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 }
1907 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001908
1909 private static final String labelForType(int type) {
1910 switch (type) {
1911 case RTC: return "RTC";
1912 case RTC_WAKEUP : return "RTC_WAKEUP";
1913 case ELAPSED_REALTIME : return "ELAPSED";
1914 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
Mao Jinlong77b0ec72015-08-31 17:25:04 +08001915 case RTC_POWEROFF_WAKEUP : return "RTC_POWEROFF_WAKEUP";
Christopher Tatee0a22b32013-07-11 14:43:13 -07001916 default:
1917 break;
1918 }
1919 return "--unknown--";
1920 }
1921
1922 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001923 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001924 for (int i=list.size()-1; i>=0; i--) {
1925 Alarm a = list.get(i);
1926 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001927 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
1928 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001929 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001930 }
1931 }
1932
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001933 private native long init();
1934 private native void close(long nativeData);
1935 private native void set(long nativeData, int type, long seconds, long nanoseconds);
Mao Jinlong77b0ec72015-08-31 17:25:04 +08001936 private native void clear(long nativeData, int type, long seconds, long nanoseconds);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001937 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08001938 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001939 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001941 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001942 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001943 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07001944 // batches are temporally sorted, so we need only pull from the
1945 // start of the list until we either empty it or hit a batch
1946 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07001947 while (mAlarmBatches.size() > 0) {
1948 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001949 if (batch.start > nowELAPSED) {
1950 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 break;
1952 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001953
Christopher Tatee0a22b32013-07-11 14:43:13 -07001954 // We will (re)schedule some alarms now; don't let that interfere
1955 // with delivery of this current batch
1956 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07001957
Christopher Tatee0a22b32013-07-11 14:43:13 -07001958 final int N = batch.size();
1959 for (int i = 0; i < N; i++) {
1960 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07001961
1962 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1963 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
1964 // schedule such alarms.
1965 long lastTime = mLastAllowWhileIdleDispatch.get(alarm.uid, 0);
1966 long minTime = lastTime + mAllowWhileIdleMinTime;
1967 if (nowELAPSED < minTime) {
1968 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
1969 // alarm went off for this app. Reschedule the alarm to be in the
1970 // correct time period.
1971 alarm.whenElapsed = minTime;
1972 if (alarm.maxWhenElapsed < minTime) {
1973 alarm.maxWhenElapsed = minTime;
1974 }
1975 setImplLocked(alarm, true, false);
1976 continue;
1977 }
1978 }
1979
Christopher Tatee0a22b32013-07-11 14:43:13 -07001980 alarm.count = 1;
1981 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001982 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1983 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
1984 alarm.tag);
1985 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001986 if (mPendingIdleUntil == alarm) {
1987 mPendingIdleUntil = null;
1988 rebatchAllAlarmsLocked(false);
1989 restorePendingWhileIdleAlarmsLocked();
1990 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001991 if (mNextWakeFromIdle == alarm) {
1992 mNextWakeFromIdle = null;
1993 rebatchAllAlarmsLocked(false);
1994 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001995
1996 // Recurring alarms may have passed several alarm intervals while the
1997 // phone was asleep or off, so pass a trigger count when sending them.
1998 if (alarm.repeatInterval > 0) {
1999 // this adjustment will be zero if we're late by
2000 // less than one full repeat interval
2001 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
2002
2003 // Also schedule its next recurrence
2004 final long delta = alarm.count * alarm.repeatInterval;
2005 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07002006 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07002007 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002008 alarm.repeatInterval, alarm.operation, alarm.flags, true,
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07002009 alarm.workSource, alarm.alarmClock, alarm.uid);
Christopher Tate864d42e2014-12-02 11:48:53 -08002010 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002011
Christopher Tate864d42e2014-12-02 11:48:53 -08002012 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002013 hasWakeup = true;
2014 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002015
2016 // We removed an alarm clock. Let the caller recompute the next alarm clock.
2017 if (alarm.alarmClock != null) {
2018 mNextAlarmClockMayChange = true;
2019 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07002020 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002021 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002022
Christopher Tate1590f1e2014-10-02 17:27:57 -07002023 // This is a new alarm delivery set; bump the sequence number to indicate that
2024 // all apps' alarm delivery classes should be recalculated.
2025 mCurrentSeq++;
2026 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002027 Collections.sort(triggerList, mAlarmDispatchComparator);
2028
2029 if (localLOGV) {
2030 for (int i=0; i<triggerList.size(); i++) {
2031 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
2032 }
2033 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002034
2035 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002036 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002037
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002038 /**
2039 * This Comparator sorts Alarms into increasing time order.
2040 */
2041 public static class IncreasingTimeOrder implements Comparator<Alarm> {
2042 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09002043 long when1 = a1.whenElapsed;
2044 long when2 = a2.whenElapsed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 if (when1 - when2 > 0) {
2046 return 1;
2047 }
2048 if (when1 - when2 < 0) {
2049 return -1;
2050 }
2051 return 0;
2052 }
2053 }
2054
2055 private static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002056 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002057 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002058 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002059 public final PendingIntent operation;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002060 public final String tag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002061 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002062 public final int flags;
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07002063 public final AlarmManager.AlarmClockInfo alarmClock;
2064 public final int uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002065 public int count;
2066 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07002067 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002068 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002069 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07002071 public PriorityClass priorityClass;
Susheel Yadagiri6837e452015-07-09 13:01:39 -07002072 public int pid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002073
Christopher Tate3e04b472013-10-21 17:51:31 -07002074 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002075 long _interval, PendingIntent _op, WorkSource _ws, int _flags,
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07002076 AlarmManager.AlarmClockInfo _info, int _uid) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002077 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002078 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002079 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
Mao Jinlong77b0ec72015-08-31 17:25:04 +08002080 || _type == AlarmManager.RTC_WAKEUP
2081 || _type == AlarmManager.RTC_POWEROFF_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002082 when = _when;
2083 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07002084 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002085 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002086 repeatInterval = _interval;
2087 operation = _op;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002088 tag = makeTag(_op, _type);
David Christieebe51fc2013-07-26 13:23:29 -07002089 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002090 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002091 alarmClock = _info;
Susheel Yadagirid6b1fca2015-10-28 16:42:37 -07002092 uid = operation.getCreatorUid();
Susheel Yadagiri6837e452015-07-09 13:01:39 -07002093 pid = Binder.getCallingPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002094 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002095
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002096 public static String makeTag(PendingIntent pi, int type) {
2097 return pi.getTag(type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
Mao Jinlong77b0ec72015-08-31 17:25:04 +08002098 || type == RTC_POWEROFF_WAKEUP ? "*walarm*:" : "*alarm*:");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002099 }
2100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002101 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002102 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002103 StringBuilder sb = new StringBuilder(128);
2104 sb.append("Alarm{");
2105 sb.append(Integer.toHexString(System.identityHashCode(this)));
2106 sb.append(" type ");
2107 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002108 sb.append(" when ");
2109 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002110 sb.append(" ");
2111 sb.append(operation.getTargetPackage());
2112 sb.append('}');
2113 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002114 }
2115
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002116 public void dump(PrintWriter pw, String prefix, long nowRTC, long nowELAPSED,
2117 SimpleDateFormat sdf) {
Mao Jinlong77b0ec72015-08-31 17:25:04 +08002118 final boolean isRtc = (type == RTC || type == RTC_WAKEUP
2119 || type == RTC_POWEROFF_WAKEUP);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002120 pw.print(prefix); pw.print("tag="); pw.println(tag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002121 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002122 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
2123 nowELAPSED, pw);
2124 if (isRtc) {
2125 pw.print(" when="); pw.print(sdf.format(new Date(when)));
2126 } else {
2127 pw.print(" when="); TimeUtils.formatDuration(when, nowELAPSED, pw);
2128 }
2129 pw.println();
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07002130 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002131 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002132 pw.print(" count="); pw.print(count);
2133 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002134 if (alarmClock != null) {
2135 pw.print(prefix); pw.println("Alarm clock:");
2136 pw.print(prefix); pw.print(" triggerTime=");
2137 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
2138 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
2139 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002140 pw.print(prefix); pw.print("operation="); pw.println(operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002141 }
2142 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002143
Christopher Tatee0a22b32013-07-11 14:43:13 -07002144 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
2145 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002146 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
2147 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002148 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07002149 break;
2150 }
2151
Christopher Tatee0a22b32013-07-11 14:43:13 -07002152 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002153 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
2154 Alarm a = b.alarms.get(nextAlarm);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002155 WakeupEvent e = new WakeupEvent(nowRTC,
2156 a.operation.getCreatorUid(),
2157 a.operation.getIntent().getAction());
2158 mRecentWakeups.add(e);
2159 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002160 }
2161 }
2162
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002163 long currentNonWakeupFuzzLocked(long nowELAPSED) {
2164 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
2165 if (timeSinceOn < 5*60*1000) {
2166 // If the screen has been off for 5 minutes, only delay by at most two minutes.
2167 return 2*60*1000;
2168 } else if (timeSinceOn < 30*60*1000) {
2169 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
2170 return 15*60*1000;
2171 } else {
2172 // Otherwise, we will delay by at most an hour.
2173 return 60*60*1000;
2174 }
2175 }
2176
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002177 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002178 if (duration < 15*60*1000) {
2179 // If the duration until the time is less than 15 minutes, the maximum fuzz
2180 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002181 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002182 } else if (duration < 90*60*1000) {
2183 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
2184 return 15*60*1000;
2185 } else {
2186 // Otherwise, we will fuzz by at most half an hour.
2187 return 30*60*1000;
2188 }
2189 }
2190
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002191 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
2192 if (mInteractive) {
2193 return false;
2194 }
2195 if (mLastAlarmDeliveryTime <= 0) {
2196 return false;
2197 }
minho.choo649acab2014-12-12 16:13:55 +09002198 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002199 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
2200 // and the next delivery time is in the past, then just deliver them all. This
2201 // avoids bugs where we get stuck in a loop trying to poll for alarms.
2202 return false;
2203 }
2204 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
2205 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
2206 }
2207
2208 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
2209 mLastAlarmDeliveryTime = nowELAPSED;
2210 for (int i=0; i<triggerList.size(); i++) {
2211 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07002212 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002213 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07002214 if (localLOGV) {
2215 Slog.v(TAG, "sending alarm " + alarm);
2216 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07002217 if (RECORD_ALARMS_IN_HISTORY) {
2218 if (alarm.workSource != null && alarm.workSource.size() > 0) {
2219 for (int wi=0; wi<alarm.workSource.size(); wi++) {
2220 ActivityManagerNative.noteAlarmStart(
2221 alarm.operation, alarm.workSource.get(wi), alarm.tag);
2222 }
2223 } else {
2224 ActivityManagerNative.noteAlarmStart(
2225 alarm.operation, -1, alarm.tag);
2226 }
2227 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002228 alarm.operation.send(getContext(), 0,
2229 mBackgroundIntent.putExtra(
2230 Intent.EXTRA_ALARM_COUNT, alarm.count),
Dianne Hackborna750a632015-06-16 17:18:23 -07002231 mResultReceiver, mHandler, null, allowWhileIdle ? mIdleOptions : null);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002232
2233 // we have an active broadcast so stay awake.
Susheel Yadagiri6837e452015-07-09 13:01:39 -07002234 if (mBroadcastRefCount == 0 || !mWakeLock.isHeld()) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002235 setWakelockWorkSource(alarm.operation, alarm.workSource,
2236 alarm.type, alarm.tag, true);
2237 mWakeLock.acquire();
2238 }
2239 final InFlight inflight = new InFlight(AlarmManagerService.this,
Susheel Yadagiri6837e452015-07-09 13:01:39 -07002240 alarm.operation,
2241 alarm.workSource,
2242 alarm.type, alarm.tag,
2243 nowELAPSED, alarm.uid);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002244 mInFlight.add(inflight);
2245 mBroadcastRefCount++;
Susheel Yadagiri6837e452015-07-09 13:01:39 -07002246 mTriggeredUids.add(new Integer(alarm.uid));
Susheel Yadagirid6b1fca2015-10-28 16:42:37 -07002247 if (checkReleaseWakeLock()) {
2248 if (mWakeLock.isHeld()) {
2249 mWakeLock.release();
2250 if (localLOGV) Slog.v(TAG, "AM WakeLock Released Internally deliverAlarms");
2251 }
2252 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002253
Dianne Hackborna750a632015-06-16 17:18:23 -07002254 if (allowWhileIdle) {
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07002255 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
2256 mLastAllowWhileIdleDispatch.put(alarm.uid, nowELAPSED);
2257 }
2258
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002259 final BroadcastStats bs = inflight.mBroadcastStats;
2260 bs.count++;
2261 if (bs.nesting == 0) {
2262 bs.nesting = 1;
2263 bs.startTime = nowELAPSED;
2264 } else {
2265 bs.nesting++;
2266 }
2267 final FilterStats fs = inflight.mFilterStats;
2268 fs.count++;
2269 if (fs.nesting == 0) {
2270 fs.nesting = 1;
2271 fs.startTime = nowELAPSED;
2272 } else {
2273 fs.nesting++;
2274 }
2275 if (alarm.type == ELAPSED_REALTIME_WAKEUP
Mao Jinlong77b0ec72015-08-31 17:25:04 +08002276 || alarm.type == RTC_WAKEUP
2277 || alarm.type == RTC_POWEROFF_WAKEUP) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002278 bs.numWakeup++;
2279 fs.numWakeup++;
2280 if (alarm.workSource != null && alarm.workSource.size() > 0) {
2281 for (int wi=0; wi<alarm.workSource.size(); wi++) {
2282 ActivityManagerNative.noteWakeupAlarm(
2283 alarm.operation, alarm.workSource.get(wi),
Dianne Hackborn1e383822015-04-10 14:02:33 -07002284 alarm.workSource.getName(wi), alarm.tag);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002285 }
2286 } else {
2287 ActivityManagerNative.noteWakeupAlarm(
Dianne Hackborn1e383822015-04-10 14:02:33 -07002288 alarm.operation, -1, null, alarm.tag);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002289 }
2290 }
2291 } catch (PendingIntent.CanceledException e) {
2292 if (alarm.repeatInterval > 0) {
2293 // This IntentSender is no longer valid, but this
2294 // is a repeating alarm, so toss the hoser.
2295 removeImpl(alarm.operation);
2296 }
2297 } catch (RuntimeException e) {
2298 Slog.w(TAG, "Failure sending alarm.", e);
2299 }
2300 }
2301 }
2302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002303 private class AlarmThread extends Thread
2304 {
2305 public AlarmThread()
2306 {
2307 super("AlarmManager");
2308 }
2309
2310 public void run()
2311 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002312 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2313
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002314 while (true)
2315 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002316 int result = waitForAlarm(mNativeData);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002317
2318 triggerList.clear();
2319
Dianne Hackbornc3527222015-05-13 14:03:20 -07002320 final long nowRTC = System.currentTimeMillis();
2321 final long nowELAPSED = SystemClock.elapsedRealtime();
2322
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002323 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002324 // The kernel can give us spurious time change notifications due to
2325 // small adjustments it makes internally; we want to filter those out.
2326 final long lastTimeChangeClockTime;
2327 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07002328 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002329 lastTimeChangeClockTime = mLastTimeChangeClockTime;
2330 expectedClockTime = lastTimeChangeClockTime
2331 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07002332 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002333 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-500)
2334 || nowRTC > (expectedClockTime+500)) {
2335 // The change is by at least +/- 500 ms (or this is the first change),
2336 // let's do it!
2337 if (DEBUG_BATCH) {
2338 Slog.v(TAG, "Time changed notification from kernel; rebatching");
2339 }
2340 removeImpl(mTimeTickSender);
2341 rebatchAllAlarms();
2342 mClockReceiver.scheduleTimeTickEvent();
2343 synchronized (mLock) {
2344 mNumTimeChanged++;
2345 mLastTimeChangeClockTime = nowRTC;
2346 mLastTimeChangeRealtime = nowELAPSED;
2347 }
2348 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
2349 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
2350 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2351 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
2352
2353 // The world has changed on us, so we need to re-evaluate alarms
2354 // regardless of whether the kernel has told us one went off.
2355 result |= IS_WAKEUP_MASK;
2356 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002357 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002358
Dianne Hackbornc3527222015-05-13 14:03:20 -07002359 if (result != TIME_CHANGED_MASK) {
2360 // If this was anything besides just a time change, then figure what if
2361 // anything to do about alarms.
2362 synchronized (mLock) {
2363 if (localLOGV) Slog.v(
2364 TAG, "Checking for alarms... rtc=" + nowRTC
2365 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07002366
Dianne Hackbornc3527222015-05-13 14:03:20 -07002367 if (WAKEUP_STATS) {
2368 if ((result & IS_WAKEUP_MASK) != 0) {
2369 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
2370 int n = 0;
2371 for (WakeupEvent event : mRecentWakeups) {
2372 if (event.when > newEarliest) break;
2373 n++; // number of now-stale entries at the list head
2374 }
2375 for (int i = 0; i < n; i++) {
2376 mRecentWakeups.remove();
2377 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002378
Dianne Hackbornc3527222015-05-13 14:03:20 -07002379 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002380 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002381 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002382
2383 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2384 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
2385 // if there are no wakeup alarms and the screen is off, we can
2386 // delay what we have so far until the future.
2387 if (mPendingNonWakeupAlarms.size() == 0) {
2388 mStartCurrentDelayTime = nowELAPSED;
2389 mNextNonWakeupDeliveryTime = nowELAPSED
2390 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
2391 }
2392 mPendingNonWakeupAlarms.addAll(triggerList);
2393 mNumDelayedAlarms += triggerList.size();
2394 rescheduleKernelAlarmsLocked();
2395 updateNextAlarmClockLocked();
2396 } else {
2397 // now deliver the alarm intents; if there are pending non-wakeup
2398 // alarms, we need to merge them in to the list. note we don't
2399 // just deliver them first because we generally want non-wakeup
2400 // alarms delivered after wakeup alarms.
2401 rescheduleKernelAlarmsLocked();
2402 updateNextAlarmClockLocked();
2403 if (mPendingNonWakeupAlarms.size() > 0) {
2404 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
2405 triggerList.addAll(mPendingNonWakeupAlarms);
2406 Collections.sort(triggerList, mAlarmDispatchComparator);
2407 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2408 mTotalDelayTime += thisDelayTime;
2409 if (mMaxDelayTime < thisDelayTime) {
2410 mMaxDelayTime = thisDelayTime;
2411 }
2412 mPendingNonWakeupAlarms.clear();
2413 }
2414 deliverAlarmsLocked(triggerList, nowELAPSED);
2415 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002416 }
2417 }
2418 }
2419 }
2420 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002421
David Christieebe51fc2013-07-26 13:23:29 -07002422 /**
2423 * Attribute blame for a WakeLock.
2424 * @param pi PendingIntent to attribute blame to if ws is null.
2425 * @param ws WorkSource to attribute blame.
2426 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002427 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
2428 boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07002429 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002430 final boolean unimportant = pi == mTimeTickSender;
2431 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002432 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002433 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002434 } else {
2435 mWakeLock.setHistoryTag(null);
2436 }
2437 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07002438 if (ws != null) {
2439 mWakeLock.setWorkSource(ws);
2440 return;
2441 }
2442
Christopher Tatec4a07d12012-04-06 14:19:13 -07002443 final int uid = ActivityManagerNative.getDefault()
2444 .getUidForIntentSender(pi.getTarget());
2445 if (uid >= 0) {
2446 mWakeLock.setWorkSource(new WorkSource(uid));
2447 return;
2448 }
Susheel Yadagiri6837e452015-07-09 13:01:39 -07002449 // Something went wrong; fall back to attributing the lock to the OS
2450 mWakeLock.setWorkSource(null);
Christopher Tatec4a07d12012-04-06 14:19:13 -07002451 } catch (Exception e) {
2452 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002453 }
2454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002455 private class AlarmHandler extends Handler {
2456 public static final int ALARM_EVENT = 1;
2457 public static final int MINUTE_CHANGE_EVENT = 2;
2458 public static final int DATE_CHANGE_EVENT = 3;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002459 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002460
2461 public AlarmHandler() {
2462 }
2463
2464 public void handleMessage(Message msg) {
2465 if (msg.what == ALARM_EVENT) {
2466 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2467 synchronized (mLock) {
2468 final long nowRTC = System.currentTimeMillis();
Christopher Tatee0a22b32013-07-11 14:43:13 -07002469 final long nowELAPSED = SystemClock.elapsedRealtime();
2470 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002471 updateNextAlarmClockLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002472 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002474 // now trigger the alarms without the lock held
Dianne Hackborn390517b2013-05-30 15:03:32 -07002475 for (int i=0; i<triggerList.size(); i++) {
2476 Alarm alarm = triggerList.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002477 try {
2478 alarm.operation.send();
2479 } catch (PendingIntent.CanceledException e) {
2480 if (alarm.repeatInterval > 0) {
2481 // This IntentSender is no longer valid, but this
2482 // is a repeating alarm, so toss the hoser.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002483 removeImpl(alarm.operation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002484 }
2485 }
2486 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002487 } else if (msg.what == SEND_NEXT_ALARM_CLOCK_CHANGED) {
2488 sendNextAlarmClockChanged();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002489 }
2490 }
2491 }
2492
2493 class ClockReceiver extends BroadcastReceiver {
2494 public ClockReceiver() {
2495 IntentFilter filter = new IntentFilter();
2496 filter.addAction(Intent.ACTION_TIME_TICK);
2497 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002498 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499 }
2500
2501 @Override
2502 public void onReceive(Context context, Intent intent) {
2503 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07002504 if (DEBUG_BATCH) {
2505 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
2506 }
2507 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002508 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
2509 // Since the kernel does not keep track of DST, we need to
2510 // reset the TZ information at the beginning of each day
2511 // based off of the current Zone gmt offset + userspace tracked
2512 // daylight savings information.
2513 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02002514 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002515 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07002516 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002517 }
2518 }
2519
2520 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07002521 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09002522 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07002523
2524 // Schedule this event for the amount of time that it would take to get to
2525 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09002526 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07002527
David Christieebe51fc2013-07-26 13:23:29 -07002528 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002529 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07002530 0, mTimeTickSender, AlarmManager.FLAG_STANDALONE, workSource, null,
2531 Process.myUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002532 }
Christopher Tate385e4982013-07-23 18:22:29 -07002533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 public void scheduleDateChangedEvent() {
2535 Calendar calendar = Calendar.getInstance();
2536 calendar.setTimeInMillis(System.currentTimeMillis());
2537 calendar.set(Calendar.HOUR, 0);
2538 calendar.set(Calendar.MINUTE, 0);
2539 calendar.set(Calendar.SECOND, 0);
2540 calendar.set(Calendar.MILLISECOND, 0);
2541 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07002542
2543 final WorkSource workSource = null; // Let system take blame for date change events.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002544 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender,
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07002545 AlarmManager.FLAG_STANDALONE, workSource, null, Process.myUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002546 }
2547 }
2548
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002549 class InteractiveStateReceiver extends BroadcastReceiver {
2550 public InteractiveStateReceiver() {
2551 IntentFilter filter = new IntentFilter();
2552 filter.addAction(Intent.ACTION_SCREEN_OFF);
2553 filter.addAction(Intent.ACTION_SCREEN_ON);
2554 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
2555 getContext().registerReceiver(this, filter);
2556 }
2557
2558 @Override
2559 public void onReceive(Context context, Intent intent) {
2560 synchronized (mLock) {
2561 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
2562 }
2563 }
2564 }
2565
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 class UninstallReceiver extends BroadcastReceiver {
2567 public UninstallReceiver() {
2568 IntentFilter filter = new IntentFilter();
2569 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2570 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002571 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002572 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08002573 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002574 // Register for events related to sdcard installation.
2575 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08002576 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002577 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07002578 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002579 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002580 }
2581
2582 @Override
2583 public void onReceive(Context context, Intent intent) {
2584 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002585 String action = intent.getAction();
2586 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002587 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
2588 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
2589 for (String packageName : pkgList) {
2590 if (lookForPackageLocked(packageName)) {
2591 setResultCode(Activity.RESULT_OK);
2592 return;
2593 }
2594 }
2595 return;
2596 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002597 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002598 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
2599 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
2600 if (userHandle >= 0) {
2601 removeUserLocked(userHandle);
2602 }
Dianne Hackborn3d1933c2015-06-10 16:25:57 -07002603 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
2604 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
2605 if (uid >= 0) {
2606 mLastAllowWhileIdleDispatch.delete(uid);
2607 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002608 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08002609 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
2610 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
2611 // This package is being updated; don't kill its alarms.
2612 return;
2613 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002614 Uri data = intent.getData();
2615 if (data != null) {
2616 String pkg = data.getSchemeSpecificPart();
2617 if (pkg != null) {
2618 pkgList = new String[]{pkg};
2619 }
2620 }
2621 }
2622 if (pkgList != null && (pkgList.length > 0)) {
2623 for (String pkg : pkgList) {
2624 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07002625 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002626 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
2627 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
2628 if (uidStats.remove(pkg) != null) {
2629 if (uidStats.size() <= 0) {
2630 mBroadcastStats.removeAt(i);
2631 }
2632 }
2633 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002634 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002635 }
2636 }
2637 }
2638 }
2639
2640 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002641 String pkg = pi.getCreatorPackage();
2642 int uid = pi.getCreatorUid();
2643 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
2644 if (uidStats == null) {
2645 uidStats = new ArrayMap<String, BroadcastStats>();
2646 mBroadcastStats.put(uid, uidStats);
2647 }
2648 BroadcastStats bs = uidStats.get(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002649 if (bs == null) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002650 bs = new BroadcastStats(uid, pkg);
2651 uidStats.put(pkg, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002652 }
2653 return bs;
2654 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002655
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002656 class ResultReceiver implements PendingIntent.OnFinished {
2657 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
2658 String resultData, Bundle resultExtras) {
2659 synchronized (mLock) {
Susheel Yadagiri6837e452015-07-09 13:01:39 -07002660 int uid = 0;
Dianne Hackborn81038902012-11-26 17:04:09 -08002661 InFlight inflight = null;
2662 for (int i=0; i<mInFlight.size(); i++) {
2663 if (mInFlight.get(i).mPendingIntent == pi) {
Susheel Yadagiri6837e452015-07-09 13:01:39 -07002664 uid = mInFlight.get(i).mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -08002665 inflight = mInFlight.remove(i);
2666 break;
2667 }
2668 }
2669 if (inflight != null) {
2670 final long nowELAPSED = SystemClock.elapsedRealtime();
2671 BroadcastStats bs = inflight.mBroadcastStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002672 bs.nesting--;
2673 if (bs.nesting <= 0) {
2674 bs.nesting = 0;
Dianne Hackborn81038902012-11-26 17:04:09 -08002675 bs.aggregateTime += nowELAPSED - bs.startTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002676 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002677 FilterStats fs = inflight.mFilterStats;
2678 fs.nesting--;
2679 if (fs.nesting <= 0) {
2680 fs.nesting = 0;
2681 fs.aggregateTime += nowELAPSED - fs.startTime;
2682 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07002683 if (RECORD_ALARMS_IN_HISTORY) {
2684 if (inflight.mWorkSource != null && inflight.mWorkSource.size() > 0) {
2685 for (int wi=0; wi<inflight.mWorkSource.size(); wi++) {
2686 ActivityManagerNative.noteAlarmFinish(
2687 pi, inflight.mWorkSource.get(wi), inflight.mTag);
2688 }
2689 } else {
2690 ActivityManagerNative.noteAlarmFinish(
2691 pi, -1, inflight.mTag);
2692 }
2693 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002694 } else {
2695 mLog.w("No in-flight alarm for " + pi + " " + intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002696 }
2697 mBroadcastRefCount--;
Susheel Yadagiri6837e452015-07-09 13:01:39 -07002698 mTriggeredUids.remove(new Integer(uid));
2699
2700 if (checkReleaseWakeLock()) {
2701 if (mWakeLock.isHeld()) {
2702 mWakeLock.release();
2703 if (localLOGV) Slog.v(TAG, "AM WakeLock Released Internally onSendFinish");
2704 }
2705 }
2706
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002707 if (mBroadcastRefCount == 0) {
Susheel Yadagiri6837e452015-07-09 13:01:39 -07002708 if (mWakeLock.isHeld()) {
2709 mWakeLock.release();
2710 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002711 if (mInFlight.size() > 0) {
2712 mLog.w("Finished all broadcasts with " + mInFlight.size()
2713 + " remaining inflights");
2714 for (int i=0; i<mInFlight.size(); i++) {
2715 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
2716 }
2717 mInFlight.clear();
2718 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002719 } else {
2720 // the next of our alarms is now in flight. reattribute the wakelock.
Susheel Yadagirid6b1fca2015-10-28 16:42:37 -07002721 InFlight inFlight = null;
Dianne Hackborn81038902012-11-26 17:04:09 -08002722 if (mInFlight.size() > 0) {
Susheel Yadagirid6b1fca2015-10-28 16:42:37 -07002723 for(int index = 0; index < mInFlight.size(); index++){
2724 inFlight = mInFlight.get(index);
2725 if(!mBlockedUids.contains(inFlight.mUid)) break;
2726 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -08002727 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002728 inFlight.mAlarmType, inFlight.mTag, false);
Christopher Tatec4a07d12012-04-06 14:19:13 -07002729 } else {
2730 // should never happen
Dianne Hackborn81038902012-11-26 17:04:09 -08002731 mLog.w("Alarm wakelock still held but sent queue empty");
Christopher Tatec4a07d12012-04-06 14:19:13 -07002732 mWakeLock.setWorkSource(null);
2733 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002734 }
2735 }
2736 }
2737 }
2738}