blob: 5ffb7385fcc3a28497be685404277111263d9936 [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;
Christopher Tate57ceaaa2013-07-19 16:30:43 -070021import android.app.AlarmManager;
Christopher Tate14a7bb02015-10-01 10:24:31 -070022import android.app.AppOpsManager;
Dianne Hackborna750a632015-06-16 17:18:23 -070023import android.app.BroadcastOptions;
Christopher Tate14a7bb02015-10-01 10:24:31 -070024import android.app.IAlarmCompleteListener;
25import android.app.IAlarmListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.app.IAlarmManager;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070027import android.app.IUidObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.app.PendingIntent;
29import android.content.BroadcastReceiver;
Dianne Hackborna750a632015-06-16 17:18:23 -070030import android.content.ContentResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.content.Context;
32import android.content.Intent;
33import android.content.IntentFilter;
34import android.content.pm.PackageManager;
Dianne Hackborna750a632015-06-16 17:18:23 -070035import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.net.Uri;
37import android.os.Binder;
38import android.os.Bundle;
39import android.os.Handler;
Adam Lesinski182f73f2013-12-05 16:48:06 -080040import android.os.IBinder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.os.Message;
42import android.os.PowerManager;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070043import android.os.Process;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070044import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.os.SystemClock;
46import android.os.SystemProperties;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070047import android.os.UserHandle;
Christopher Tatec4a07d12012-04-06 14:19:13 -070048import android.os.WorkSource;
Adrian Roosc42a1e12014-07-07 23:35:53 +020049import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.text.TextUtils;
Adrian Roosc42a1e12014-07-07 23:35:53 +020051import android.text.format.DateFormat;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080052import android.util.ArrayMap;
Dianne Hackborna750a632015-06-16 17:18:23 -070053import android.util.KeyValueListParser;
Adrian Roosc42a1e12014-07-07 23:35:53 +020054import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080055import android.util.Slog;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080056import android.util.SparseArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +020057import android.util.SparseBooleanArray;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -070058import android.util.SparseLongArray;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070059import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060
Christopher Tate4cb338d2013-07-26 13:11:31 -070061import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import java.io.FileDescriptor;
63import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070064import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -080066import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import java.util.Calendar;
68import java.util.Collections;
69import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -050070import java.util.Date;
Christopher Tate1590f1e2014-10-02 17:27:57 -070071import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -070072import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +020073import java.util.Locale;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070074import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import java.util.TimeZone;
John Spurlock604a5ee2015-06-01 12:27:22 -040076import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077
Christopher Tatee0a22b32013-07-11 14:43:13 -070078import static android.app.AlarmManager.RTC_WAKEUP;
79import static android.app.AlarmManager.RTC;
80import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
81import static android.app.AlarmManager.ELAPSED_REALTIME;
82
Dianne Hackborn81038902012-11-26 17:04:09 -080083import com.android.internal.util.LocalLog;
84
Adam Lesinski182f73f2013-12-05 16:48:06 -080085class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -070086 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
87 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -080088 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -070089 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -080090 static final int TIME_CHANGED_MASK = 1 << 16;
91 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -080092
Christopher Tatee0a22b32013-07-11 14:43:13 -070093 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -080094 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -080095
Adam Lesinski182f73f2013-12-05 16:48:06 -080096 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -080097 static final boolean localLOGV = false;
98 static final boolean DEBUG_BATCH = localLOGV || false;
99 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200100 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700101 static final boolean DEBUG_LISTENER_CALLBACK = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700102 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700103 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800104 static final int ALARM_EVENT = 1;
105 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200106
Christopher Tate14a7bb02015-10-01 10:24:31 -0700107 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800109 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110
Adam Lesinski182f73f2013-12-05 16:48:06 -0800111 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700112
Christopher Tate24cd46f2016-02-02 14:28:01 -0800113 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT =
114 new Intent(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED)
115 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Adrian Roosc42a1e12014-07-07 23:35:53 +0200116
Adam Lesinski182f73f2013-12-05 16:48:06 -0800117 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800118
Christopher Tate14a7bb02015-10-01 10:24:31 -0700119 AppOpsManager mAppOps;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800120 DeviceIdleController.LocalService mLocalDeviceIdleController;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700121
Adam Lesinski182f73f2013-12-05 16:48:06 -0800122 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800123
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800124 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800125 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700126 private long mNextNonWakeup;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -0700127 private long mLastWakeupSet;
128 private long mLastWakeup;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800129 int mBroadcastRefCount = 0;
130 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700131 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700132 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
133 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800134 final AlarmHandler mHandler = new AlarmHandler();
135 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700136 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700138 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800139 PendingIntent mTimeTickSender;
140 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700141 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700142 boolean mInteractive = true;
143 long mNonInteractiveStartTime;
144 long mNonInteractiveTime;
145 long mLastAlarmDeliveryTime;
146 long mStartCurrentDelayTime;
147 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700148 long mLastTimeChangeClockTime;
149 long mLastTimeChangeRealtime;
Dianne Hackborna750a632015-06-16 17:18:23 -0700150 long mAllowWhileIdleMinTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700151 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800152
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700153 /**
Dianne Hackborn262ae5c2016-02-10 16:28:29 -0800154 * The current set of user whitelisted apps for device idle mode, meaning these are allowed
155 * to freely schedule alarms.
156 */
157 int[] mDeviceIdleUserWhitelist = new int[0];
158
159 /**
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700160 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
161 * used to determine the earliest we can dispatch the next such alarm.
162 */
163 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
164
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700165 final static class IdleDispatchEntry {
166 int uid;
167 String pkg;
168 String tag;
169 String op;
170 long elapsedRealtime;
171 long argRealtime;
172 }
173 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
174
Dianne Hackborna750a632015-06-16 17:18:23 -0700175 /**
176 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
177 */
178 Bundle mIdleOptions;
179
Jose Lima235510e2014-08-13 12:50:01 -0700180 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
181 new SparseArray<>();
182 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
183 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200184 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
185 new SparseBooleanArray();
186 private boolean mNextAlarmClockMayChange;
187
188 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700189 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
190 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200191
Dianne Hackborna750a632015-06-16 17:18:23 -0700192 /**
193 * All times are in milliseconds. These constants are kept synchronized with the system
194 * global Settings. Any access to this class or its fields should be done while
195 * holding the AlarmManagerService.mLock lock.
196 */
197 private final class Constants extends ContentObserver {
198 // Key names stored in the settings value.
199 private static final String KEY_MIN_FUTURITY = "min_futurity";
200 private static final String KEY_MIN_INTERVAL = "min_interval";
201 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
202 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
203 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
204 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700205 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Dianne Hackborna750a632015-06-16 17:18:23 -0700206
207 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
208 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tateaa244da2015-08-27 15:57:57 -0700209 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700210 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700211 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
212
Christopher Tate14a7bb02015-10-01 10:24:31 -0700213 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
214
Dianne Hackborna750a632015-06-16 17:18:23 -0700215 // Minimum futurity of a new alarm
216 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
217
218 // Minimum alarm recurrence interval
219 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
220
221 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
222 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
223
224 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
225 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
226
227 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
228 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
229 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
230
Christopher Tate14a7bb02015-10-01 10:24:31 -0700231 // Direct alarm listener callback timeout
232 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
233
Dianne Hackborna750a632015-06-16 17:18:23 -0700234 private ContentResolver mResolver;
235 private final KeyValueListParser mParser = new KeyValueListParser(',');
236 private long mLastAllowWhileIdleWhitelistDuration = -1;
237
238 public Constants(Handler handler) {
239 super(handler);
240 updateAllowWhileIdleMinTimeLocked();
241 updateAllowWhileIdleWhitelistDurationLocked();
242 }
243
244 public void start(ContentResolver resolver) {
245 mResolver = resolver;
246 mResolver.registerContentObserver(Settings.Global.getUriFor(
247 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
248 updateConstants();
249 }
250
251 public void updateAllowWhileIdleMinTimeLocked() {
252 mAllowWhileIdleMinTime = mPendingIdleUntil != null
253 ? ALLOW_WHILE_IDLE_LONG_TIME : ALLOW_WHILE_IDLE_SHORT_TIME;
254 }
255
256 public void updateAllowWhileIdleWhitelistDurationLocked() {
257 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
258 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
259 BroadcastOptions opts = BroadcastOptions.makeBasic();
260 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
261 mIdleOptions = opts.toBundle();
262 }
263 }
264
265 @Override
266 public void onChange(boolean selfChange, Uri uri) {
267 updateConstants();
268 }
269
270 private void updateConstants() {
271 synchronized (mLock) {
272 try {
273 mParser.setString(Settings.Global.getString(mResolver,
274 Settings.Global.ALARM_MANAGER_CONSTANTS));
275 } catch (IllegalArgumentException e) {
276 // Failed to parse the settings string, log this and move on
277 // with defaults.
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800278 Slog.e(TAG, "Bad alarm manager settings", e);
Dianne Hackborna750a632015-06-16 17:18:23 -0700279 }
280
281 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
282 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
283 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
284 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
285 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
286 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
287 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
288 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
289 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700290 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
291 DEFAULT_LISTENER_TIMEOUT);
Dianne Hackborna750a632015-06-16 17:18:23 -0700292
293 updateAllowWhileIdleMinTimeLocked();
294 updateAllowWhileIdleWhitelistDurationLocked();
295 }
296 }
297
298 void dump(PrintWriter pw) {
299 pw.println(" Settings:");
300
301 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
302 TimeUtils.formatDuration(MIN_FUTURITY, pw);
303 pw.println();
304
305 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
306 TimeUtils.formatDuration(MIN_INTERVAL, pw);
307 pw.println();
308
Christopher Tate14a7bb02015-10-01 10:24:31 -0700309 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
310 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
311 pw.println();
312
Dianne Hackborna750a632015-06-16 17:18:23 -0700313 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
314 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
315 pw.println();
316
317 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
318 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
319 pw.println();
320
321 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
322 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
323 pw.println();
324 }
325 }
326
327 final Constants mConstants;
328
Christopher Tate1590f1e2014-10-02 17:27:57 -0700329 // Alarm delivery ordering bookkeeping
330 static final int PRIO_TICK = 0;
331 static final int PRIO_WAKEUP = 1;
332 static final int PRIO_NORMAL = 2;
333
Dianne Hackborna750a632015-06-16 17:18:23 -0700334 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700335 int seq;
336 int priority;
337
338 PriorityClass() {
339 seq = mCurrentSeq - 1;
340 priority = PRIO_NORMAL;
341 }
342 }
343
Dianne Hackborna750a632015-06-16 17:18:23 -0700344 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700345 int mCurrentSeq = 0;
346
Dianne Hackborna750a632015-06-16 17:18:23 -0700347 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700348 public long when;
349 public int uid;
350 public String action;
351
352 public WakeupEvent(long theTime, int theUid, String theAction) {
353 when = theTime;
354 uid = theUid;
355 action = theAction;
356 }
357 }
358
Adam Lesinski182f73f2013-12-05 16:48:06 -0800359 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
360 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700361
Adrian Roosc42a1e12014-07-07 23:35:53 +0200362 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700363 long start; // These endpoints are always in ELAPSED
364 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700365 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700366
367 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
368
369 Batch() {
370 start = 0;
371 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700372 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700373 }
374
375 Batch(Alarm seed) {
376 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700377 end = seed.maxWhenElapsed;
378 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700379 alarms.add(seed);
380 }
381
382 int size() {
383 return alarms.size();
384 }
385
386 Alarm get(int index) {
387 return alarms.get(index);
388 }
389
390 boolean canHold(long whenElapsed, long maxWhen) {
391 return (end >= whenElapsed) && (start <= maxWhen);
392 }
393
394 boolean add(Alarm alarm) {
395 boolean newStart = false;
396 // narrows the batch if necessary; presumes that canHold(alarm) is true
397 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
398 if (index < 0) {
399 index = 0 - index - 1;
400 }
401 alarms.add(index, alarm);
402 if (DEBUG_BATCH) {
403 Slog.v(TAG, "Adding " + alarm + " to " + this);
404 }
405 if (alarm.whenElapsed > start) {
406 start = alarm.whenElapsed;
407 newStart = true;
408 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700409 if (alarm.maxWhenElapsed < end) {
410 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700411 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700412 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700413
414 if (DEBUG_BATCH) {
415 Slog.v(TAG, " => now " + this);
416 }
417 return newStart;
418 }
419
Christopher Tate14a7bb02015-10-01 10:24:31 -0700420 boolean remove(final PendingIntent operation, final IAlarmListener listener) {
421 if (operation == null && listener == null) {
422 if (localLOGV) {
423 Slog.w(TAG, "requested remove() of null operation",
424 new RuntimeException("here"));
425 }
426 return false;
427 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700428 boolean didRemove = false;
429 long newStart = 0; // recalculate endpoints as we go
430 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700431 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700432 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700433 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700434 if (alarm.matches(operation, listener)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700435 alarms.remove(i);
436 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200437 if (alarm.alarmClock != null) {
438 mNextAlarmClockMayChange = true;
439 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700440 } else {
441 if (alarm.whenElapsed > newStart) {
442 newStart = alarm.whenElapsed;
443 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700444 if (alarm.maxWhenElapsed < newEnd) {
445 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700446 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700447 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700448 i++;
449 }
450 }
451 if (didRemove) {
452 // commit the new batch bounds
453 start = newStart;
454 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700455 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700456 }
457 return didRemove;
458 }
459
460 boolean remove(final String packageName) {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700461 if (packageName == null) {
462 if (localLOGV) {
463 Slog.w(TAG, "requested remove() of null packageName",
464 new RuntimeException("here"));
465 }
466 return false;
467 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700468 boolean didRemove = false;
469 long newStart = 0; // recalculate endpoints as we go
470 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700471 int newFlags = 0;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700472 for (int i = alarms.size()-1; i >= 0; i--) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700473 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700474 if (alarm.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700475 alarms.remove(i);
476 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200477 if (alarm.alarmClock != null) {
478 mNextAlarmClockMayChange = true;
479 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700480 } else {
481 if (alarm.whenElapsed > newStart) {
482 newStart = alarm.whenElapsed;
483 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700484 if (alarm.maxWhenElapsed < newEnd) {
485 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700486 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700487 newFlags |= alarm.flags;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700488 }
489 }
490 if (didRemove) {
491 // commit the new batch bounds
492 start = newStart;
493 end = newEnd;
494 flags = newFlags;
495 }
496 return didRemove;
497 }
498
499 boolean removeForStopped(final int uid) {
500 boolean didRemove = false;
501 long newStart = 0; // recalculate endpoints as we go
502 long newEnd = Long.MAX_VALUE;
503 int newFlags = 0;
504 for (int i = alarms.size()-1; i >= 0; i--) {
505 Alarm alarm = alarms.get(i);
506 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800507 if (alarm.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
508 uid, alarm.packageName)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700509 alarms.remove(i);
510 didRemove = true;
511 if (alarm.alarmClock != null) {
512 mNextAlarmClockMayChange = true;
513 }
514 } else {
515 if (alarm.whenElapsed > newStart) {
516 newStart = alarm.whenElapsed;
517 }
518 if (alarm.maxWhenElapsed < newEnd) {
519 newEnd = alarm.maxWhenElapsed;
520 }
521 newFlags |= alarm.flags;
522 }
523 } catch (RemoteException e) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700524 }
525 }
526 if (didRemove) {
527 // commit the new batch bounds
528 start = newStart;
529 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700530 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700531 }
532 return didRemove;
533 }
534
535 boolean remove(final int userHandle) {
536 boolean didRemove = false;
537 long newStart = 0; // recalculate endpoints as we go
538 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700539 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700540 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700541 if (UserHandle.getUserId(alarm.creatorUid) == userHandle) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700542 alarms.remove(i);
543 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200544 if (alarm.alarmClock != null) {
545 mNextAlarmClockMayChange = true;
546 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700547 } else {
548 if (alarm.whenElapsed > newStart) {
549 newStart = alarm.whenElapsed;
550 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700551 if (alarm.maxWhenElapsed < newEnd) {
552 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700553 }
554 i++;
555 }
556 }
557 if (didRemove) {
558 // commit the new batch bounds
559 start = newStart;
560 end = newEnd;
561 }
562 return didRemove;
563 }
564
565 boolean hasPackage(final String packageName) {
566 final int N = alarms.size();
567 for (int i = 0; i < N; i++) {
568 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700569 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700570 return true;
571 }
572 }
573 return false;
574 }
575
576 boolean hasWakeups() {
577 final int N = alarms.size();
578 for (int i = 0; i < N; i++) {
579 Alarm a = alarms.get(i);
580 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
581 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
582 return true;
583 }
584 }
585 return false;
586 }
587
588 @Override
589 public String toString() {
590 StringBuilder b = new StringBuilder(40);
591 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
592 b.append(" num="); b.append(size());
593 b.append(" start="); b.append(start);
594 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700595 if (flags != 0) {
596 b.append(" flgs=0x");
597 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700598 }
599 b.append('}');
600 return b.toString();
601 }
602 }
603
604 static class BatchTimeOrder implements Comparator<Batch> {
605 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800606 long when1 = b1.start;
607 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800608 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700609 return 1;
610 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800611 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700612 return -1;
613 }
614 return 0;
615 }
616 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800617
618 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
619 @Override
620 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700621 // priority class trumps everything. TICK < WAKEUP < NORMAL
622 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
623 return -1;
624 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
625 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800626 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700627
628 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800629 if (lhs.whenElapsed < rhs.whenElapsed) {
630 return -1;
631 } else if (lhs.whenElapsed > rhs.whenElapsed) {
632 return 1;
633 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700634
635 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800636 return 0;
637 }
638 };
639
Christopher Tate1590f1e2014-10-02 17:27:57 -0700640 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
641 final int N = alarms.size();
642 for (int i = 0; i < N; i++) {
643 Alarm a = alarms.get(i);
644
645 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700646 if (a.operation != null
647 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700648 alarmPrio = PRIO_TICK;
649 } else if (a.wakeup) {
650 alarmPrio = PRIO_WAKEUP;
651 } else {
652 alarmPrio = PRIO_NORMAL;
653 }
654
655 PriorityClass packagePrio = a.priorityClass;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700656 String alarmPackage = (a.operation != null)
657 ? a.operation.getCreatorPackage()
658 : a.packageName;
659 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700660 if (packagePrio == null) {
661 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700662 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700663 }
664 a.priorityClass = packagePrio;
665
666 if (packagePrio.seq != mCurrentSeq) {
667 // first alarm we've seen in the current delivery generation from this package
668 packagePrio.priority = alarmPrio;
669 packagePrio.seq = mCurrentSeq;
670 } else {
671 // Multiple alarms from this package being delivered in this generation;
672 // bump the package's delivery class if it's warranted.
673 // TICK < WAKEUP < NORMAL
674 if (alarmPrio < packagePrio.priority) {
675 packagePrio.priority = alarmPrio;
676 }
677 }
678 }
679 }
680
Christopher Tatee0a22b32013-07-11 14:43:13 -0700681 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800682 static final long MIN_FUZZABLE_INTERVAL = 10000;
683 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700684 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
685
686 // set to null if in idle mode; while in this mode, any alarms we don't want
687 // to run during this time are placed in mPendingWhileIdleAlarms
688 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700689 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700690 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700691
Jeff Brownb880d882014-02-10 19:47:07 -0800692 public AlarmManagerService(Context context) {
693 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700694 mConstants = new Constants(mHandler);
Jeff Brownb880d882014-02-10 19:47:07 -0800695 }
696
Christopher Tatee0a22b32013-07-11 14:43:13 -0700697 static long convertToElapsed(long when, int type) {
698 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
699 if (isRtc) {
700 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
701 }
702 return when;
703 }
704
705 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
706 // calculate the end of our nominal delivery window for the alarm.
707 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
708 // Current heuristic: batchable window is 75% of either the recurrence interval
709 // [for a periodic alarm] or of the time from now to the desired delivery time,
710 // with a minimum delay/interval of 10 seconds, under which we will simply not
711 // defer the alarm.
712 long futurity = (interval == 0)
713 ? (triggerAtTime - now)
714 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700715 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700716 futurity = 0;
717 }
718 return triggerAtTime + (long)(.75 * futurity);
719 }
720
721 // returns true if the batch was added at the head
722 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
723 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
724 if (index < 0) {
725 index = 0 - index - 1;
726 }
727 list.add(index, newBatch);
728 return (index == 0);
729 }
730
Christopher Tate385e4982013-07-23 18:22:29 -0700731 // Return the index of the matching batch, or -1 if none found.
732 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700733 final int N = mAlarmBatches.size();
734 for (int i = 0; i < N; i++) {
735 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700736 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700737 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700738 }
739 }
Christopher Tate385e4982013-07-23 18:22:29 -0700740 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700741 }
742
743 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
744 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700745 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700746 rebatchAllAlarmsLocked(true);
747 }
748 }
749
750 void rebatchAllAlarmsLocked(boolean doValidate) {
751 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
752 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700753 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700754 final long nowElapsed = SystemClock.elapsedRealtime();
755 final int oldBatches = oldSet.size();
756 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
757 Batch batch = oldSet.get(batchNum);
758 final int N = batch.size();
759 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700760 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700761 }
762 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700763 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
764 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
765 + " to " + mPendingIdleUntil);
766 if (mPendingIdleUntil == null) {
767 // Somehow we lost this... we need to restore all of the pending alarms.
768 restorePendingWhileIdleAlarmsLocked();
769 }
770 }
771 rescheduleKernelAlarmsLocked();
772 updateNextAlarmClockLocked();
773 }
774
775 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
776 a.when = a.origWhen;
777 long whenElapsed = convertToElapsed(a.when, a.type);
778 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700779 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700780 // Exact
781 maxElapsed = whenElapsed;
782 } else {
783 // Not exact. Preserve any explicit window, otherwise recalculate
784 // the window based on the alarm's new futurity. Note that this
785 // reflects a policy of preferring timely to deferred delivery.
786 maxElapsed = (a.windowLength > 0)
787 ? (whenElapsed + a.windowLength)
788 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
789 }
790 a.whenElapsed = whenElapsed;
791 a.maxWhenElapsed = maxElapsed;
792 setImplLocked(a, true, doValidate);
793 }
794
795 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700796 if (RECORD_DEVICE_IDLE_ALARMS) {
797 IdleDispatchEntry ent = new IdleDispatchEntry();
798 ent.uid = 0;
799 ent.pkg = "FINISH IDLE";
800 ent.elapsedRealtime = SystemClock.elapsedRealtime();
801 mAllowWhileIdleDispatches.add(ent);
802 }
803
Dianne Hackborn35d54032015-04-23 10:30:43 -0700804 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700805 if (mPendingWhileIdleAlarms.size() > 0) {
806 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
807 mPendingWhileIdleAlarms = new ArrayList<>();
808 final long nowElapsed = SystemClock.elapsedRealtime();
809 for (int i=alarms.size() - 1; i >= 0; i--) {
810 Alarm a = alarms.get(i);
811 reAddAlarmLocked(a, nowElapsed, false);
812 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700813 }
Dianne Hackborn35d54032015-04-23 10:30:43 -0700814
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700815 // Make sure we are using the correct ALLOW_WHILE_IDLE min time.
Dianne Hackborna750a632015-06-16 17:18:23 -0700816 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700817
Dianne Hackborn35d54032015-04-23 10:30:43 -0700818 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700819 rescheduleKernelAlarmsLocked();
820 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -0700821
822 // And send a TIME_TICK right now, since it is important to get the UI updated.
823 try {
824 mTimeTickSender.send();
825 } catch (PendingIntent.CanceledException e) {
826 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700827 }
828
Christopher Tate14a7bb02015-10-01 10:24:31 -0700829 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -0800830 final PendingIntent mPendingIntent;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700831 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -0700832 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700833 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700834 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800835 final BroadcastStats mBroadcastStats;
836 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800837 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800838
Christopher Tate14a7bb02015-10-01 10:24:31 -0700839 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
840 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
841 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800842 mPendingIntent = pendingIntent;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700843 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -0700844 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700845 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700846 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700847 mBroadcastStats = (pendingIntent != null)
848 ? service.getStatsLocked(pendingIntent)
849 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700850 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -0800851 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700852 fs = new FilterStats(mBroadcastStats, mTag);
853 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -0800854 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700855 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -0800856 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800857 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800858 }
Makoto Onuki33955e12017-03-01 18:11:00 -0800859
860 @Override
861 public String toString() {
862 return "InFlight{"
863 + "pendingIntent=" + mPendingIntent
864 + ", workSource=" + mWorkSource
865 + ", uid=" + mUid
866 + ", tag=" + mTag
867 + ", broadcastStats=" + mBroadcastStats
868 + ", filterStats=" + mFilterStats
869 + ", alarmType=" + mAlarmType
870 + "}";
871 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800873
Adam Lesinski182f73f2013-12-05 16:48:06 -0800874 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -0800875 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700876 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800877
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700878 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800880 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 int numWakeup;
882 long startTime;
883 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -0800884
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700885 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800886 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700887 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800888 }
Makoto Onuki33955e12017-03-01 18:11:00 -0800889
890 @Override
891 public String toString() {
892 return "FilterStats{"
893 + "tag=" + mTag
894 + ", lastTime=" + lastTime
895 + ", aggregateTime=" + aggregateTime
896 + ", count=" + count
897 + ", numWakeup=" + numWakeup
898 + ", startTime=" + startTime
899 + ", nesting=" + nesting
900 + "}";
901 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800902 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700903
Adam Lesinski182f73f2013-12-05 16:48:06 -0800904 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800905 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800906 final String mPackageName;
907
908 long aggregateTime;
909 int count;
910 int numWakeup;
911 long startTime;
912 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700913 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -0800914
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800915 BroadcastStats(int uid, String packageName) {
916 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800917 mPackageName = packageName;
918 }
Makoto Onuki33955e12017-03-01 18:11:00 -0800919
920 @Override
921 public String toString() {
922 return "BroadcastStats{"
923 + "uid=" + mUid
924 + ", packageName=" + mPackageName
925 + ", aggregateTime=" + aggregateTime
926 + ", count=" + count
927 + ", numWakeup=" + numWakeup
928 + ", startTime=" + startTime
929 + ", nesting=" + nesting
930 + "}";
931 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700933
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800934 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
935 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700936
937 int mNumDelayedAlarms = 0;
938 long mTotalDelayTime = 0;
939 long mMaxDelayTime = 0;
940
Adam Lesinski182f73f2013-12-05 16:48:06 -0800941 @Override
942 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800943 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800944 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800945
946 // We have to set current TimeZone info to kernel
947 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -0800948 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800949
Adam Lesinski182f73f2013-12-05 16:48:06 -0800950 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800951 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800952
Adam Lesinski182f73f2013-12-05 16:48:06 -0800953 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -0700955 Intent.FLAG_RECEIVER_REGISTERED_ONLY
956 | Intent.FLAG_RECEIVER_FOREGROUND), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700957 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800958 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
959 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800960 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -0700961 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962
963 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -0800964 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 mClockReceiver.scheduleTimeTickEvent();
966 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700967 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 mUninstallReceiver = new UninstallReceiver();
969
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800970 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800971 AlarmThread waitThread = new AlarmThread();
972 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800974 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800976
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700977 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800978 ActivityManager.getService().registerUidObserver(new UidObserver(),
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800979 ActivityManager.UID_OBSERVER_IDLE, ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700980 } catch (RemoteException e) {
981 // ignored; both services live in system_server
982 }
983
Adam Lesinski182f73f2013-12-05 16:48:06 -0800984 publishBinderService(Context.ALARM_SERVICE, mService);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -0800985 publishLocalService(LocalService.class, new LocalService());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 }
Adam Lesinski182f73f2013-12-05 16:48:06 -0800987
988 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -0700989 public void onBootPhase(int phase) {
990 if (phase == PHASE_SYSTEM_SERVICES_READY) {
991 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -0700992 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800993 mLocalDeviceIdleController
994 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackborna750a632015-06-16 17:18:23 -0700995 }
996 }
997
998 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999 protected void finalize() throws Throwable {
1000 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001001 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002 } finally {
1003 super.finalize();
1004 }
1005 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001006
Adam Lesinski182f73f2013-12-05 16:48:06 -08001007 void setTimeZoneImpl(String tz) {
1008 if (TextUtils.isEmpty(tz)) {
1009 return;
David Christieebe51fc2013-07-26 13:23:29 -07001010 }
1011
Adam Lesinski182f73f2013-12-05 16:48:06 -08001012 TimeZone zone = TimeZone.getTimeZone(tz);
1013 // Prevent reentrant calls from stepping on each other when writing
1014 // the time zone property
1015 boolean timeZoneWasChanged = false;
1016 synchronized (this) {
1017 String current = SystemProperties.get(TIMEZONE_PROPERTY);
1018 if (current == null || !current.equals(zone.getID())) {
1019 if (localLOGV) {
1020 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
1021 }
1022 timeZoneWasChanged = true;
1023 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
1024 }
1025
1026 // Update the kernel timezone information
1027 // Kernel tracks time offsets as 'minutes west of GMT'
1028 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001029 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001030 }
1031
1032 TimeZone.setDefault(null);
1033
1034 if (timeZoneWasChanged) {
1035 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
1036 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
1037 intent.putExtra("time-zone", zone.getID());
1038 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1039 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001041
Adam Lesinski182f73f2013-12-05 16:48:06 -08001042 void removeImpl(PendingIntent operation) {
1043 if (operation == null) {
1044 return;
1045 }
1046 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001047 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001048 }
1049 }
1050
1051 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001052 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1053 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1054 int callingUid, String callingPackage) {
1055 // must be *either* PendingIntent or AlarmReceiver, but not both
1056 if ((operation == null && directReceiver == null)
1057 || (operation != null && directReceiver != null)) {
1058 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1059 // NB: previous releases failed silently here, so we are continuing to do the same
1060 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061 return;
1062 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001063
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001064 // Sanity check the window length. This will catch people mistakenly
1065 // trying to pass an end-of-window timestamp rather than a duration.
1066 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1067 Slog.w(TAG, "Window length " + windowLength
1068 + "ms suspiciously long; limiting to 1 hour");
1069 windowLength = AlarmManager.INTERVAL_HOUR;
1070 }
1071
Christopher Tate498c6cb2014-11-17 16:09:27 -08001072 // Sanity check the recurrence interval. This will catch people who supply
1073 // seconds when the API expects milliseconds.
Dianne Hackborna750a632015-06-16 17:18:23 -07001074 final long minInterval = mConstants.MIN_INTERVAL;
1075 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001076 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001077 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001078 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001079 interval = minInterval;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001080 }
1081
Christopher Tatee0a22b32013-07-11 14:43:13 -07001082 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1083 throw new IllegalArgumentException("Invalid alarm type " + type);
1084 }
1085
Christopher Tate5f221e82013-07-30 17:13:15 -07001086 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001087 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001088 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001089 + " pid=" + what);
1090 triggerAtTime = 0;
1091 }
1092
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001093 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001094 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1095 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001096 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001097 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1098
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001099 final long maxElapsed;
1100 if (windowLength == AlarmManager.WINDOW_EXACT) {
1101 maxElapsed = triggerElapsed;
1102 } else if (windowLength < 0) {
1103 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001104 // Fix this window in place, so that as time approaches we don't collapse it.
1105 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001106 } else {
1107 maxElapsed = triggerElapsed + windowLength;
1108 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001111 if (DEBUG_BATCH) {
1112 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001113 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001114 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001115 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001117 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001118 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1119 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 }
1121 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122
Christopher Tate3e04b472013-10-21 17:51:31 -07001123 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001124 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1125 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1126 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001127 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001128 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1129 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001130 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001131 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001132 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1133 + " -- package not allowed to start");
1134 return;
1135 }
1136 } catch (RemoteException e) {
1137 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001138 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001139 setImplLocked(a, false, doValidate);
1140 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001141
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001142 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1143 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001144 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001145 // The caller has given the time they want this to happen at, however we need
1146 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001147 // bring us out of idle at an earlier time.
1148 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001149 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001150 }
1151 // Add fuzz to make the alarm go off some time before the actual desired time.
1152 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001153 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001154 if (fuzz > 0) {
1155 if (mRandom == null) {
1156 mRandom = new Random();
1157 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001158 final int delta = mRandom.nextInt(fuzz);
1159 a.whenElapsed -= delta;
1160 if (false) {
1161 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1162 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1163 Slog.d(TAG, "Applied fuzz: " + fuzz);
1164 Slog.d(TAG, "Final delta: " + delta);
1165 Slog.d(TAG, "Final when: " + a.whenElapsed);
1166 }
1167 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001168 }
1169
1170 } else if (mPendingIdleUntil != null) {
1171 // We currently have an idle until alarm scheduled; if the new alarm has
1172 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001173 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1174 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1175 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001176 == 0) {
1177 mPendingWhileIdleAlarms.add(a);
1178 return;
1179 }
1180 }
1181
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001182 if (RECORD_DEVICE_IDLE_ALARMS) {
1183 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1184 IdleDispatchEntry ent = new IdleDispatchEntry();
1185 ent.uid = a.uid;
1186 ent.pkg = a.operation.getCreatorPackage();
1187 ent.tag = a.operation.getTag("");
1188 ent.op = "SET";
1189 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1190 ent.argRealtime = a.whenElapsed;
1191 mAllowWhileIdleDispatches.add(ent);
1192 }
1193 }
1194
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001195 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
1196 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -07001197 if (whichBatch < 0) {
1198 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001199 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 } else {
Christopher Tate385e4982013-07-23 18:22:29 -07001201 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001202 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001203 // The start time of this batch advanced, so batch ordering may
1204 // have just been broken. Move it to where it now belongs.
1205 mAlarmBatches.remove(whichBatch);
1206 addBatchLocked(mAlarmBatches, batch);
1207 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208 }
1209
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001210 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001211 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001212 }
1213
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001214 boolean needRebatch = false;
1215
1216 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001217 if (RECORD_DEVICE_IDLE_ALARMS) {
1218 if (mPendingIdleUntil == null) {
1219 IdleDispatchEntry ent = new IdleDispatchEntry();
1220 ent.uid = 0;
1221 ent.pkg = "START IDLE";
1222 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1223 mAllowWhileIdleDispatches.add(ent);
1224 }
1225 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001226 mPendingIdleUntil = a;
Dianne Hackborna750a632015-06-16 17:18:23 -07001227 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001228 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001229 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1230 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1231 mNextWakeFromIdle = a;
1232 // If this wake from idle is earlier than whatever was previously scheduled,
1233 // and we are currently idling, then we need to rebatch alarms in case the idle
1234 // until time needs to be updated.
1235 if (mPendingIdleUntil != null) {
1236 needRebatch = true;
1237 }
1238 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001239 }
1240
1241 if (!rebatching) {
1242 if (DEBUG_VALIDATE) {
1243 if (doValidate && !validateConsistencyLocked()) {
1244 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1245 + " when(hex)=" + Long.toHexString(a.when)
1246 + " whenElapsed=" + a.whenElapsed
1247 + " maxWhenElapsed=" + a.maxWhenElapsed
1248 + " interval=" + a.repeatInterval + " op=" + a.operation
1249 + " flags=0x" + Integer.toHexString(a.flags));
1250 rebatchAllAlarmsLocked(false);
1251 needRebatch = false;
1252 }
1253 }
1254
1255 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001256 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001257 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001258
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001259 rescheduleKernelAlarmsLocked();
1260 updateNextAlarmClockLocked();
1261 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001262 }
1263
Adam Lesinski182f73f2013-12-05 16:48:06 -08001264 private final IBinder mService = new IAlarmManager.Stub() {
1265 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001266 public void set(String callingPackage,
1267 int type, long triggerAtTime, long windowLength, long interval, int flags,
1268 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1269 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001270 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001271
1272 // make sure the caller is not lying about which package should be blamed for
1273 // wakelock time spent in alarm delivery
1274 mAppOps.checkPackage(callingUid, callingPackage);
1275
1276 // Repeating alarms must use PendingIntent, not direct listener
1277 if (interval != 0) {
1278 if (directReceiver != null) {
1279 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1280 }
1281 }
1282
Adam Lesinski182f73f2013-12-05 16:48:06 -08001283 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001284 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001285 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001286 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001287 }
1288
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001289 // No incoming callers can request either WAKE_FROM_IDLE or
1290 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1291 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1292 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1293
1294 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1295 // manager when to come out of idle mode, which is only for DeviceIdleController.
1296 if (callingUid != Process.SYSTEM_UID) {
1297 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1298 }
1299
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001300 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001301 if (windowLength == AlarmManager.WINDOW_EXACT) {
1302 flags |= AlarmManager.FLAG_STANDALONE;
1303 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001304
1305 // If this alarm is for an alarm clock, then it must be standalone and we will
1306 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001307 if (alarmClock != null) {
1308 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001309
1310 // If the caller is a core system component or on the user's whitelist, and not calling
1311 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1312 // This means we will allow these alarms to go off as normal even while idle, with no
1313 // timing restrictions.
1314 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
1315 || Arrays.binarySearch(mDeviceIdleUserWhitelist,
1316 UserHandle.getAppId(callingUid)) >= 0)) {
1317 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1318 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001319 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001320
Christopher Tate14a7bb02015-10-01 10:24:31 -07001321 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1322 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001323 }
Christopher Tate89779822012-08-31 14:40:03 -07001324
Adam Lesinski182f73f2013-12-05 16:48:06 -08001325 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001326 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001327 getContext().enforceCallingOrSelfPermission(
1328 "android.permission.SET_TIME",
1329 "setTime");
1330
Greg Hackmann0cab8962014-02-21 16:35:52 -08001331 if (mNativeData == 0) {
1332 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1333 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001334 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001335
1336 synchronized (mLock) {
1337 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001340
1341 @Override
1342 public void setTimeZone(String tz) {
1343 getContext().enforceCallingOrSelfPermission(
1344 "android.permission.SET_TIME_ZONE",
1345 "setTimeZone");
1346
1347 final long oldId = Binder.clearCallingIdentity();
1348 try {
1349 setTimeZoneImpl(tz);
1350 } finally {
1351 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001352 }
1353 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001354
Adam Lesinski182f73f2013-12-05 16:48:06 -08001355 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001356 public void remove(PendingIntent operation, IAlarmListener listener) {
1357 if (operation == null && listener == null) {
1358 Slog.w(TAG, "remove() with no intent or listener");
1359 return;
1360 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001361
Christopher Tate14a7bb02015-10-01 10:24:31 -07001362 synchronized (mLock) {
1363 removeLocked(operation, listener);
1364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001366
Adam Lesinski182f73f2013-12-05 16:48:06 -08001367 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001368 public long getNextWakeFromIdleTime() {
1369 return getNextWakeFromIdleTimeImpl();
1370 }
1371
1372 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001373 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001374 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1375 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1376 "getNextAlarmClock", null);
1377
1378 return getNextAlarmClockImpl(userId);
1379 }
1380
1381 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001382 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1383 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1384 != PackageManager.PERMISSION_GRANTED) {
1385 pw.println("Permission Denial: can't dump AlarmManager from from pid="
1386 + Binder.getCallingPid()
1387 + ", uid=" + Binder.getCallingUid());
1388 return;
Christopher Tate4cb338d2013-07-26 13:11:31 -07001389 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001390
Adam Lesinski182f73f2013-12-05 16:48:06 -08001391 dumpImpl(pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001392 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001393 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001394
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001395 public final class LocalService {
1396 public void setDeviceIdleUserWhitelist(int[] appids) {
1397 setDeviceIdleUserWhitelistImpl(appids);
1398 }
1399 }
1400
Adam Lesinski182f73f2013-12-05 16:48:06 -08001401 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402 synchronized (mLock) {
1403 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001404 mConstants.dump(pw);
1405 pw.println();
1406
Christopher Tatee0a22b32013-07-11 14:43:13 -07001407 final long nowRTC = System.currentTimeMillis();
1408 final long nowELAPSED = SystemClock.elapsedRealtime();
1409 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1410
Dianne Hackborna750a632015-06-16 17:18:23 -07001411 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001412 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001413 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001414 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001415 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001416 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001417 pw.print(" mLastTimeChangeRealtime=");
Dianne Hackbornc3527222015-05-13 14:03:20 -07001418 TimeUtils.formatDuration(mLastTimeChangeRealtime, pw);
1419 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001420 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001421 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001422 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1423 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001424 pw.print(" Max wakeup delay: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001425 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1426 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001427 pw.print(" Time since last dispatch: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001428 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1429 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001430 pw.print(" Next non-wakeup delivery time: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001431 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1432 pw.println();
1433 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001434
1435 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1436 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001437 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001438 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001439 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001440 pw.print(" Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001441 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001442 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
1443 pw.print(" set at "); TimeUtils.formatDuration(mLastWakeupSet, nowELAPSED, pw);
1444 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001445 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001446 pw.println(" mDeviceIdleUserWhitelist=" + Arrays.toString(mDeviceIdleUserWhitelist));
Christopher Tatee0a22b32013-07-11 14:43:13 -07001447
John Spurlock604a5ee2015-06-01 12:27:22 -04001448 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001449 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001450 final TreeSet<Integer> users = new TreeSet<>();
1451 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1452 users.add(mNextAlarmClockForUser.keyAt(i));
1453 }
1454 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1455 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1456 }
1457 for (int user : users) {
1458 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1459 final long time = next != null ? next.getTriggerTime() : 0;
1460 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001461 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001462 pw.print(" pendingSend:"); pw.print(pendingSend);
1463 pw.print(" time:"); pw.print(time);
1464 if (time > 0) {
1465 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1466 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1467 }
1468 pw.println();
1469 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001470 if (mAlarmBatches.size() > 0) {
1471 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001472 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001473 pw.println(mAlarmBatches.size());
1474 for (Batch b : mAlarmBatches) {
1475 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001476 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001477 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001479 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001480 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001481 pw.println(" Idle mode state:");
1482 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001483 if (mPendingIdleUntil != null) {
1484 pw.println(mPendingIdleUntil);
Dianne Hackbornf3831292015-10-15 14:51:06 -07001485 mPendingIdleUntil.dump(pw, " ", nowRTC, nowELAPSED, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001486 } else {
1487 pw.println("null");
1488 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001489 pw.println(" Pending alarms:");
1490 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001491 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001492 if (mNextWakeFromIdle != null) {
1493 pw.println();
1494 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
1495 mNextWakeFromIdle.dump(pw, " ", nowRTC, nowELAPSED, sdf);
1496 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001497
1498 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001499 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001500 if (mPendingNonWakeupAlarms.size() > 0) {
1501 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001502 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001503 } else {
1504 pw.println("(none)");
1505 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001506 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001507 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1508 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001509 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001510 pw.print(", max non-interactive time: ");
1511 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1512 pw.println();
1513
1514 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001515 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001516 pw.println();
1517
Christopher Tate7f2a0352015-12-08 10:24:33 -08001518 if (mInFlight.size() > 0) {
1519 pw.println("Outstanding deliveries:");
1520 for (int i = 0; i < mInFlight.size(); i++) {
1521 pw.print(" #"); pw.print(i); pw.print(": ");
1522 pw.println(mInFlight.get(i));
1523 }
1524 pw.println();
1525 }
1526
Dianne Hackborna750a632015-06-16 17:18:23 -07001527 pw.print(" mAllowWhileIdleMinTime=");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001528 TimeUtils.formatDuration(mAllowWhileIdleMinTime, pw);
1529 pw.println();
1530 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001531 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001532 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
1533 pw.print(" UID ");
1534 UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
1535 pw.print(": ");
1536 TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i),
1537 nowELAPSED, pw);
1538 pw.println();
1539 }
1540 }
1541 pw.println();
1542
Dianne Hackborn81038902012-11-26 17:04:09 -08001543 if (mLog.dump(pw, " Recent problems", " ")) {
1544 pw.println();
1545 }
1546
1547 final FilterStats[] topFilters = new FilterStats[10];
1548 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1549 @Override
1550 public int compare(FilterStats lhs, FilterStats rhs) {
1551 if (lhs.aggregateTime < rhs.aggregateTime) {
1552 return 1;
1553 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1554 return -1;
1555 }
1556 return 0;
1557 }
1558 };
1559 int len = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001560 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1561 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1562 for (int ip=0; ip<uidStats.size(); ip++) {
1563 BroadcastStats bs = uidStats.valueAt(ip);
1564 for (int is=0; is<bs.filterStats.size(); is++) {
1565 FilterStats fs = bs.filterStats.valueAt(is);
1566 int pos = len > 0
1567 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1568 if (pos < 0) {
1569 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001570 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001571 if (pos < topFilters.length) {
1572 int copylen = topFilters.length - pos - 1;
1573 if (copylen > 0) {
1574 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1575 }
1576 topFilters[pos] = fs;
1577 if (len < topFilters.length) {
1578 len++;
1579 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001580 }
1581 }
1582 }
1583 }
1584 if (len > 0) {
1585 pw.println(" Top Alarms:");
1586 for (int i=0; i<len; i++) {
1587 FilterStats fs = topFilters[i];
1588 pw.print(" ");
1589 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1590 TimeUtils.formatDuration(fs.aggregateTime, pw);
1591 pw.print(" running, "); pw.print(fs.numWakeup);
1592 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001593 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1594 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001595 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001596 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001597 pw.println();
1598 }
1599 }
1600
1601 pw.println(" ");
1602 pw.println(" Alarm Stats:");
1603 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001604 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1605 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1606 for (int ip=0; ip<uidStats.size(); ip++) {
1607 BroadcastStats bs = uidStats.valueAt(ip);
1608 pw.print(" ");
1609 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1610 UserHandle.formatUid(pw, bs.mUid);
1611 pw.print(":");
1612 pw.print(bs.mPackageName);
1613 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1614 pw.print(" running, "); pw.print(bs.numWakeup);
1615 pw.println(" wakeups:");
1616 tmpFilters.clear();
1617 for (int is=0; is<bs.filterStats.size(); is++) {
1618 tmpFilters.add(bs.filterStats.valueAt(is));
1619 }
1620 Collections.sort(tmpFilters, comparator);
1621 for (int i=0; i<tmpFilters.size(); i++) {
1622 FilterStats fs = tmpFilters.get(i);
1623 pw.print(" ");
1624 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1625 TimeUtils.formatDuration(fs.aggregateTime, pw);
1626 pw.print(" "); pw.print(fs.numWakeup);
1627 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001628 pw.print(" alarms, last ");
1629 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1630 pw.println(":");
1631 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001632 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001633 pw.println();
1634 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 }
1636 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001637
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001638 if (RECORD_DEVICE_IDLE_ALARMS) {
1639 pw.println();
1640 pw.println(" Allow while idle dispatches:");
1641 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
1642 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
1643 pw.print(" ");
1644 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
1645 pw.print(": ");
1646 UserHandle.formatUid(pw, ent.uid);
1647 pw.print(":");
1648 pw.println(ent.pkg);
1649 if (ent.op != null) {
1650 pw.print(" ");
1651 pw.print(ent.op);
1652 pw.print(" / ");
1653 pw.print(ent.tag);
1654 if (ent.argRealtime != 0) {
1655 pw.print(" (");
1656 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
1657 pw.print(")");
1658 }
1659 pw.println();
1660 }
1661 }
1662 }
1663
Christopher Tate18a75f12013-07-01 18:18:59 -07001664 if (WAKEUP_STATS) {
1665 pw.println();
1666 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001667 long last = -1;
1668 for (WakeupEvent event : mRecentWakeups) {
1669 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1670 pw.print('|');
1671 if (last < 0) {
1672 pw.print('0');
1673 } else {
1674 pw.print(event.when - last);
1675 }
1676 last = event.when;
1677 pw.print('|'); pw.print(event.uid);
1678 pw.print('|'); pw.print(event.action);
1679 pw.println();
1680 }
1681 pw.println();
1682 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 }
1684 }
1685
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001686 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001687 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
1688 PrintWriter pw = new PrintWriter(bs);
1689 final long nowRTC = System.currentTimeMillis();
1690 final long nowELAPSED = SystemClock.elapsedRealtime();
1691 final int NZ = mAlarmBatches.size();
1692 for (int iz = 0; iz < NZ; iz++) {
1693 Batch bz = mAlarmBatches.get(iz);
1694 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001695 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001696 pw.flush();
1697 Slog.v(TAG, bs.toString());
1698 bs.reset();
1699 }
1700 }
1701
1702 private boolean validateConsistencyLocked() {
1703 if (DEBUG_VALIDATE) {
1704 long lastTime = Long.MIN_VALUE;
1705 final int N = mAlarmBatches.size();
1706 for (int i = 0; i < N; i++) {
1707 Batch b = mAlarmBatches.get(i);
1708 if (b.start >= lastTime) {
1709 // duplicate start times are okay because of standalone batches
1710 lastTime = b.start;
1711 } else {
1712 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001713 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1714 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001715 return false;
1716 }
1717 }
1718 }
1719 return true;
1720 }
1721
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001722 private Batch findFirstWakeupBatchLocked() {
1723 final int N = mAlarmBatches.size();
1724 for (int i = 0; i < N; i++) {
1725 Batch b = mAlarmBatches.get(i);
1726 if (b.hasWakeups()) {
1727 return b;
1728 }
1729 }
1730 return null;
1731 }
1732
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001733 long getNextWakeFromIdleTimeImpl() {
1734 synchronized (mLock) {
1735 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
1736 }
1737 }
1738
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001739 void setDeviceIdleUserWhitelistImpl(int[] appids) {
1740 synchronized (mLock) {
1741 mDeviceIdleUserWhitelist = appids;
1742 }
1743 }
1744
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001745 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001746 synchronized (mLock) {
1747 return mNextAlarmClockForUser.get(userId);
1748 }
1749 }
1750
1751 /**
1752 * Recomputes the next alarm clock for all users.
1753 */
1754 private void updateNextAlarmClockLocked() {
1755 if (!mNextAlarmClockMayChange) {
1756 return;
1757 }
1758 mNextAlarmClockMayChange = false;
1759
Jose Lima235510e2014-08-13 12:50:01 -07001760 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001761 nextForUser.clear();
1762
1763 final int N = mAlarmBatches.size();
1764 for (int i = 0; i < N; i++) {
1765 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
1766 final int M = alarms.size();
1767
1768 for (int j = 0; j < M; j++) {
1769 Alarm a = alarms.get(j);
1770 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001771 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07001772 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001773
1774 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07001775 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001776 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02001777 " for user " + userId);
1778 }
1779
1780 // Alarms and batches are sorted by time, no need to compare times here.
1781 if (nextForUser.get(userId) == null) {
1782 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07001783 } else if (a.alarmClock.equals(current)
1784 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
1785 // same/earlier time and it's the one we cited before, so stick with it
1786 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001787 }
1788 }
1789 }
1790 }
1791
1792 // Update mNextAlarmForUser with new values.
1793 final int NN = nextForUser.size();
1794 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07001795 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001796 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001797 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001798 if (!newAlarm.equals(currentAlarm)) {
1799 updateNextAlarmInfoForUserLocked(userId, newAlarm);
1800 }
1801 }
1802
1803 // Remove users without any alarm clocks scheduled.
1804 final int NNN = mNextAlarmClockForUser.size();
1805 for (int i = NNN - 1; i >= 0; i--) {
1806 int userId = mNextAlarmClockForUser.keyAt(i);
1807 if (nextForUser.get(userId) == null) {
1808 updateNextAlarmInfoForUserLocked(userId, null);
1809 }
1810 }
1811 }
1812
Jose Lima235510e2014-08-13 12:50:01 -07001813 private void updateNextAlarmInfoForUserLocked(int userId,
1814 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001815 if (alarmClock != null) {
1816 if (DEBUG_ALARM_CLOCK) {
1817 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001818 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02001819 }
1820 mNextAlarmClockForUser.put(userId, alarmClock);
1821 } else {
1822 if (DEBUG_ALARM_CLOCK) {
1823 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
1824 }
1825 mNextAlarmClockForUser.remove(userId);
1826 }
1827
1828 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
1829 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1830 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1831 }
1832
1833 /**
1834 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
1835 * for which alarm clocks have changed since the last call to this.
1836 *
1837 * Do not call with a lock held. Only call from mHandler's thread.
1838 *
1839 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
1840 */
1841 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07001842 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001843 pendingUsers.clear();
1844
1845 synchronized (mLock) {
1846 final int N = mPendingSendNextAlarmClockChangedForUser.size();
1847 for (int i = 0; i < N; i++) {
1848 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
1849 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
1850 }
1851 mPendingSendNextAlarmClockChangedForUser.clear();
1852 }
1853
1854 final int N = pendingUsers.size();
1855 for (int i = 0; i < N; i++) {
1856 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001857 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001858 Settings.System.putStringForUser(getContext().getContentResolver(),
1859 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01001860 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02001861 userId);
1862
1863 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
1864 new UserHandle(userId));
1865 }
1866 }
1867
1868 /**
1869 * Formats an alarm like platform/packages/apps/DeskClock used to.
1870 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01001871 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
1872 int userId) {
1873 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02001874 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
1875 return (info == null) ? "" :
1876 DateFormat.format(pattern, info.getTriggerTime()).toString();
1877 }
1878
Adam Lesinski182f73f2013-12-05 16:48:06 -08001879 void rescheduleKernelAlarmsLocked() {
1880 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
1881 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001882 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001883 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001884 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001885 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07001886 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001887 mNextWakeup = firstWakeup.start;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001888 mLastWakeupSet = SystemClock.elapsedRealtime();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001889 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001890 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001891 if (firstBatch != firstWakeup) {
1892 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001893 }
1894 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001895 if (mPendingNonWakeupAlarms.size() > 0) {
1896 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
1897 nextNonWakeup = mNextNonWakeupDeliveryTime;
1898 }
1899 }
Prashant Malani753e9e02015-06-10 17:43:49 -07001900 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001901 mNextNonWakeup = nextNonWakeup;
1902 setLocked(ELAPSED_REALTIME, nextNonWakeup);
1903 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001904 }
1905
Christopher Tate14a7bb02015-10-01 10:24:31 -07001906 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001907 boolean didRemove = false;
1908 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1909 Batch b = mAlarmBatches.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -07001910 didRemove |= b.remove(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001911 if (b.size() == 0) {
1912 mAlarmBatches.remove(i);
1913 }
1914 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001915 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001916 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001917 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1918 mPendingWhileIdleAlarms.remove(i);
1919 }
1920 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001921
1922 if (didRemove) {
1923 if (DEBUG_BATCH) {
1924 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
1925 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001926 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001927 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001928 mPendingIdleUntil = null;
1929 restorePending = true;
1930 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001931 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001932 mNextWakeFromIdle = null;
1933 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001934 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001935 if (restorePending) {
1936 restorePendingWhileIdleAlarmsLocked();
1937 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001938 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001939 }
1940 }
1941
1942 void removeLocked(String packageName) {
1943 boolean didRemove = false;
1944 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1945 Batch b = mAlarmBatches.get(i);
1946 didRemove |= b.remove(packageName);
1947 if (b.size() == 0) {
1948 mAlarmBatches.remove(i);
1949 }
1950 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001951 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001952 final Alarm a = mPendingWhileIdleAlarms.get(i);
1953 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001954 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1955 mPendingWhileIdleAlarms.remove(i);
1956 }
1957 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001958
1959 if (didRemove) {
1960 if (DEBUG_BATCH) {
1961 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1962 }
1963 rebatchAllAlarmsLocked(true);
1964 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001965 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001966 }
1967 }
1968
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001969 void removeForStoppedLocked(int uid) {
1970 boolean didRemove = false;
1971 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1972 Batch b = mAlarmBatches.get(i);
1973 didRemove |= b.removeForStopped(uid);
1974 if (b.size() == 0) {
1975 mAlarmBatches.remove(i);
1976 }
1977 }
1978 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
1979 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08001980 if (a.uid == uid) {
1981 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1982 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001983 }
1984 }
1985
1986 if (didRemove) {
1987 if (DEBUG_BATCH) {
1988 Slog.v(TAG, "remove(package) changed bounds; rebatching");
1989 }
1990 rebatchAllAlarmsLocked(true);
1991 rescheduleKernelAlarmsLocked();
1992 updateNextAlarmClockLocked();
1993 }
1994 }
1995
Adam Lesinski182f73f2013-12-05 16:48:06 -08001996 void removeUserLocked(int userHandle) {
1997 boolean didRemove = false;
1998 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1999 Batch b = mAlarmBatches.get(i);
2000 didRemove |= b.remove(userHandle);
2001 if (b.size() == 0) {
2002 mAlarmBatches.remove(i);
2003 }
2004 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002005 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002006 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002007 == userHandle) {
2008 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2009 mPendingWhileIdleAlarms.remove(i);
2010 }
2011 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002012 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
2013 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
2014 mLastAllowWhileIdleDispatch.removeAt(i);
2015 }
2016 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002017
2018 if (didRemove) {
2019 if (DEBUG_BATCH) {
2020 Slog.v(TAG, "remove(user) changed bounds; rebatching");
2021 }
2022 rebatchAllAlarmsLocked(true);
2023 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002024 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002025 }
2026 }
2027
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002028 void interactiveStateChangedLocked(boolean interactive) {
2029 if (mInteractive != interactive) {
2030 mInteractive = interactive;
2031 final long nowELAPSED = SystemClock.elapsedRealtime();
2032 if (interactive) {
2033 if (mPendingNonWakeupAlarms.size() > 0) {
2034 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2035 mTotalDelayTime += thisDelayTime;
2036 if (mMaxDelayTime < thisDelayTime) {
2037 mMaxDelayTime = thisDelayTime;
2038 }
2039 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2040 mPendingNonWakeupAlarms.clear();
2041 }
2042 if (mNonInteractiveStartTime > 0) {
2043 long dur = nowELAPSED - mNonInteractiveStartTime;
2044 if (dur > mNonInteractiveTime) {
2045 mNonInteractiveTime = dur;
2046 }
2047 }
2048 } else {
2049 mNonInteractiveStartTime = nowELAPSED;
2050 }
2051 }
2052 }
2053
Adam Lesinski182f73f2013-12-05 16:48:06 -08002054 boolean lookForPackageLocked(String packageName) {
2055 for (int i = 0; i < mAlarmBatches.size(); i++) {
2056 Batch b = mAlarmBatches.get(i);
2057 if (b.hasPackage(packageName)) {
2058 return true;
2059 }
2060 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002061 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002062 final Alarm a = mPendingWhileIdleAlarms.get(i);
2063 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002064 return true;
2065 }
2066 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002067 return false;
2068 }
2069
2070 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002071 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002072 // The kernel never triggers alarms with negative wakeup times
2073 // so we ensure they are positive.
2074 long alarmSeconds, alarmNanoseconds;
2075 if (when < 0) {
2076 alarmSeconds = 0;
2077 alarmNanoseconds = 0;
2078 } else {
2079 alarmSeconds = when / 1000;
2080 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2081 }
2082
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002083 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002084 } else {
2085 Message msg = Message.obtain();
2086 msg.what = ALARM_EVENT;
2087
2088 mHandler.removeMessages(ALARM_EVENT);
2089 mHandler.sendMessageAtTime(msg, when);
2090 }
2091 }
2092
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002093 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002094 String prefix, String label, long nowRTC, long nowELAPSED, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002095 for (int i=list.size()-1; i>=0; i--) {
2096 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002097 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2098 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002099 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002100 }
2101 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002102
2103 private static final String labelForType(int type) {
2104 switch (type) {
2105 case RTC: return "RTC";
2106 case RTC_WAKEUP : return "RTC_WAKEUP";
2107 case ELAPSED_REALTIME : return "ELAPSED";
2108 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
2109 default:
2110 break;
2111 }
2112 return "--unknown--";
2113 }
2114
2115 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002116 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002117 for (int i=list.size()-1; i>=0; i--) {
2118 Alarm a = list.get(i);
2119 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002120 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2121 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002122 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002123 }
2124 }
2125
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002126 private native long init();
2127 private native void close(long nativeData);
2128 private native void set(long nativeData, int type, long seconds, long nanoseconds);
2129 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08002130 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002131 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002132
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002133 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002134 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002135 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002136 // batches are temporally sorted, so we need only pull from the
2137 // start of the list until we either empty it or hit a batch
2138 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07002139 while (mAlarmBatches.size() > 0) {
2140 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002141 if (batch.start > nowELAPSED) {
2142 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002143 break;
2144 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002145
Christopher Tatee0a22b32013-07-11 14:43:13 -07002146 // We will (re)schedule some alarms now; don't let that interfere
2147 // with delivery of this current batch
2148 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002149
Christopher Tatee0a22b32013-07-11 14:43:13 -07002150 final int N = batch.size();
2151 for (int i = 0; i < N; i++) {
2152 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002153
2154 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
2155 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
2156 // schedule such alarms.
2157 long lastTime = mLastAllowWhileIdleDispatch.get(alarm.uid, 0);
2158 long minTime = lastTime + mAllowWhileIdleMinTime;
2159 if (nowELAPSED < minTime) {
2160 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
2161 // alarm went off for this app. Reschedule the alarm to be in the
2162 // correct time period.
2163 alarm.whenElapsed = minTime;
2164 if (alarm.maxWhenElapsed < minTime) {
2165 alarm.maxWhenElapsed = minTime;
2166 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002167 if (RECORD_DEVICE_IDLE_ALARMS) {
2168 IdleDispatchEntry ent = new IdleDispatchEntry();
2169 ent.uid = alarm.uid;
2170 ent.pkg = alarm.operation.getCreatorPackage();
2171 ent.tag = alarm.operation.getTag("");
2172 ent.op = "RESCHEDULE";
2173 ent.elapsedRealtime = nowELAPSED;
2174 ent.argRealtime = lastTime;
2175 mAllowWhileIdleDispatches.add(ent);
2176 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002177 setImplLocked(alarm, true, false);
2178 continue;
2179 }
2180 }
2181
Christopher Tatee0a22b32013-07-11 14:43:13 -07002182 alarm.count = 1;
2183 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002184 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
2185 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002186 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002187 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002188 if (mPendingIdleUntil == alarm) {
2189 mPendingIdleUntil = null;
2190 rebatchAllAlarmsLocked(false);
2191 restorePendingWhileIdleAlarmsLocked();
2192 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002193 if (mNextWakeFromIdle == alarm) {
2194 mNextWakeFromIdle = null;
2195 rebatchAllAlarmsLocked(false);
2196 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002197
2198 // Recurring alarms may have passed several alarm intervals while the
2199 // phone was asleep or off, so pass a trigger count when sending them.
2200 if (alarm.repeatInterval > 0) {
2201 // this adjustment will be zero if we're late by
2202 // less than one full repeat interval
2203 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
2204
2205 // Also schedule its next recurrence
2206 final long delta = alarm.count * alarm.repeatInterval;
2207 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07002208 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07002209 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07002210 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
2211 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08002212 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002213
Christopher Tate864d42e2014-12-02 11:48:53 -08002214 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002215 hasWakeup = true;
2216 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002217
2218 // We removed an alarm clock. Let the caller recompute the next alarm clock.
2219 if (alarm.alarmClock != null) {
2220 mNextAlarmClockMayChange = true;
2221 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07002222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002223 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002224
Christopher Tate1590f1e2014-10-02 17:27:57 -07002225 // This is a new alarm delivery set; bump the sequence number to indicate that
2226 // all apps' alarm delivery classes should be recalculated.
2227 mCurrentSeq++;
2228 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002229 Collections.sort(triggerList, mAlarmDispatchComparator);
2230
2231 if (localLOGV) {
2232 for (int i=0; i<triggerList.size(); i++) {
2233 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
2234 }
2235 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002236
2237 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002238 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002239
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002240 /**
2241 * This Comparator sorts Alarms into increasing time order.
2242 */
2243 public static class IncreasingTimeOrder implements Comparator<Alarm> {
2244 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09002245 long when1 = a1.whenElapsed;
2246 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002247 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002248 return 1;
2249 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002250 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002251 return -1;
2252 }
2253 return 0;
2254 }
2255 }
2256
2257 private static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002258 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002259 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002260 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002261 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002262 public final IAlarmListener listener;
2263 public final String listenerTag;
2264 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002265 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002266 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002267 public final AlarmManager.AlarmClockInfo alarmClock;
2268 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002269 public final int creatorUid;
2270 public final String packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002271 public int count;
2272 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07002273 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002274 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002275 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002276 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07002277 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002278
Christopher Tate3e04b472013-10-21 17:51:31 -07002279 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002280 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
2281 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
2282 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002283 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002284 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002285 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
2286 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002287 when = _when;
2288 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07002289 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002290 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002291 repeatInterval = _interval;
2292 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002293 listener = _rec;
2294 listenerTag = _listenerTag;
2295 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07002296 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002297 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002298 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002299 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002300 packageName = _pkgName;
2301
2302 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002303 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002304
Christopher Tate14a7bb02015-10-01 10:24:31 -07002305 public static String makeTag(PendingIntent pi, String tag, int type) {
2306 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
2307 ? "*walarm*:" : "*alarm*:";
2308 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
2309 }
2310
2311 public WakeupEvent makeWakeupEvent(long nowRTC) {
2312 return new WakeupEvent(nowRTC, creatorUid,
2313 (operation != null)
2314 ? operation.getIntent().getAction()
2315 : ("<listener>:" + listenerTag));
2316 }
2317
2318 // Returns true if either matches
2319 public boolean matches(PendingIntent pi, IAlarmListener rec) {
2320 return (operation != null)
2321 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09002322 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07002323 }
2324
2325 public boolean matches(String packageName) {
2326 return (operation != null)
2327 ? packageName.equals(operation.getTargetPackage())
2328 : packageName.equals(this.packageName);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002329 }
2330
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002331 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002332 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002333 StringBuilder sb = new StringBuilder(128);
2334 sb.append("Alarm{");
2335 sb.append(Integer.toHexString(System.identityHashCode(this)));
2336 sb.append(" type ");
2337 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002338 sb.append(" when ");
2339 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002340 sb.append(" ");
Christopher Tate14a7bb02015-10-01 10:24:31 -07002341 if (operation != null) {
2342 sb.append(operation.getTargetPackage());
2343 } else {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002344 sb.append(packageName);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002345 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002346 sb.append('}');
2347 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002348 }
2349
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002350 public void dump(PrintWriter pw, String prefix, long nowRTC, long nowELAPSED,
2351 SimpleDateFormat sdf) {
2352 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002353 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002354 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002355 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
2356 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002357 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002358 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002359 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002360 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002361 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002362 }
2363 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002364 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002365 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002366 pw.print(" count="); pw.print(count);
2367 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002368 if (alarmClock != null) {
2369 pw.print(prefix); pw.println("Alarm clock:");
2370 pw.print(prefix); pw.print(" triggerTime=");
2371 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
2372 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
2373 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002374 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002375 if (listener != null) {
2376 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
2377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002378 }
2379 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002380
Christopher Tatee0a22b32013-07-11 14:43:13 -07002381 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
2382 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002383 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
2384 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002385 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07002386 break;
2387 }
2388
Christopher Tatee0a22b32013-07-11 14:43:13 -07002389 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002390 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
2391 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002392 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07002393 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002394 }
2395 }
2396
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002397 long currentNonWakeupFuzzLocked(long nowELAPSED) {
2398 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
2399 if (timeSinceOn < 5*60*1000) {
2400 // If the screen has been off for 5 minutes, only delay by at most two minutes.
2401 return 2*60*1000;
2402 } else if (timeSinceOn < 30*60*1000) {
2403 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
2404 return 15*60*1000;
2405 } else {
2406 // Otherwise, we will delay by at most an hour.
2407 return 60*60*1000;
2408 }
2409 }
2410
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002411 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002412 if (duration < 15*60*1000) {
2413 // If the duration until the time is less than 15 minutes, the maximum fuzz
2414 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002415 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002416 } else if (duration < 90*60*1000) {
2417 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
2418 return 15*60*1000;
2419 } else {
2420 // Otherwise, we will fuzz by at most half an hour.
2421 return 30*60*1000;
2422 }
2423 }
2424
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002425 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
2426 if (mInteractive) {
2427 return false;
2428 }
2429 if (mLastAlarmDeliveryTime <= 0) {
2430 return false;
2431 }
minho.choo649acab2014-12-12 16:13:55 +09002432 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002433 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
2434 // and the next delivery time is in the past, then just deliver them all. This
2435 // avoids bugs where we get stuck in a loop trying to poll for alarms.
2436 return false;
2437 }
2438 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
2439 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
2440 }
2441
2442 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
2443 mLastAlarmDeliveryTime = nowELAPSED;
2444 for (int i=0; i<triggerList.size(); i++) {
2445 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07002446 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002447 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07002448 if (localLOGV) {
2449 Slog.v(TAG, "sending alarm " + alarm);
2450 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07002451 if (RECORD_ALARMS_IN_HISTORY) {
2452 if (alarm.workSource != null && alarm.workSource.size() > 0) {
2453 for (int wi=0; wi<alarm.workSource.size(); wi++) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002454 ActivityManager.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002455 alarm.operation, alarm.workSource.get(wi), alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002456 }
2457 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002458 ActivityManager.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002459 alarm.operation, alarm.uid, alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002460 }
2461 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002462 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002463 } catch (RuntimeException e) {
2464 Slog.w(TAG, "Failure sending alarm.", e);
2465 }
2466 }
2467 }
2468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002469 private class AlarmThread extends Thread
2470 {
2471 public AlarmThread()
2472 {
2473 super("AlarmManager");
2474 }
2475
2476 public void run()
2477 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002478 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2479
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002480 while (true)
2481 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002482 int result = waitForAlarm(mNativeData);
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002483 mLastWakeup = SystemClock.elapsedRealtime();
Dianne Hackborn390517b2013-05-30 15:03:32 -07002484
2485 triggerList.clear();
2486
Dianne Hackbornc3527222015-05-13 14:03:20 -07002487 final long nowRTC = System.currentTimeMillis();
2488 final long nowELAPSED = SystemClock.elapsedRealtime();
2489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002490 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002491 // The kernel can give us spurious time change notifications due to
2492 // small adjustments it makes internally; we want to filter those out.
2493 final long lastTimeChangeClockTime;
2494 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07002495 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002496 lastTimeChangeClockTime = mLastTimeChangeClockTime;
2497 expectedClockTime = lastTimeChangeClockTime
2498 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07002499 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08002500 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
2501 || nowRTC > (expectedClockTime+1000)) {
2502 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07002503 // let's do it!
2504 if (DEBUG_BATCH) {
2505 Slog.v(TAG, "Time changed notification from kernel; rebatching");
2506 }
2507 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07002508 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07002509 rebatchAllAlarms();
2510 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07002511 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07002512 synchronized (mLock) {
2513 mNumTimeChanged++;
2514 mLastTimeChangeClockTime = nowRTC;
2515 mLastTimeChangeRealtime = nowELAPSED;
2516 }
2517 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
2518 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08002519 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
2520 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Dianne Hackbornc3527222015-05-13 14:03:20 -07002521 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
2522
2523 // The world has changed on us, so we need to re-evaluate alarms
2524 // regardless of whether the kernel has told us one went off.
2525 result |= IS_WAKEUP_MASK;
2526 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002528
Dianne Hackbornc3527222015-05-13 14:03:20 -07002529 if (result != TIME_CHANGED_MASK) {
2530 // If this was anything besides just a time change, then figure what if
2531 // anything to do about alarms.
2532 synchronized (mLock) {
2533 if (localLOGV) Slog.v(
2534 TAG, "Checking for alarms... rtc=" + nowRTC
2535 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07002536
Dianne Hackbornc3527222015-05-13 14:03:20 -07002537 if (WAKEUP_STATS) {
2538 if ((result & IS_WAKEUP_MASK) != 0) {
2539 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
2540 int n = 0;
2541 for (WakeupEvent event : mRecentWakeups) {
2542 if (event.when > newEarliest) break;
2543 n++; // number of now-stale entries at the list head
2544 }
2545 for (int i = 0; i < n; i++) {
2546 mRecentWakeups.remove();
2547 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002548
Dianne Hackbornc3527222015-05-13 14:03:20 -07002549 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002550 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002551 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002552
2553 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2554 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
2555 // if there are no wakeup alarms and the screen is off, we can
2556 // delay what we have so far until the future.
2557 if (mPendingNonWakeupAlarms.size() == 0) {
2558 mStartCurrentDelayTime = nowELAPSED;
2559 mNextNonWakeupDeliveryTime = nowELAPSED
2560 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
2561 }
2562 mPendingNonWakeupAlarms.addAll(triggerList);
2563 mNumDelayedAlarms += triggerList.size();
2564 rescheduleKernelAlarmsLocked();
2565 updateNextAlarmClockLocked();
2566 } else {
2567 // now deliver the alarm intents; if there are pending non-wakeup
2568 // alarms, we need to merge them in to the list. note we don't
2569 // just deliver them first because we generally want non-wakeup
2570 // alarms delivered after wakeup alarms.
2571 rescheduleKernelAlarmsLocked();
2572 updateNextAlarmClockLocked();
2573 if (mPendingNonWakeupAlarms.size() > 0) {
2574 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
2575 triggerList.addAll(mPendingNonWakeupAlarms);
2576 Collections.sort(triggerList, mAlarmDispatchComparator);
2577 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2578 mTotalDelayTime += thisDelayTime;
2579 if (mMaxDelayTime < thisDelayTime) {
2580 mMaxDelayTime = thisDelayTime;
2581 }
2582 mPendingNonWakeupAlarms.clear();
2583 }
2584 deliverAlarmsLocked(triggerList, nowELAPSED);
2585 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002586 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002587
2588 } else {
2589 // Just in case -- even though no wakeup flag was set, make sure
2590 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07002591 synchronized (mLock) {
2592 rescheduleKernelAlarmsLocked();
2593 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002594 }
2595 }
2596 }
2597 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002598
David Christieebe51fc2013-07-26 13:23:29 -07002599 /**
2600 * Attribute blame for a WakeLock.
2601 * @param pi PendingIntent to attribute blame to if ws is null.
2602 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002603 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07002604 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002605 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002606 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07002607 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002608 final boolean unimportant = pi == mTimeTickSender;
2609 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002610 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002611 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002612 } else {
2613 mWakeLock.setHistoryTag(null);
2614 }
2615 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07002616 if (ws != null) {
2617 mWakeLock.setWorkSource(ws);
2618 return;
2619 }
2620
Christopher Tate14a7bb02015-10-01 10:24:31 -07002621 final int uid = (knownUid >= 0)
2622 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002623 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07002624 if (uid >= 0) {
2625 mWakeLock.setWorkSource(new WorkSource(uid));
2626 return;
2627 }
2628 } catch (Exception e) {
2629 }
2630
2631 // Something went wrong; fall back to attributing the lock to the OS
2632 mWakeLock.setWorkSource(null);
2633 }
2634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002635 private class AlarmHandler extends Handler {
2636 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002637 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
2638 public static final int LISTENER_TIMEOUT = 3;
2639 public static final int REPORT_ALARMS_ACTIVE = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002640
2641 public AlarmHandler() {
2642 }
2643
2644 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002645 switch (msg.what) {
2646 case ALARM_EVENT: {
2647 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2648 synchronized (mLock) {
2649 final long nowRTC = System.currentTimeMillis();
2650 final long nowELAPSED = SystemClock.elapsedRealtime();
2651 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2652 updateNextAlarmClockLocked();
2653 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002654
Christopher Tate14a7bb02015-10-01 10:24:31 -07002655 // now trigger the alarms without the lock held
2656 for (int i=0; i<triggerList.size(); i++) {
2657 Alarm alarm = triggerList.get(i);
2658 try {
2659 alarm.operation.send();
2660 } catch (PendingIntent.CanceledException e) {
2661 if (alarm.repeatInterval > 0) {
2662 // This IntentSender is no longer valid, but this
2663 // is a repeating alarm, so toss the hoser.
2664 removeImpl(alarm.operation);
2665 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002666 }
2667 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002668 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002669 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002670
2671 case SEND_NEXT_ALARM_CLOCK_CHANGED:
2672 sendNextAlarmClockChanged();
2673 break;
2674
2675 case LISTENER_TIMEOUT:
2676 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
2677 break;
2678
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002679 case REPORT_ALARMS_ACTIVE:
2680 if (mLocalDeviceIdleController != null) {
2681 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
2682 }
2683 break;
2684
Christopher Tate14a7bb02015-10-01 10:24:31 -07002685 default:
2686 // nope, just ignore it
2687 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 }
2689 }
2690 }
2691
2692 class ClockReceiver extends BroadcastReceiver {
2693 public ClockReceiver() {
2694 IntentFilter filter = new IntentFilter();
2695 filter.addAction(Intent.ACTION_TIME_TICK);
2696 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002697 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002698 }
2699
2700 @Override
2701 public void onReceive(Context context, Intent intent) {
2702 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07002703 if (DEBUG_BATCH) {
2704 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
2705 }
2706 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002707 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
2708 // Since the kernel does not keep track of DST, we need to
2709 // reset the TZ information at the beginning of each day
2710 // based off of the current Zone gmt offset + userspace tracked
2711 // daylight savings information.
2712 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02002713 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002714 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07002715 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002716 }
2717 }
2718
2719 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07002720 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09002721 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07002722
2723 // Schedule this event for the amount of time that it would take to get to
2724 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09002725 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07002726
David Christieebe51fc2013-07-26 13:23:29 -07002727 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002728 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002729 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
2730 null, Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002731 }
Christopher Tate385e4982013-07-23 18:22:29 -07002732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002733 public void scheduleDateChangedEvent() {
2734 Calendar calendar = Calendar.getInstance();
2735 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07002736 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002737 calendar.set(Calendar.MINUTE, 0);
2738 calendar.set(Calendar.SECOND, 0);
2739 calendar.set(Calendar.MILLISECOND, 0);
2740 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07002741
2742 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002743 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
2744 AlarmManager.FLAG_STANDALONE, workSource, null,
2745 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002746 }
2747 }
2748
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002749 class InteractiveStateReceiver extends BroadcastReceiver {
2750 public InteractiveStateReceiver() {
2751 IntentFilter filter = new IntentFilter();
2752 filter.addAction(Intent.ACTION_SCREEN_OFF);
2753 filter.addAction(Intent.ACTION_SCREEN_ON);
2754 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
2755 getContext().registerReceiver(this, filter);
2756 }
2757
2758 @Override
2759 public void onReceive(Context context, Intent intent) {
2760 synchronized (mLock) {
2761 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
2762 }
2763 }
2764 }
2765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002766 class UninstallReceiver extends BroadcastReceiver {
2767 public UninstallReceiver() {
2768 IntentFilter filter = new IntentFilter();
2769 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2770 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002771 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002772 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08002773 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002774 // Register for events related to sdcard installation.
2775 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08002776 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002777 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002778 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002779 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002780 }
2781
2782 @Override
2783 public void onReceive(Context context, Intent intent) {
2784 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002785 String action = intent.getAction();
2786 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002787 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
2788 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
2789 for (String packageName : pkgList) {
2790 if (lookForPackageLocked(packageName)) {
2791 setResultCode(Activity.RESULT_OK);
2792 return;
2793 }
2794 }
2795 return;
2796 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002797 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002798 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
2799 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
2800 if (userHandle >= 0) {
2801 removeUserLocked(userHandle);
2802 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002803 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
2804 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
2805 if (uid >= 0) {
2806 mLastAllowWhileIdleDispatch.delete(uid);
2807 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002808 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08002809 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
2810 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
2811 // This package is being updated; don't kill its alarms.
2812 return;
2813 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002814 Uri data = intent.getData();
2815 if (data != null) {
2816 String pkg = data.getSchemeSpecificPart();
2817 if (pkg != null) {
2818 pkgList = new String[]{pkg};
2819 }
2820 }
2821 }
2822 if (pkgList != null && (pkgList.length > 0)) {
2823 for (String pkg : pkgList) {
2824 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07002825 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002826 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
2827 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
2828 if (uidStats.remove(pkg) != null) {
2829 if (uidStats.size() <= 0) {
2830 mBroadcastStats.removeAt(i);
2831 }
2832 }
2833 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002834 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 }
2836 }
2837 }
2838 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002839
2840 final class UidObserver extends IUidObserver.Stub {
2841 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
2842 }
2843
Dianne Hackborne07641d2016-11-09 15:07:23 -08002844 @Override public void onUidGone(int uid, boolean disabled) throws RemoteException {
2845 if (disabled) {
2846 synchronized (mLock) {
2847 removeForStoppedLocked(uid);
2848 }
2849 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002850 }
2851
2852 @Override public void onUidActive(int uid) throws RemoteException {
2853 }
2854
Dianne Hackborne07641d2016-11-09 15:07:23 -08002855 @Override public void onUidIdle(int uid, boolean disabled) throws RemoteException {
2856 if (disabled) {
2857 synchronized (mLock) {
2858 removeForStoppedLocked(uid);
2859 }
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08002860 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002861 }
2862 };
2863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002864 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002865 String pkg = pi.getCreatorPackage();
2866 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002867 return getStatsLocked(uid, pkg);
2868 }
2869
2870 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002871 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
2872 if (uidStats == null) {
2873 uidStats = new ArrayMap<String, BroadcastStats>();
2874 mBroadcastStats.put(uid, uidStats);
2875 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002876 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002877 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002878 bs = new BroadcastStats(uid, pkgName);
2879 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002880 }
2881 return bs;
2882 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002883
Christopher Tate14a7bb02015-10-01 10:24:31 -07002884 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
2885 private InFlight removeLocked(PendingIntent pi, Intent intent) {
2886 for (int i = 0; i < mInFlight.size(); i++) {
2887 if (mInFlight.get(i).mPendingIntent == pi) {
2888 return mInFlight.remove(i);
2889 }
2890 }
2891 mLog.w("No in-flight alarm for " + pi + " " + intent);
2892 return null;
2893 }
2894
2895 private InFlight removeLocked(IBinder listener) {
2896 for (int i = 0; i < mInFlight.size(); i++) {
2897 if (mInFlight.get(i).mListener == listener) {
2898 return mInFlight.remove(i);
2899 }
2900 }
2901 mLog.w("No in-flight alarm for listener " + listener);
2902 return null;
2903 }
2904
2905 private void updateStatsLocked(InFlight inflight) {
2906 final long nowELAPSED = SystemClock.elapsedRealtime();
2907 BroadcastStats bs = inflight.mBroadcastStats;
2908 bs.nesting--;
2909 if (bs.nesting <= 0) {
2910 bs.nesting = 0;
2911 bs.aggregateTime += nowELAPSED - bs.startTime;
2912 }
2913 FilterStats fs = inflight.mFilterStats;
2914 fs.nesting--;
2915 if (fs.nesting <= 0) {
2916 fs.nesting = 0;
2917 fs.aggregateTime += nowELAPSED - fs.startTime;
2918 }
2919 if (RECORD_ALARMS_IN_HISTORY) {
2920 if (inflight.mWorkSource != null && inflight.mWorkSource.size() > 0) {
2921 for (int wi=0; wi<inflight.mWorkSource.size(); wi++) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002922 ActivityManager.noteAlarmFinish(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002923 inflight.mPendingIntent, inflight.mWorkSource.get(wi), inflight.mTag);
2924 }
2925 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002926 ActivityManager.noteAlarmFinish(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002927 inflight.mPendingIntent, inflight.mUid, inflight.mTag);
2928 }
2929 }
2930 }
2931
2932 private void updateTrackingLocked(InFlight inflight) {
2933 if (inflight != null) {
2934 updateStatsLocked(inflight);
2935 }
2936 mBroadcastRefCount--;
2937 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002938 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002939 mWakeLock.release();
2940 if (mInFlight.size() > 0) {
2941 mLog.w("Finished all dispatches with " + mInFlight.size()
2942 + " remaining inflights");
2943 for (int i=0; i<mInFlight.size(); i++) {
2944 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
2945 }
2946 mInFlight.clear();
2947 }
2948 } else {
2949 // the next of our alarms is now in flight. reattribute the wakelock.
2950 if (mInFlight.size() > 0) {
2951 InFlight inFlight = mInFlight.get(0);
2952 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
2953 inFlight.mAlarmType, inFlight.mTag, -1, false);
2954 } else {
2955 // should never happen
2956 mLog.w("Alarm wakelock still held but sent queue empty");
2957 mWakeLock.setWorkSource(null);
2958 }
2959 }
2960 }
2961
2962 /**
2963 * Callback that arrives when a direct-call alarm reports that delivery has finished
2964 */
2965 @Override
2966 public void alarmComplete(IBinder who) {
2967 if (who == null) {
2968 Slog.w(TAG, "Invalid alarmComplete: uid=" + Binder.getCallingUid()
2969 + " pid=" + Binder.getCallingPid());
2970 return;
2971 }
2972
2973 final long ident = Binder.clearCallingIdentity();
2974 try {
2975 synchronized (mLock) {
2976 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
2977 InFlight inflight = removeLocked(who);
2978 if (inflight != null) {
2979 if (DEBUG_LISTENER_CALLBACK) {
2980 Slog.i(TAG, "alarmComplete() from " + who);
2981 }
2982 updateTrackingLocked(inflight);
2983 } else {
2984 // Delivery timed out, and the timeout handling already took care of
2985 // updating our tracking here, so we needn't do anything further.
2986 if (DEBUG_LISTENER_CALLBACK) {
2987 Slog.i(TAG, "Late alarmComplete() from " + who);
2988 }
2989 }
2990 }
2991 } finally {
2992 Binder.restoreCallingIdentity(ident);
2993 }
2994 }
2995
2996 /**
2997 * Callback that arrives when a PendingIntent alarm has finished delivery
2998 */
2999 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003000 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
3001 String resultData, Bundle resultExtras) {
3002 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003003 updateTrackingLocked(removeLocked(pi, intent));
3004 }
3005 }
3006
3007 /**
3008 * Timeout of a direct-call alarm delivery
3009 */
3010 public void alarmTimedOut(IBinder who) {
3011 synchronized (mLock) {
3012 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08003013 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003014 // TODO: implement ANR policy for the target
3015 if (DEBUG_LISTENER_CALLBACK) {
3016 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003017 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003018 updateTrackingLocked(inflight);
Dianne Hackborn81038902012-11-26 17:04:09 -08003019 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003020 if (DEBUG_LISTENER_CALLBACK) {
3021 Slog.i(TAG, "Spurious timeout of listener " + who);
3022 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003023 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003024 }
3025 }
3026
3027 /**
3028 * Deliver an alarm and set up the post-delivery handling appropriately
3029 */
3030 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
3031 if (alarm.operation != null) {
3032 // PendingIntent alarm
3033 try {
3034 alarm.operation.send(getContext(), 0,
3035 mBackgroundIntent.putExtra(
3036 Intent.EXTRA_ALARM_COUNT, alarm.count),
3037 mDeliveryTracker, mHandler, null,
3038 allowWhileIdle ? mIdleOptions : null);
3039 } catch (PendingIntent.CanceledException e) {
3040 if (alarm.repeatInterval > 0) {
3041 // This IntentSender is no longer valid, but this
3042 // is a repeating alarm, so toss it
3043 removeImpl(alarm.operation);
3044 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003045 // No actual delivery was possible, so the delivery tracker's
3046 // 'finished' callback won't be invoked. We also don't need
3047 // to do any wakelock or stats tracking, so we have nothing
3048 // left to do here but go on to the next thing.
3049 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003050 }
3051 } else {
3052 // Direct listener callback alarm
3053 try {
3054 if (DEBUG_LISTENER_CALLBACK) {
3055 Slog.v(TAG, "Alarm to uid=" + alarm.uid
3056 + " listener=" + alarm.listener.asBinder());
3057 }
3058 alarm.listener.doAlarm(this);
3059 mHandler.sendMessageDelayed(
3060 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
3061 alarm.listener.asBinder()),
3062 mConstants.LISTENER_TIMEOUT);
3063 } catch (Exception e) {
3064 if (DEBUG_LISTENER_CALLBACK) {
3065 Slog.i(TAG, "Alarm undeliverable to listener "
3066 + alarm.listener.asBinder(), e);
3067 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003068 // As in the PendingIntent.CanceledException case, delivery of the
3069 // alarm was not possible, so we have no wakelock or timeout or
3070 // stats management to do. It threw before we posted the delayed
3071 // timeout message, so we're done here.
3072 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003073 }
3074 }
3075
3076 // The alarm is now in flight; now arrange wakelock and stats tracking
3077 if (mBroadcastRefCount == 0) {
3078 setWakelockWorkSource(alarm.operation, alarm.workSource,
3079 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
3080 true);
3081 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003082 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003083 }
3084 final InFlight inflight = new InFlight(AlarmManagerService.this,
3085 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
3086 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
3087 mInFlight.add(inflight);
3088 mBroadcastRefCount++;
3089
3090 if (allowWhileIdle) {
3091 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
3092 mLastAllowWhileIdleDispatch.put(alarm.uid, nowELAPSED);
3093 if (RECORD_DEVICE_IDLE_ALARMS) {
3094 IdleDispatchEntry ent = new IdleDispatchEntry();
3095 ent.uid = alarm.uid;
3096 ent.pkg = alarm.packageName;
3097 ent.tag = alarm.statsTag;
3098 ent.op = "DELIVER";
3099 ent.elapsedRealtime = nowELAPSED;
3100 mAllowWhileIdleDispatches.add(ent);
3101 }
3102 }
3103
3104 final BroadcastStats bs = inflight.mBroadcastStats;
3105 bs.count++;
3106 if (bs.nesting == 0) {
3107 bs.nesting = 1;
3108 bs.startTime = nowELAPSED;
3109 } else {
3110 bs.nesting++;
3111 }
3112 final FilterStats fs = inflight.mFilterStats;
3113 fs.count++;
3114 if (fs.nesting == 0) {
3115 fs.nesting = 1;
3116 fs.startTime = nowELAPSED;
3117 } else {
3118 fs.nesting++;
3119 }
3120 if (alarm.type == ELAPSED_REALTIME_WAKEUP
3121 || alarm.type == RTC_WAKEUP) {
3122 bs.numWakeup++;
3123 fs.numWakeup++;
3124 if (alarm.workSource != null && alarm.workSource.size() > 0) {
3125 for (int wi=0; wi<alarm.workSource.size(); wi++) {
Christopher Tate0029f572016-06-14 10:16:28 -07003126 final String wsName = alarm.workSource.getName(wi);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003127 ActivityManager.noteWakeupAlarm(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003128 alarm.operation, alarm.workSource.get(wi),
Christopher Tate0029f572016-06-14 10:16:28 -07003129 (wsName != null) ? wsName : alarm.packageName,
3130 alarm.statsTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08003131 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003132 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003133 ActivityManager.noteWakeupAlarm(
Joe Onorato78bcdf92016-05-09 10:10:29 -07003134 alarm.operation, alarm.uid, alarm.packageName, alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003135 }
3136 }
3137 }
3138 }
3139}