blob: e860dd6f39dde0fcbe5d38425ddc3a16a118dc53 [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;
Christopher Tatebb9cce52017-04-18 14:19:43 -070034import android.content.pm.ApplicationInfo;
35import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.content.pm.PackageManager;
Christopher Tatebb9cce52017-04-18 14:19:43 -070037import android.content.pm.PackageManager.NameNotFoundException;
38import android.content.pm.PermissionInfo;
Dianne Hackborna750a632015-06-16 17:18:23 -070039import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.net.Uri;
41import android.os.Binder;
42import android.os.Bundle;
Christopher Tate247571462017-04-10 11:45:05 -070043import android.os.Environment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.os.Handler;
Adam Lesinski182f73f2013-12-05 16:48:06 -080045import android.os.IBinder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.os.Message;
47import android.os.PowerManager;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070048import android.os.Process;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070049import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.os.SystemClock;
51import android.os.SystemProperties;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070052import android.os.UserHandle;
Christopher Tatec4a07d12012-04-06 14:19:13 -070053import android.os.WorkSource;
Adrian Roosc42a1e12014-07-07 23:35:53 +020054import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.text.TextUtils;
Adrian Roosc42a1e12014-07-07 23:35:53 +020056import android.text.format.DateFormat;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080057import android.util.ArrayMap;
Dianne Hackborna750a632015-06-16 17:18:23 -070058import android.util.KeyValueListParser;
Adrian Roosc42a1e12014-07-07 23:35:53 +020059import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080060import android.util.Slog;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080061import android.util.SparseArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +020062import android.util.SparseBooleanArray;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -070063import android.util.SparseLongArray;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070064import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065
Christopher Tate4cb338d2013-07-26 13:11:31 -070066import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import java.io.FileDescriptor;
68import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070069import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -080071import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import java.util.Calendar;
73import java.util.Collections;
74import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -050075import java.util.Date;
Christopher Tate1590f1e2014-10-02 17:27:57 -070076import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -070077import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +020078import java.util.Locale;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070079import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import java.util.TimeZone;
John Spurlock604a5ee2015-06-01 12:27:22 -040081import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082
Christopher Tatee0a22b32013-07-11 14:43:13 -070083import static android.app.AlarmManager.RTC_WAKEUP;
84import static android.app.AlarmManager.RTC;
85import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
86import static android.app.AlarmManager.ELAPSED_REALTIME;
87
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060088import com.android.internal.util.DumpUtils;
Dianne Hackborn81038902012-11-26 17:04:09 -080089import com.android.internal.util.LocalLog;
90
Adam Lesinski182f73f2013-12-05 16:48:06 -080091class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -070092 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
93 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -080094 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -070095 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -080096 static final int TIME_CHANGED_MASK = 1 << 16;
97 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -080098
Christopher Tatee0a22b32013-07-11 14:43:13 -070099 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -0800100 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -0800101
Adam Lesinski182f73f2013-12-05 16:48:06 -0800102 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -0800103 static final boolean localLOGV = false;
104 static final boolean DEBUG_BATCH = localLOGV || false;
105 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200106 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700107 static final boolean DEBUG_LISTENER_CALLBACK = localLOGV || false;
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800108 static final boolean DEBUG_WAKELOCK = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700109 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700110 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800111 static final int ALARM_EVENT = 1;
112 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200113
Christopher Tate14a7bb02015-10-01 10:24:31 -0700114 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800116 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117
Adam Lesinski182f73f2013-12-05 16:48:06 -0800118 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700119
Christopher Tate24cd46f2016-02-02 14:28:01 -0800120 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT =
121 new Intent(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED)
Christopher Tate50191db2017-05-09 16:02:25 -0700122 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
123 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Adrian Roosc42a1e12014-07-07 23:35:53 +0200124
Adam Lesinski182f73f2013-12-05 16:48:06 -0800125 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800126
Christopher Tate14a7bb02015-10-01 10:24:31 -0700127 AppOpsManager mAppOps;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800128 DeviceIdleController.LocalService mLocalDeviceIdleController;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700129
Adam Lesinski182f73f2013-12-05 16:48:06 -0800130 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800131
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800132 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800133 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700134 private long mNextNonWakeup;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -0700135 private long mLastWakeupSet;
136 private long mLastWakeup;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800137 int mBroadcastRefCount = 0;
138 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700139 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700140 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
141 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800142 final AlarmHandler mHandler = new AlarmHandler();
143 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700144 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700146 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800147 PendingIntent mTimeTickSender;
148 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700149 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700150 boolean mInteractive = true;
151 long mNonInteractiveStartTime;
152 long mNonInteractiveTime;
153 long mLastAlarmDeliveryTime;
154 long mStartCurrentDelayTime;
155 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700156 long mLastTimeChangeClockTime;
157 long mLastTimeChangeRealtime;
Dianne Hackborna750a632015-06-16 17:18:23 -0700158 long mAllowWhileIdleMinTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700159 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800160
Christopher Tatebb9cce52017-04-18 14:19:43 -0700161 // Bookkeeping about the identity of the "System UI" package, determined at runtime.
162
163 /**
164 * This permission must be defined by the canonical System UI package,
165 * with protection level "signature".
166 */
167 private static final String SYSTEM_UI_SELF_PERMISSION =
168 "android.permission.systemui.IDENTITY";
169
170 /**
171 * At boot we use SYSTEM_UI_SELF_PERMISSION to look up the definer's uid.
172 */
173 int mSystemUiUid;
174
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700175 /**
Dianne Hackborn262ae5c2016-02-10 16:28:29 -0800176 * The current set of user whitelisted apps for device idle mode, meaning these are allowed
177 * to freely schedule alarms.
178 */
179 int[] mDeviceIdleUserWhitelist = new int[0];
180
181 /**
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700182 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
183 * used to determine the earliest we can dispatch the next such alarm.
184 */
185 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
186
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700187 final static class IdleDispatchEntry {
188 int uid;
189 String pkg;
190 String tag;
191 String op;
192 long elapsedRealtime;
193 long argRealtime;
194 }
195 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
196
Dianne Hackborna750a632015-06-16 17:18:23 -0700197 /**
198 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
199 */
200 Bundle mIdleOptions;
201
Jose Lima235510e2014-08-13 12:50:01 -0700202 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
203 new SparseArray<>();
204 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
205 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200206 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
207 new SparseBooleanArray();
208 private boolean mNextAlarmClockMayChange;
209
210 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700211 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
212 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200213
Dianne Hackborna750a632015-06-16 17:18:23 -0700214 /**
215 * All times are in milliseconds. These constants are kept synchronized with the system
216 * global Settings. Any access to this class or its fields should be done while
217 * holding the AlarmManagerService.mLock lock.
218 */
219 private final class Constants extends ContentObserver {
220 // Key names stored in the settings value.
221 private static final String KEY_MIN_FUTURITY = "min_futurity";
222 private static final String KEY_MIN_INTERVAL = "min_interval";
223 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
224 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
225 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
226 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700227 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Dianne Hackborna750a632015-06-16 17:18:23 -0700228
229 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
230 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tateaa244da2015-08-27 15:57:57 -0700231 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700232 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700233 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
234
Christopher Tate14a7bb02015-10-01 10:24:31 -0700235 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
236
Dianne Hackborna750a632015-06-16 17:18:23 -0700237 // Minimum futurity of a new alarm
238 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
239
240 // Minimum alarm recurrence interval
241 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
242
243 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
244 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
245
246 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
247 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
248
249 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
250 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
251 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
252
Christopher Tate14a7bb02015-10-01 10:24:31 -0700253 // Direct alarm listener callback timeout
254 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
255
Dianne Hackborna750a632015-06-16 17:18:23 -0700256 private ContentResolver mResolver;
257 private final KeyValueListParser mParser = new KeyValueListParser(',');
258 private long mLastAllowWhileIdleWhitelistDuration = -1;
259
260 public Constants(Handler handler) {
261 super(handler);
262 updateAllowWhileIdleMinTimeLocked();
263 updateAllowWhileIdleWhitelistDurationLocked();
264 }
265
266 public void start(ContentResolver resolver) {
267 mResolver = resolver;
268 mResolver.registerContentObserver(Settings.Global.getUriFor(
269 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
270 updateConstants();
271 }
272
273 public void updateAllowWhileIdleMinTimeLocked() {
274 mAllowWhileIdleMinTime = mPendingIdleUntil != null
275 ? ALLOW_WHILE_IDLE_LONG_TIME : ALLOW_WHILE_IDLE_SHORT_TIME;
276 }
277
278 public void updateAllowWhileIdleWhitelistDurationLocked() {
279 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
280 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
281 BroadcastOptions opts = BroadcastOptions.makeBasic();
282 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
283 mIdleOptions = opts.toBundle();
284 }
285 }
286
287 @Override
288 public void onChange(boolean selfChange, Uri uri) {
289 updateConstants();
290 }
291
292 private void updateConstants() {
293 synchronized (mLock) {
294 try {
295 mParser.setString(Settings.Global.getString(mResolver,
296 Settings.Global.ALARM_MANAGER_CONSTANTS));
297 } catch (IllegalArgumentException e) {
298 // Failed to parse the settings string, log this and move on
299 // with defaults.
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800300 Slog.e(TAG, "Bad alarm manager settings", e);
Dianne Hackborna750a632015-06-16 17:18:23 -0700301 }
302
303 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
304 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
305 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
306 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
307 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
308 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
309 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
310 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
311 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700312 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
313 DEFAULT_LISTENER_TIMEOUT);
Dianne Hackborna750a632015-06-16 17:18:23 -0700314
315 updateAllowWhileIdleMinTimeLocked();
316 updateAllowWhileIdleWhitelistDurationLocked();
317 }
318 }
319
320 void dump(PrintWriter pw) {
321 pw.println(" Settings:");
322
323 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
324 TimeUtils.formatDuration(MIN_FUTURITY, pw);
325 pw.println();
326
327 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
328 TimeUtils.formatDuration(MIN_INTERVAL, pw);
329 pw.println();
330
Christopher Tate14a7bb02015-10-01 10:24:31 -0700331 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
332 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
333 pw.println();
334
Dianne Hackborna750a632015-06-16 17:18:23 -0700335 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
336 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
337 pw.println();
338
339 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
340 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
341 pw.println();
342
343 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
344 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
345 pw.println();
346 }
347 }
348
349 final Constants mConstants;
350
Christopher Tate1590f1e2014-10-02 17:27:57 -0700351 // Alarm delivery ordering bookkeeping
352 static final int PRIO_TICK = 0;
353 static final int PRIO_WAKEUP = 1;
354 static final int PRIO_NORMAL = 2;
355
Dianne Hackborna750a632015-06-16 17:18:23 -0700356 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700357 int seq;
358 int priority;
359
360 PriorityClass() {
361 seq = mCurrentSeq - 1;
362 priority = PRIO_NORMAL;
363 }
364 }
365
Dianne Hackborna750a632015-06-16 17:18:23 -0700366 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700367 int mCurrentSeq = 0;
368
Dianne Hackborna750a632015-06-16 17:18:23 -0700369 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700370 public long when;
371 public int uid;
372 public String action;
373
374 public WakeupEvent(long theTime, int theUid, String theAction) {
375 when = theTime;
376 uid = theUid;
377 action = theAction;
378 }
379 }
380
Adam Lesinski182f73f2013-12-05 16:48:06 -0800381 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
382 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700383
Adrian Roosc42a1e12014-07-07 23:35:53 +0200384 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700385 long start; // These endpoints are always in ELAPSED
386 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700387 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700388
389 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
390
391 Batch() {
392 start = 0;
393 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700394 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700395 }
396
397 Batch(Alarm seed) {
398 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700399 end = seed.maxWhenElapsed;
400 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700401 alarms.add(seed);
402 }
403
404 int size() {
405 return alarms.size();
406 }
407
408 Alarm get(int index) {
409 return alarms.get(index);
410 }
411
412 boolean canHold(long whenElapsed, long maxWhen) {
413 return (end >= whenElapsed) && (start <= maxWhen);
414 }
415
416 boolean add(Alarm alarm) {
417 boolean newStart = false;
418 // narrows the batch if necessary; presumes that canHold(alarm) is true
419 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
420 if (index < 0) {
421 index = 0 - index - 1;
422 }
423 alarms.add(index, alarm);
424 if (DEBUG_BATCH) {
425 Slog.v(TAG, "Adding " + alarm + " to " + this);
426 }
427 if (alarm.whenElapsed > start) {
428 start = alarm.whenElapsed;
429 newStart = true;
430 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700431 if (alarm.maxWhenElapsed < end) {
432 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700433 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700434 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700435
436 if (DEBUG_BATCH) {
437 Slog.v(TAG, " => now " + this);
438 }
439 return newStart;
440 }
441
Christopher Tate14a7bb02015-10-01 10:24:31 -0700442 boolean remove(final PendingIntent operation, final IAlarmListener listener) {
443 if (operation == null && listener == null) {
444 if (localLOGV) {
445 Slog.w(TAG, "requested remove() of null operation",
446 new RuntimeException("here"));
447 }
448 return false;
449 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700450 boolean didRemove = false;
451 long newStart = 0; // recalculate endpoints as we go
452 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700453 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700454 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700455 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700456 if (alarm.matches(operation, listener)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700457 alarms.remove(i);
458 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200459 if (alarm.alarmClock != null) {
460 mNextAlarmClockMayChange = true;
461 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700462 } else {
463 if (alarm.whenElapsed > newStart) {
464 newStart = alarm.whenElapsed;
465 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700466 if (alarm.maxWhenElapsed < newEnd) {
467 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700468 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700469 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700470 i++;
471 }
472 }
473 if (didRemove) {
474 // commit the new batch bounds
475 start = newStart;
476 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700477 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700478 }
479 return didRemove;
480 }
481
482 boolean remove(final String packageName) {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700483 if (packageName == null) {
484 if (localLOGV) {
485 Slog.w(TAG, "requested remove() of null packageName",
486 new RuntimeException("here"));
487 }
488 return false;
489 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700490 boolean didRemove = false;
491 long newStart = 0; // recalculate endpoints as we go
492 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700493 int newFlags = 0;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700494 for (int i = alarms.size()-1; i >= 0; i--) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700495 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700496 if (alarm.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700497 alarms.remove(i);
498 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200499 if (alarm.alarmClock != null) {
500 mNextAlarmClockMayChange = true;
501 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700502 } else {
503 if (alarm.whenElapsed > newStart) {
504 newStart = alarm.whenElapsed;
505 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700506 if (alarm.maxWhenElapsed < newEnd) {
507 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700508 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700509 newFlags |= alarm.flags;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700510 }
511 }
512 if (didRemove) {
513 // commit the new batch bounds
514 start = newStart;
515 end = newEnd;
516 flags = newFlags;
517 }
518 return didRemove;
519 }
520
521 boolean removeForStopped(final int uid) {
522 boolean didRemove = false;
523 long newStart = 0; // recalculate endpoints as we go
524 long newEnd = Long.MAX_VALUE;
525 int newFlags = 0;
526 for (int i = alarms.size()-1; i >= 0; i--) {
527 Alarm alarm = alarms.get(i);
528 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800529 if (alarm.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
530 uid, alarm.packageName)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700531 alarms.remove(i);
532 didRemove = true;
533 if (alarm.alarmClock != null) {
534 mNextAlarmClockMayChange = true;
535 }
536 } else {
537 if (alarm.whenElapsed > newStart) {
538 newStart = alarm.whenElapsed;
539 }
540 if (alarm.maxWhenElapsed < newEnd) {
541 newEnd = alarm.maxWhenElapsed;
542 }
543 newFlags |= alarm.flags;
544 }
545 } catch (RemoteException e) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700546 }
547 }
548 if (didRemove) {
549 // commit the new batch bounds
550 start = newStart;
551 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700552 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700553 }
554 return didRemove;
555 }
556
557 boolean remove(final int userHandle) {
558 boolean didRemove = false;
559 long newStart = 0; // recalculate endpoints as we go
560 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700561 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700562 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700563 if (UserHandle.getUserId(alarm.creatorUid) == userHandle) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700564 alarms.remove(i);
565 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200566 if (alarm.alarmClock != null) {
567 mNextAlarmClockMayChange = true;
568 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700569 } else {
570 if (alarm.whenElapsed > newStart) {
571 newStart = alarm.whenElapsed;
572 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700573 if (alarm.maxWhenElapsed < newEnd) {
574 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700575 }
576 i++;
577 }
578 }
579 if (didRemove) {
580 // commit the new batch bounds
581 start = newStart;
582 end = newEnd;
583 }
584 return didRemove;
585 }
586
587 boolean hasPackage(final String packageName) {
588 final int N = alarms.size();
589 for (int i = 0; i < N; i++) {
590 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700591 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700592 return true;
593 }
594 }
595 return false;
596 }
597
598 boolean hasWakeups() {
599 final int N = alarms.size();
600 for (int i = 0; i < N; i++) {
601 Alarm a = alarms.get(i);
602 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
603 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
604 return true;
605 }
606 }
607 return false;
608 }
609
610 @Override
611 public String toString() {
612 StringBuilder b = new StringBuilder(40);
613 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
614 b.append(" num="); b.append(size());
615 b.append(" start="); b.append(start);
616 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700617 if (flags != 0) {
618 b.append(" flgs=0x");
619 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700620 }
621 b.append('}');
622 return b.toString();
623 }
624 }
625
626 static class BatchTimeOrder implements Comparator<Batch> {
627 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800628 long when1 = b1.start;
629 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800630 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700631 return 1;
632 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800633 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700634 return -1;
635 }
636 return 0;
637 }
638 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800639
640 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
641 @Override
642 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700643 // priority class trumps everything. TICK < WAKEUP < NORMAL
644 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
645 return -1;
646 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
647 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800648 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700649
650 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800651 if (lhs.whenElapsed < rhs.whenElapsed) {
652 return -1;
653 } else if (lhs.whenElapsed > rhs.whenElapsed) {
654 return 1;
655 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700656
657 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800658 return 0;
659 }
660 };
661
Christopher Tate1590f1e2014-10-02 17:27:57 -0700662 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
663 final int N = alarms.size();
664 for (int i = 0; i < N; i++) {
665 Alarm a = alarms.get(i);
666
667 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700668 if (a.operation != null
669 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700670 alarmPrio = PRIO_TICK;
671 } else if (a.wakeup) {
672 alarmPrio = PRIO_WAKEUP;
673 } else {
674 alarmPrio = PRIO_NORMAL;
675 }
676
677 PriorityClass packagePrio = a.priorityClass;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700678 String alarmPackage = (a.operation != null)
679 ? a.operation.getCreatorPackage()
680 : a.packageName;
681 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700682 if (packagePrio == null) {
683 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700684 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700685 }
686 a.priorityClass = packagePrio;
687
688 if (packagePrio.seq != mCurrentSeq) {
689 // first alarm we've seen in the current delivery generation from this package
690 packagePrio.priority = alarmPrio;
691 packagePrio.seq = mCurrentSeq;
692 } else {
693 // Multiple alarms from this package being delivered in this generation;
694 // bump the package's delivery class if it's warranted.
695 // TICK < WAKEUP < NORMAL
696 if (alarmPrio < packagePrio.priority) {
697 packagePrio.priority = alarmPrio;
698 }
699 }
700 }
701 }
702
Christopher Tatee0a22b32013-07-11 14:43:13 -0700703 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800704 static final long MIN_FUZZABLE_INTERVAL = 10000;
705 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700706 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
707
708 // set to null if in idle mode; while in this mode, any alarms we don't want
709 // to run during this time are placed in mPendingWhileIdleAlarms
710 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700711 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700712 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700713
Jeff Brownb880d882014-02-10 19:47:07 -0800714 public AlarmManagerService(Context context) {
715 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700716 mConstants = new Constants(mHandler);
Jeff Brownb880d882014-02-10 19:47:07 -0800717 }
718
Christopher Tatee0a22b32013-07-11 14:43:13 -0700719 static long convertToElapsed(long when, int type) {
720 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
721 if (isRtc) {
722 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
723 }
724 return when;
725 }
726
727 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
728 // calculate the end of our nominal delivery window for the alarm.
729 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
730 // Current heuristic: batchable window is 75% of either the recurrence interval
731 // [for a periodic alarm] or of the time from now to the desired delivery time,
732 // with a minimum delay/interval of 10 seconds, under which we will simply not
733 // defer the alarm.
734 long futurity = (interval == 0)
735 ? (triggerAtTime - now)
736 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700737 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700738 futurity = 0;
739 }
740 return triggerAtTime + (long)(.75 * futurity);
741 }
742
743 // returns true if the batch was added at the head
744 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
745 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
746 if (index < 0) {
747 index = 0 - index - 1;
748 }
749 list.add(index, newBatch);
750 return (index == 0);
751 }
752
Christopher Tate385e4982013-07-23 18:22:29 -0700753 // Return the index of the matching batch, or -1 if none found.
754 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700755 final int N = mAlarmBatches.size();
756 for (int i = 0; i < N; i++) {
757 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700758 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700759 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700760 }
761 }
Christopher Tate385e4982013-07-23 18:22:29 -0700762 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700763 }
764
765 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
766 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700767 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700768 rebatchAllAlarmsLocked(true);
769 }
770 }
771
772 void rebatchAllAlarmsLocked(boolean doValidate) {
773 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
774 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700775 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700776 final long nowElapsed = SystemClock.elapsedRealtime();
777 final int oldBatches = oldSet.size();
778 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
779 Batch batch = oldSet.get(batchNum);
780 final int N = batch.size();
781 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700782 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700783 }
784 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700785 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
786 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
787 + " to " + mPendingIdleUntil);
788 if (mPendingIdleUntil == null) {
789 // Somehow we lost this... we need to restore all of the pending alarms.
790 restorePendingWhileIdleAlarmsLocked();
791 }
792 }
793 rescheduleKernelAlarmsLocked();
794 updateNextAlarmClockLocked();
795 }
796
797 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
798 a.when = a.origWhen;
799 long whenElapsed = convertToElapsed(a.when, a.type);
800 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700801 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700802 // Exact
803 maxElapsed = whenElapsed;
804 } else {
805 // Not exact. Preserve any explicit window, otherwise recalculate
806 // the window based on the alarm's new futurity. Note that this
807 // reflects a policy of preferring timely to deferred delivery.
808 maxElapsed = (a.windowLength > 0)
809 ? (whenElapsed + a.windowLength)
810 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
811 }
812 a.whenElapsed = whenElapsed;
813 a.maxWhenElapsed = maxElapsed;
814 setImplLocked(a, true, doValidate);
815 }
816
817 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700818 if (RECORD_DEVICE_IDLE_ALARMS) {
819 IdleDispatchEntry ent = new IdleDispatchEntry();
820 ent.uid = 0;
821 ent.pkg = "FINISH IDLE";
822 ent.elapsedRealtime = SystemClock.elapsedRealtime();
823 mAllowWhileIdleDispatches.add(ent);
824 }
825
Dianne Hackborn35d54032015-04-23 10:30:43 -0700826 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700827 if (mPendingWhileIdleAlarms.size() > 0) {
828 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
829 mPendingWhileIdleAlarms = new ArrayList<>();
830 final long nowElapsed = SystemClock.elapsedRealtime();
831 for (int i=alarms.size() - 1; i >= 0; i--) {
832 Alarm a = alarms.get(i);
833 reAddAlarmLocked(a, nowElapsed, false);
834 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700835 }
Dianne Hackborn35d54032015-04-23 10:30:43 -0700836
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700837 // Make sure we are using the correct ALLOW_WHILE_IDLE min time.
Dianne Hackborna750a632015-06-16 17:18:23 -0700838 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700839
Dianne Hackborn35d54032015-04-23 10:30:43 -0700840 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700841 rescheduleKernelAlarmsLocked();
842 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -0700843
844 // And send a TIME_TICK right now, since it is important to get the UI updated.
845 try {
846 mTimeTickSender.send();
847 } catch (PendingIntent.CanceledException e) {
848 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700849 }
850
Christopher Tate14a7bb02015-10-01 10:24:31 -0700851 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -0800852 final PendingIntent mPendingIntent;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700853 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -0700854 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700855 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700856 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800857 final BroadcastStats mBroadcastStats;
858 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800859 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800860
Christopher Tate14a7bb02015-10-01 10:24:31 -0700861 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
862 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
863 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800864 mPendingIntent = pendingIntent;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700865 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -0700866 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700867 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700868 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700869 mBroadcastStats = (pendingIntent != null)
870 ? service.getStatsLocked(pendingIntent)
871 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700872 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -0800873 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700874 fs = new FilterStats(mBroadcastStats, mTag);
875 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -0800876 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700877 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -0800878 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800879 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800880 }
Makoto Onuki33955e12017-03-01 18:11:00 -0800881
882 @Override
883 public String toString() {
884 return "InFlight{"
885 + "pendingIntent=" + mPendingIntent
886 + ", workSource=" + mWorkSource
887 + ", uid=" + mUid
888 + ", tag=" + mTag
889 + ", broadcastStats=" + mBroadcastStats
890 + ", filterStats=" + mFilterStats
891 + ", alarmType=" + mAlarmType
892 + "}";
893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800895
Adam Lesinski182f73f2013-12-05 16:48:06 -0800896 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -0800897 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700898 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800899
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700900 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800902 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 int numWakeup;
904 long startTime;
905 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -0800906
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700907 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800908 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700909 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800910 }
Makoto Onuki33955e12017-03-01 18:11:00 -0800911
912 @Override
913 public String toString() {
914 return "FilterStats{"
915 + "tag=" + mTag
916 + ", lastTime=" + lastTime
917 + ", aggregateTime=" + aggregateTime
918 + ", count=" + count
919 + ", numWakeup=" + numWakeup
920 + ", startTime=" + startTime
921 + ", nesting=" + nesting
922 + "}";
923 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800924 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700925
Adam Lesinski182f73f2013-12-05 16:48:06 -0800926 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800927 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800928 final String mPackageName;
929
930 long aggregateTime;
931 int count;
932 int numWakeup;
933 long startTime;
934 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700935 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -0800936
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800937 BroadcastStats(int uid, String packageName) {
938 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -0800939 mPackageName = packageName;
940 }
Makoto Onuki33955e12017-03-01 18:11:00 -0800941
942 @Override
943 public String toString() {
944 return "BroadcastStats{"
945 + "uid=" + mUid
946 + ", packageName=" + mPackageName
947 + ", aggregateTime=" + aggregateTime
948 + ", count=" + count
949 + ", numWakeup=" + numWakeup
950 + ", startTime=" + startTime
951 + ", nesting=" + nesting
952 + "}";
953 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700955
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800956 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
957 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700958
959 int mNumDelayedAlarms = 0;
960 long mTotalDelayTime = 0;
961 long mMaxDelayTime = 0;
962
Adam Lesinski182f73f2013-12-05 16:48:06 -0800963 @Override
964 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -0800965 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800966 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800967
968 // We have to set current TimeZone info to kernel
969 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -0800970 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +0800971
Christopher Tate247571462017-04-10 11:45:05 -0700972 // Also sure that we're booting with a halfway sensible current time
973 if (mNativeData != 0) {
974 final long systemBuildTime = Environment.getRootDirectory().lastModified();
975 if (System.currentTimeMillis() < systemBuildTime) {
976 Slog.i(TAG, "Current time only " + System.currentTimeMillis()
977 + ", advancing to build time " + systemBuildTime);
978 setKernelTime(mNativeData, systemBuildTime);
979 }
980 }
981
Christopher Tatebb9cce52017-04-18 14:19:43 -0700982 // Determine SysUI's uid
983 final PackageManager packMan = getContext().getPackageManager();
984 try {
985 PermissionInfo sysUiPerm = packMan.getPermissionInfo(SYSTEM_UI_SELF_PERMISSION, 0);
986 ApplicationInfo sysUi = packMan.getApplicationInfo(sysUiPerm.packageName, 0);
987 if ((sysUi.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
988 mSystemUiUid = sysUi.uid;
989 } else {
990 Slog.e(TAG, "SysUI permission " + SYSTEM_UI_SELF_PERMISSION
991 + " defined by non-privileged app " + sysUi.packageName
992 + " - ignoring");
993 }
994 } catch (NameNotFoundException e) {
995 }
996
997 if (mSystemUiUid <= 0) {
998 Slog.wtf(TAG, "SysUI package not found!");
999 }
1000
Adam Lesinski182f73f2013-12-05 16:48:06 -08001001 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001002 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001003
Adam Lesinski182f73f2013-12-05 16:48:06 -08001004 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001006 Intent.FLAG_RECEIVER_REGISTERED_ONLY
Chad Brubaker291df4f2017-03-14 10:23:02 -07001007 | Intent.FLAG_RECEIVER_FOREGROUND
1008 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001009 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001010 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001011 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1012 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001013 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001014 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015
1016 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -08001017 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 mClockReceiver.scheduleTimeTickEvent();
1019 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001020 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021 mUninstallReceiver = new UninstallReceiver();
1022
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001023 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001024 AlarmThread waitThread = new AlarmThread();
1025 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001027 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001029
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001030 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001031 ActivityManager.getService().registerUidObserver(new UidObserver(),
Dianne Hackborn5614bf52016-11-07 17:26:41 -08001032 ActivityManager.UID_OBSERVER_IDLE, ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001033 } catch (RemoteException e) {
1034 // ignored; both services live in system_server
1035 }
1036
Adam Lesinski182f73f2013-12-05 16:48:06 -08001037 publishBinderService(Context.ALARM_SERVICE, mService);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001038 publishLocalService(LocalService.class, new LocalService());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001040
1041 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001042 public void onBootPhase(int phase) {
1043 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1044 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -07001045 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001046 mLocalDeviceIdleController
1047 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackborna750a632015-06-16 17:18:23 -07001048 }
1049 }
1050
1051 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 protected void finalize() throws Throwable {
1053 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001054 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 } finally {
1056 super.finalize();
1057 }
1058 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001059
Adam Lesinski182f73f2013-12-05 16:48:06 -08001060 void setTimeZoneImpl(String tz) {
1061 if (TextUtils.isEmpty(tz)) {
1062 return;
David Christieebe51fc2013-07-26 13:23:29 -07001063 }
1064
Adam Lesinski182f73f2013-12-05 16:48:06 -08001065 TimeZone zone = TimeZone.getTimeZone(tz);
1066 // Prevent reentrant calls from stepping on each other when writing
1067 // the time zone property
1068 boolean timeZoneWasChanged = false;
1069 synchronized (this) {
1070 String current = SystemProperties.get(TIMEZONE_PROPERTY);
1071 if (current == null || !current.equals(zone.getID())) {
1072 if (localLOGV) {
1073 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
1074 }
1075 timeZoneWasChanged = true;
1076 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
1077 }
1078
1079 // Update the kernel timezone information
1080 // Kernel tracks time offsets as 'minutes west of GMT'
1081 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001082 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001083 }
1084
1085 TimeZone.setDefault(null);
1086
1087 if (timeZoneWasChanged) {
1088 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001089 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate5cdf9f82017-05-03 18:10:39 -07001090 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
Chad Brubaker291df4f2017-03-14 10:23:02 -07001091 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001092 intent.putExtra("time-zone", zone.getID());
1093 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1094 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001096
Adam Lesinski182f73f2013-12-05 16:48:06 -08001097 void removeImpl(PendingIntent operation) {
1098 if (operation == null) {
1099 return;
1100 }
1101 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001102 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001103 }
1104 }
1105
1106 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001107 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1108 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1109 int callingUid, String callingPackage) {
1110 // must be *either* PendingIntent or AlarmReceiver, but not both
1111 if ((operation == null && directReceiver == null)
1112 || (operation != null && directReceiver != null)) {
1113 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1114 // NB: previous releases failed silently here, so we are continuing to do the same
1115 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 return;
1117 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001118
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001119 // Sanity check the window length. This will catch people mistakenly
1120 // trying to pass an end-of-window timestamp rather than a duration.
1121 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1122 Slog.w(TAG, "Window length " + windowLength
1123 + "ms suspiciously long; limiting to 1 hour");
1124 windowLength = AlarmManager.INTERVAL_HOUR;
1125 }
1126
Christopher Tate498c6cb2014-11-17 16:09:27 -08001127 // Sanity check the recurrence interval. This will catch people who supply
1128 // seconds when the API expects milliseconds.
Dianne Hackborna750a632015-06-16 17:18:23 -07001129 final long minInterval = mConstants.MIN_INTERVAL;
1130 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001131 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001132 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001133 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001134 interval = minInterval;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001135 }
1136
Christopher Tatee0a22b32013-07-11 14:43:13 -07001137 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1138 throw new IllegalArgumentException("Invalid alarm type " + type);
1139 }
1140
Christopher Tate5f221e82013-07-30 17:13:15 -07001141 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001142 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001143 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001144 + " pid=" + what);
1145 triggerAtTime = 0;
1146 }
1147
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001148 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001149 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1150 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001151 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001152 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1153
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001154 final long maxElapsed;
1155 if (windowLength == AlarmManager.WINDOW_EXACT) {
1156 maxElapsed = triggerElapsed;
1157 } else if (windowLength < 0) {
1158 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001159 // Fix this window in place, so that as time approaches we don't collapse it.
1160 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001161 } else {
1162 maxElapsed = triggerElapsed + windowLength;
1163 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001164
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001165 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001166 if (DEBUG_BATCH) {
1167 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001168 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001169 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001170 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001172 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001173 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1174 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175 }
1176 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001177
Christopher Tate3e04b472013-10-21 17:51:31 -07001178 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001179 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1180 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1181 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001182 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001183 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1184 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001185 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001186 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001187 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1188 + " -- package not allowed to start");
1189 return;
1190 }
1191 } catch (RemoteException e) {
1192 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001193 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001194 setImplLocked(a, false, doValidate);
1195 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001196
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001197 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1198 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001199 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001200 // The caller has given the time they want this to happen at, however we need
1201 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001202 // bring us out of idle at an earlier time.
1203 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001204 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001205 }
1206 // Add fuzz to make the alarm go off some time before the actual desired time.
1207 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001208 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001209 if (fuzz > 0) {
1210 if (mRandom == null) {
1211 mRandom = new Random();
1212 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001213 final int delta = mRandom.nextInt(fuzz);
1214 a.whenElapsed -= delta;
1215 if (false) {
1216 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1217 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1218 Slog.d(TAG, "Applied fuzz: " + fuzz);
1219 Slog.d(TAG, "Final delta: " + delta);
1220 Slog.d(TAG, "Final when: " + a.whenElapsed);
1221 }
1222 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001223 }
1224
1225 } else if (mPendingIdleUntil != null) {
1226 // We currently have an idle until alarm scheduled; if the new alarm has
1227 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001228 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1229 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1230 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001231 == 0) {
1232 mPendingWhileIdleAlarms.add(a);
1233 return;
1234 }
1235 }
1236
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001237 if (RECORD_DEVICE_IDLE_ALARMS) {
1238 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1239 IdleDispatchEntry ent = new IdleDispatchEntry();
1240 ent.uid = a.uid;
1241 ent.pkg = a.operation.getCreatorPackage();
1242 ent.tag = a.operation.getTag("");
1243 ent.op = "SET";
1244 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1245 ent.argRealtime = a.whenElapsed;
1246 mAllowWhileIdleDispatches.add(ent);
1247 }
1248 }
1249
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001250 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
1251 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -07001252 if (whichBatch < 0) {
1253 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001254 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 } else {
Christopher Tate385e4982013-07-23 18:22:29 -07001256 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001257 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001258 // The start time of this batch advanced, so batch ordering may
1259 // have just been broken. Move it to where it now belongs.
1260 mAlarmBatches.remove(whichBatch);
1261 addBatchLocked(mAlarmBatches, batch);
1262 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263 }
1264
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001265 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001266 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001267 }
1268
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001269 boolean needRebatch = false;
1270
1271 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001272 if (RECORD_DEVICE_IDLE_ALARMS) {
1273 if (mPendingIdleUntil == null) {
1274 IdleDispatchEntry ent = new IdleDispatchEntry();
1275 ent.uid = 0;
1276 ent.pkg = "START IDLE";
1277 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1278 mAllowWhileIdleDispatches.add(ent);
1279 }
1280 }
Makoto Onuki4274a6d2017-04-21 12:21:25 -07001281 if ((mPendingIdleUntil != a) && (mPendingIdleUntil != null)) {
1282 Slog.wtfStack(TAG, "setImplLocked: idle until changed from " + mPendingIdleUntil
1283 + " to " + a);
1284 }
1285
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001286 mPendingIdleUntil = a;
Dianne Hackborna750a632015-06-16 17:18:23 -07001287 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001288 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001289 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1290 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1291 mNextWakeFromIdle = a;
1292 // If this wake from idle is earlier than whatever was previously scheduled,
1293 // and we are currently idling, then we need to rebatch alarms in case the idle
1294 // until time needs to be updated.
1295 if (mPendingIdleUntil != null) {
1296 needRebatch = true;
1297 }
1298 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001299 }
1300
1301 if (!rebatching) {
1302 if (DEBUG_VALIDATE) {
1303 if (doValidate && !validateConsistencyLocked()) {
1304 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1305 + " when(hex)=" + Long.toHexString(a.when)
1306 + " whenElapsed=" + a.whenElapsed
1307 + " maxWhenElapsed=" + a.maxWhenElapsed
1308 + " interval=" + a.repeatInterval + " op=" + a.operation
1309 + " flags=0x" + Integer.toHexString(a.flags));
1310 rebatchAllAlarmsLocked(false);
1311 needRebatch = false;
1312 }
1313 }
1314
1315 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001316 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001317 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001318
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001319 rescheduleKernelAlarmsLocked();
1320 updateNextAlarmClockLocked();
1321 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001322 }
1323
Adam Lesinski182f73f2013-12-05 16:48:06 -08001324 private final IBinder mService = new IAlarmManager.Stub() {
1325 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001326 public void set(String callingPackage,
1327 int type, long triggerAtTime, long windowLength, long interval, int flags,
1328 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1329 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001330 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001331
1332 // make sure the caller is not lying about which package should be blamed for
1333 // wakelock time spent in alarm delivery
1334 mAppOps.checkPackage(callingUid, callingPackage);
1335
1336 // Repeating alarms must use PendingIntent, not direct listener
1337 if (interval != 0) {
1338 if (directReceiver != null) {
1339 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1340 }
1341 }
1342
Adam Lesinski182f73f2013-12-05 16:48:06 -08001343 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001344 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001345 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001346 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001347 }
1348
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001349 // No incoming callers can request either WAKE_FROM_IDLE or
1350 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1351 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1352 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1353
1354 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1355 // manager when to come out of idle mode, which is only for DeviceIdleController.
1356 if (callingUid != Process.SYSTEM_UID) {
1357 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1358 }
1359
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001360 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001361 if (windowLength == AlarmManager.WINDOW_EXACT) {
1362 flags |= AlarmManager.FLAG_STANDALONE;
1363 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001364
1365 // If this alarm is for an alarm clock, then it must be standalone and we will
1366 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001367 if (alarmClock != null) {
1368 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001369
1370 // If the caller is a core system component or on the user's whitelist, and not calling
1371 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1372 // This means we will allow these alarms to go off as normal even while idle, with no
1373 // timing restrictions.
1374 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
Christopher Tatebb9cce52017-04-18 14:19:43 -07001375 || callingUid == mSystemUiUid
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001376 || Arrays.binarySearch(mDeviceIdleUserWhitelist,
1377 UserHandle.getAppId(callingUid)) >= 0)) {
1378 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1379 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001380 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001381
Christopher Tate14a7bb02015-10-01 10:24:31 -07001382 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1383 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001384 }
Christopher Tate89779822012-08-31 14:40:03 -07001385
Adam Lesinski182f73f2013-12-05 16:48:06 -08001386 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001387 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001388 getContext().enforceCallingOrSelfPermission(
1389 "android.permission.SET_TIME",
1390 "setTime");
1391
Greg Hackmann0cab8962014-02-21 16:35:52 -08001392 if (mNativeData == 0) {
1393 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1394 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001395 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001396
1397 synchronized (mLock) {
1398 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001401
1402 @Override
1403 public void setTimeZone(String tz) {
1404 getContext().enforceCallingOrSelfPermission(
1405 "android.permission.SET_TIME_ZONE",
1406 "setTimeZone");
1407
1408 final long oldId = Binder.clearCallingIdentity();
1409 try {
1410 setTimeZoneImpl(tz);
1411 } finally {
1412 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 }
1414 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001415
Adam Lesinski182f73f2013-12-05 16:48:06 -08001416 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001417 public void remove(PendingIntent operation, IAlarmListener listener) {
1418 if (operation == null && listener == null) {
1419 Slog.w(TAG, "remove() with no intent or listener");
1420 return;
1421 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001422
Christopher Tate14a7bb02015-10-01 10:24:31 -07001423 synchronized (mLock) {
1424 removeLocked(operation, listener);
1425 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001427
Adam Lesinski182f73f2013-12-05 16:48:06 -08001428 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001429 public long getNextWakeFromIdleTime() {
1430 return getNextWakeFromIdleTimeImpl();
1431 }
1432
1433 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001434 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001435 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1436 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1437 "getNextAlarmClock", null);
1438
1439 return getNextAlarmClockImpl(userId);
1440 }
1441
1442 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001443 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06001444 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001445 dumpImpl(pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001446 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001447 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001448
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001449 public final class LocalService {
1450 public void setDeviceIdleUserWhitelist(int[] appids) {
1451 setDeviceIdleUserWhitelistImpl(appids);
1452 }
1453 }
1454
Adam Lesinski182f73f2013-12-05 16:48:06 -08001455 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 synchronized (mLock) {
1457 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001458 mConstants.dump(pw);
1459 pw.println();
1460
Christopher Tatee0a22b32013-07-11 14:43:13 -07001461 final long nowRTC = System.currentTimeMillis();
1462 final long nowELAPSED = SystemClock.elapsedRealtime();
1463 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1464
Dianne Hackborna750a632015-06-16 17:18:23 -07001465 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001466 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001467 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001468 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001469 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001470 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001471 pw.print(" mLastTimeChangeRealtime=");
Dianne Hackbornc3527222015-05-13 14:03:20 -07001472 TimeUtils.formatDuration(mLastTimeChangeRealtime, pw);
1473 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001474 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001475 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001476 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1477 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001478 pw.print(" Max wakeup delay: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001479 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1480 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001481 pw.print(" Time since last dispatch: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001482 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1483 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001484 pw.print(" Next non-wakeup delivery time: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001485 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1486 pw.println();
1487 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001488
1489 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1490 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001491 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001492 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001493 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001494 pw.print(" Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001495 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001496 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
1497 pw.print(" set at "); TimeUtils.formatDuration(mLastWakeupSet, nowELAPSED, pw);
1498 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001499 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001500 pw.println(" mDeviceIdleUserWhitelist=" + Arrays.toString(mDeviceIdleUserWhitelist));
Christopher Tatee0a22b32013-07-11 14:43:13 -07001501
John Spurlock604a5ee2015-06-01 12:27:22 -04001502 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001503 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001504 final TreeSet<Integer> users = new TreeSet<>();
1505 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1506 users.add(mNextAlarmClockForUser.keyAt(i));
1507 }
1508 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1509 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1510 }
1511 for (int user : users) {
1512 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1513 final long time = next != null ? next.getTriggerTime() : 0;
1514 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001515 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001516 pw.print(" pendingSend:"); pw.print(pendingSend);
1517 pw.print(" time:"); pw.print(time);
1518 if (time > 0) {
1519 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1520 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1521 }
1522 pw.println();
1523 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001524 if (mAlarmBatches.size() > 0) {
1525 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001526 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001527 pw.println(mAlarmBatches.size());
1528 for (Batch b : mAlarmBatches) {
1529 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001530 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001531 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001533 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001534 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001535 pw.println(" Idle mode state:");
1536 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001537 if (mPendingIdleUntil != null) {
1538 pw.println(mPendingIdleUntil);
Dianne Hackbornf3831292015-10-15 14:51:06 -07001539 mPendingIdleUntil.dump(pw, " ", nowRTC, nowELAPSED, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001540 } else {
1541 pw.println("null");
1542 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001543 pw.println(" Pending alarms:");
1544 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001545 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001546 if (mNextWakeFromIdle != null) {
1547 pw.println();
1548 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
1549 mNextWakeFromIdle.dump(pw, " ", nowRTC, nowELAPSED, sdf);
1550 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001551
1552 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001553 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001554 if (mPendingNonWakeupAlarms.size() > 0) {
1555 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001556 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001557 } else {
1558 pw.println("(none)");
1559 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001560 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001561 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1562 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001563 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001564 pw.print(", max non-interactive time: ");
1565 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1566 pw.println();
1567
1568 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001569 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001570 pw.println();
1571
Christopher Tate7f2a0352015-12-08 10:24:33 -08001572 if (mInFlight.size() > 0) {
1573 pw.println("Outstanding deliveries:");
1574 for (int i = 0; i < mInFlight.size(); i++) {
1575 pw.print(" #"); pw.print(i); pw.print(": ");
1576 pw.println(mInFlight.get(i));
1577 }
1578 pw.println();
1579 }
1580
Dianne Hackborna750a632015-06-16 17:18:23 -07001581 pw.print(" mAllowWhileIdleMinTime=");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001582 TimeUtils.formatDuration(mAllowWhileIdleMinTime, pw);
1583 pw.println();
1584 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001585 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001586 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
1587 pw.print(" UID ");
1588 UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
1589 pw.print(": ");
1590 TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i),
1591 nowELAPSED, pw);
1592 pw.println();
1593 }
1594 }
1595 pw.println();
1596
Dianne Hackborn81038902012-11-26 17:04:09 -08001597 if (mLog.dump(pw, " Recent problems", " ")) {
1598 pw.println();
1599 }
1600
1601 final FilterStats[] topFilters = new FilterStats[10];
1602 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1603 @Override
1604 public int compare(FilterStats lhs, FilterStats rhs) {
1605 if (lhs.aggregateTime < rhs.aggregateTime) {
1606 return 1;
1607 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1608 return -1;
1609 }
1610 return 0;
1611 }
1612 };
1613 int len = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001614 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1615 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1616 for (int ip=0; ip<uidStats.size(); ip++) {
1617 BroadcastStats bs = uidStats.valueAt(ip);
1618 for (int is=0; is<bs.filterStats.size(); is++) {
1619 FilterStats fs = bs.filterStats.valueAt(is);
1620 int pos = len > 0
1621 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1622 if (pos < 0) {
1623 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001624 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001625 if (pos < topFilters.length) {
1626 int copylen = topFilters.length - pos - 1;
1627 if (copylen > 0) {
1628 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1629 }
1630 topFilters[pos] = fs;
1631 if (len < topFilters.length) {
1632 len++;
1633 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001634 }
1635 }
1636 }
1637 }
1638 if (len > 0) {
1639 pw.println(" Top Alarms:");
1640 for (int i=0; i<len; i++) {
1641 FilterStats fs = topFilters[i];
1642 pw.print(" ");
1643 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1644 TimeUtils.formatDuration(fs.aggregateTime, pw);
1645 pw.print(" running, "); pw.print(fs.numWakeup);
1646 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001647 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1648 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001649 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001650 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001651 pw.println();
1652 }
1653 }
1654
1655 pw.println(" ");
1656 pw.println(" Alarm Stats:");
1657 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001658 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1659 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1660 for (int ip=0; ip<uidStats.size(); ip++) {
1661 BroadcastStats bs = uidStats.valueAt(ip);
1662 pw.print(" ");
1663 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1664 UserHandle.formatUid(pw, bs.mUid);
1665 pw.print(":");
1666 pw.print(bs.mPackageName);
1667 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1668 pw.print(" running, "); pw.print(bs.numWakeup);
1669 pw.println(" wakeups:");
1670 tmpFilters.clear();
1671 for (int is=0; is<bs.filterStats.size(); is++) {
1672 tmpFilters.add(bs.filterStats.valueAt(is));
1673 }
1674 Collections.sort(tmpFilters, comparator);
1675 for (int i=0; i<tmpFilters.size(); i++) {
1676 FilterStats fs = tmpFilters.get(i);
1677 pw.print(" ");
1678 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1679 TimeUtils.formatDuration(fs.aggregateTime, pw);
1680 pw.print(" "); pw.print(fs.numWakeup);
1681 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001682 pw.print(" alarms, last ");
1683 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1684 pw.println(":");
1685 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001686 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001687 pw.println();
1688 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 }
1690 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001691
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001692 if (RECORD_DEVICE_IDLE_ALARMS) {
1693 pw.println();
1694 pw.println(" Allow while idle dispatches:");
1695 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
1696 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
1697 pw.print(" ");
1698 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
1699 pw.print(": ");
1700 UserHandle.formatUid(pw, ent.uid);
1701 pw.print(":");
1702 pw.println(ent.pkg);
1703 if (ent.op != null) {
1704 pw.print(" ");
1705 pw.print(ent.op);
1706 pw.print(" / ");
1707 pw.print(ent.tag);
1708 if (ent.argRealtime != 0) {
1709 pw.print(" (");
1710 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
1711 pw.print(")");
1712 }
1713 pw.println();
1714 }
1715 }
1716 }
1717
Christopher Tate18a75f12013-07-01 18:18:59 -07001718 if (WAKEUP_STATS) {
1719 pw.println();
1720 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001721 long last = -1;
1722 for (WakeupEvent event : mRecentWakeups) {
1723 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1724 pw.print('|');
1725 if (last < 0) {
1726 pw.print('0');
1727 } else {
1728 pw.print(event.when - last);
1729 }
1730 last = event.when;
1731 pw.print('|'); pw.print(event.uid);
1732 pw.print('|'); pw.print(event.action);
1733 pw.println();
1734 }
1735 pw.println();
1736 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 }
1738 }
1739
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001740 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001741 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
1742 PrintWriter pw = new PrintWriter(bs);
1743 final long nowRTC = System.currentTimeMillis();
1744 final long nowELAPSED = SystemClock.elapsedRealtime();
1745 final int NZ = mAlarmBatches.size();
1746 for (int iz = 0; iz < NZ; iz++) {
1747 Batch bz = mAlarmBatches.get(iz);
1748 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001749 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001750 pw.flush();
1751 Slog.v(TAG, bs.toString());
1752 bs.reset();
1753 }
1754 }
1755
1756 private boolean validateConsistencyLocked() {
1757 if (DEBUG_VALIDATE) {
1758 long lastTime = Long.MIN_VALUE;
1759 final int N = mAlarmBatches.size();
1760 for (int i = 0; i < N; i++) {
1761 Batch b = mAlarmBatches.get(i);
1762 if (b.start >= lastTime) {
1763 // duplicate start times are okay because of standalone batches
1764 lastTime = b.start;
1765 } else {
1766 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001767 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1768 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001769 return false;
1770 }
1771 }
1772 }
1773 return true;
1774 }
1775
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001776 private Batch findFirstWakeupBatchLocked() {
1777 final int N = mAlarmBatches.size();
1778 for (int i = 0; i < N; i++) {
1779 Batch b = mAlarmBatches.get(i);
1780 if (b.hasWakeups()) {
1781 return b;
1782 }
1783 }
1784 return null;
1785 }
1786
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001787 long getNextWakeFromIdleTimeImpl() {
1788 synchronized (mLock) {
1789 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
1790 }
1791 }
1792
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001793 void setDeviceIdleUserWhitelistImpl(int[] appids) {
1794 synchronized (mLock) {
1795 mDeviceIdleUserWhitelist = appids;
1796 }
1797 }
1798
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001799 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001800 synchronized (mLock) {
1801 return mNextAlarmClockForUser.get(userId);
1802 }
1803 }
1804
1805 /**
1806 * Recomputes the next alarm clock for all users.
1807 */
1808 private void updateNextAlarmClockLocked() {
1809 if (!mNextAlarmClockMayChange) {
1810 return;
1811 }
1812 mNextAlarmClockMayChange = false;
1813
Jose Lima235510e2014-08-13 12:50:01 -07001814 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001815 nextForUser.clear();
1816
1817 final int N = mAlarmBatches.size();
1818 for (int i = 0; i < N; i++) {
1819 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
1820 final int M = alarms.size();
1821
1822 for (int j = 0; j < M; j++) {
1823 Alarm a = alarms.get(j);
1824 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001825 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07001826 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001827
1828 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07001829 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001830 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02001831 " for user " + userId);
1832 }
1833
1834 // Alarms and batches are sorted by time, no need to compare times here.
1835 if (nextForUser.get(userId) == null) {
1836 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07001837 } else if (a.alarmClock.equals(current)
1838 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
1839 // same/earlier time and it's the one we cited before, so stick with it
1840 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001841 }
1842 }
1843 }
1844 }
1845
1846 // Update mNextAlarmForUser with new values.
1847 final int NN = nextForUser.size();
1848 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07001849 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001850 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001851 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001852 if (!newAlarm.equals(currentAlarm)) {
1853 updateNextAlarmInfoForUserLocked(userId, newAlarm);
1854 }
1855 }
1856
1857 // Remove users without any alarm clocks scheduled.
1858 final int NNN = mNextAlarmClockForUser.size();
1859 for (int i = NNN - 1; i >= 0; i--) {
1860 int userId = mNextAlarmClockForUser.keyAt(i);
1861 if (nextForUser.get(userId) == null) {
1862 updateNextAlarmInfoForUserLocked(userId, null);
1863 }
1864 }
1865 }
1866
Jose Lima235510e2014-08-13 12:50:01 -07001867 private void updateNextAlarmInfoForUserLocked(int userId,
1868 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001869 if (alarmClock != null) {
1870 if (DEBUG_ALARM_CLOCK) {
1871 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001872 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02001873 }
1874 mNextAlarmClockForUser.put(userId, alarmClock);
1875 } else {
1876 if (DEBUG_ALARM_CLOCK) {
1877 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
1878 }
1879 mNextAlarmClockForUser.remove(userId);
1880 }
1881
1882 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
1883 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1884 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
1885 }
1886
1887 /**
1888 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
1889 * for which alarm clocks have changed since the last call to this.
1890 *
1891 * Do not call with a lock held. Only call from mHandler's thread.
1892 *
1893 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
1894 */
1895 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07001896 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001897 pendingUsers.clear();
1898
1899 synchronized (mLock) {
1900 final int N = mPendingSendNextAlarmClockChangedForUser.size();
1901 for (int i = 0; i < N; i++) {
1902 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
1903 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
1904 }
1905 mPendingSendNextAlarmClockChangedForUser.clear();
1906 }
1907
1908 final int N = pendingUsers.size();
1909 for (int i = 0; i < N; i++) {
1910 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07001911 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001912 Settings.System.putStringForUser(getContext().getContentResolver(),
1913 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01001914 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02001915 userId);
1916
1917 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
1918 new UserHandle(userId));
1919 }
1920 }
1921
1922 /**
1923 * Formats an alarm like platform/packages/apps/DeskClock used to.
1924 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01001925 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
1926 int userId) {
1927 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02001928 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
1929 return (info == null) ? "" :
1930 DateFormat.format(pattern, info.getTriggerTime()).toString();
1931 }
1932
Adam Lesinski182f73f2013-12-05 16:48:06 -08001933 void rescheduleKernelAlarmsLocked() {
1934 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
1935 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001936 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001937 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001938 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001939 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07001940 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001941 mNextWakeup = firstWakeup.start;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001942 mLastWakeupSet = SystemClock.elapsedRealtime();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001943 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001944 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001945 if (firstBatch != firstWakeup) {
1946 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001947 }
1948 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001949 if (mPendingNonWakeupAlarms.size() > 0) {
1950 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
1951 nextNonWakeup = mNextNonWakeupDeliveryTime;
1952 }
1953 }
Prashant Malani753e9e02015-06-10 17:43:49 -07001954 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001955 mNextNonWakeup = nextNonWakeup;
1956 setLocked(ELAPSED_REALTIME, nextNonWakeup);
1957 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001958 }
1959
Christopher Tate14a7bb02015-10-01 10:24:31 -07001960 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001961 boolean didRemove = false;
1962 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1963 Batch b = mAlarmBatches.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -07001964 didRemove |= b.remove(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001965 if (b.size() == 0) {
1966 mAlarmBatches.remove(i);
1967 }
1968 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001969 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001970 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001971 // Don't set didRemove, since this doesn't impact the scheduled alarms.
1972 mPendingWhileIdleAlarms.remove(i);
1973 }
1974 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001975
1976 if (didRemove) {
1977 if (DEBUG_BATCH) {
1978 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
1979 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001980 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001981 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001982 mPendingIdleUntil = null;
1983 restorePending = true;
1984 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001985 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001986 mNextWakeFromIdle = null;
1987 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001988 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001989 if (restorePending) {
1990 restorePendingWhileIdleAlarmsLocked();
1991 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001992 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001993 }
1994 }
1995
1996 void removeLocked(String packageName) {
1997 boolean didRemove = false;
1998 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
1999 Batch b = mAlarmBatches.get(i);
2000 didRemove |= b.remove(packageName);
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 final Alarm a = mPendingWhileIdleAlarms.get(i);
2007 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002008 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2009 mPendingWhileIdleAlarms.remove(i);
2010 }
2011 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002012
2013 if (didRemove) {
2014 if (DEBUG_BATCH) {
2015 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2016 }
2017 rebatchAllAlarmsLocked(true);
2018 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002019 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002020 }
2021 }
2022
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002023 void removeForStoppedLocked(int uid) {
2024 boolean didRemove = false;
2025 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2026 Batch b = mAlarmBatches.get(i);
2027 didRemove |= b.removeForStopped(uid);
2028 if (b.size() == 0) {
2029 mAlarmBatches.remove(i);
2030 }
2031 }
2032 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2033 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08002034 if (a.uid == uid) {
2035 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2036 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002037 }
2038 }
2039
2040 if (didRemove) {
2041 if (DEBUG_BATCH) {
2042 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2043 }
2044 rebatchAllAlarmsLocked(true);
2045 rescheduleKernelAlarmsLocked();
2046 updateNextAlarmClockLocked();
2047 }
2048 }
2049
Adam Lesinski182f73f2013-12-05 16:48:06 -08002050 void removeUserLocked(int userHandle) {
2051 boolean didRemove = false;
2052 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2053 Batch b = mAlarmBatches.get(i);
2054 didRemove |= b.remove(userHandle);
2055 if (b.size() == 0) {
2056 mAlarmBatches.remove(i);
2057 }
2058 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002059 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002060 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002061 == userHandle) {
2062 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2063 mPendingWhileIdleAlarms.remove(i);
2064 }
2065 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002066 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
2067 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
2068 mLastAllowWhileIdleDispatch.removeAt(i);
2069 }
2070 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002071
2072 if (didRemove) {
2073 if (DEBUG_BATCH) {
2074 Slog.v(TAG, "remove(user) changed bounds; rebatching");
2075 }
2076 rebatchAllAlarmsLocked(true);
2077 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002078 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002079 }
2080 }
2081
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002082 void interactiveStateChangedLocked(boolean interactive) {
2083 if (mInteractive != interactive) {
2084 mInteractive = interactive;
2085 final long nowELAPSED = SystemClock.elapsedRealtime();
2086 if (interactive) {
2087 if (mPendingNonWakeupAlarms.size() > 0) {
2088 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2089 mTotalDelayTime += thisDelayTime;
2090 if (mMaxDelayTime < thisDelayTime) {
2091 mMaxDelayTime = thisDelayTime;
2092 }
2093 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2094 mPendingNonWakeupAlarms.clear();
2095 }
2096 if (mNonInteractiveStartTime > 0) {
2097 long dur = nowELAPSED - mNonInteractiveStartTime;
2098 if (dur > mNonInteractiveTime) {
2099 mNonInteractiveTime = dur;
2100 }
2101 }
2102 } else {
2103 mNonInteractiveStartTime = nowELAPSED;
2104 }
2105 }
2106 }
2107
Adam Lesinski182f73f2013-12-05 16:48:06 -08002108 boolean lookForPackageLocked(String packageName) {
2109 for (int i = 0; i < mAlarmBatches.size(); i++) {
2110 Batch b = mAlarmBatches.get(i);
2111 if (b.hasPackage(packageName)) {
2112 return true;
2113 }
2114 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002115 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002116 final Alarm a = mPendingWhileIdleAlarms.get(i);
2117 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002118 return true;
2119 }
2120 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002121 return false;
2122 }
2123
2124 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002125 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002126 // The kernel never triggers alarms with negative wakeup times
2127 // so we ensure they are positive.
2128 long alarmSeconds, alarmNanoseconds;
2129 if (when < 0) {
2130 alarmSeconds = 0;
2131 alarmNanoseconds = 0;
2132 } else {
2133 alarmSeconds = when / 1000;
2134 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2135 }
2136
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002137 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002138 } else {
2139 Message msg = Message.obtain();
2140 msg.what = ALARM_EVENT;
2141
2142 mHandler.removeMessages(ALARM_EVENT);
2143 mHandler.sendMessageAtTime(msg, when);
2144 }
2145 }
2146
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002147 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002148 String prefix, String label, long nowRTC, long nowELAPSED, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002149 for (int i=list.size()-1; i>=0; i--) {
2150 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002151 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2152 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002153 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002154 }
2155 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002156
2157 private static final String labelForType(int type) {
2158 switch (type) {
2159 case RTC: return "RTC";
2160 case RTC_WAKEUP : return "RTC_WAKEUP";
2161 case ELAPSED_REALTIME : return "ELAPSED";
2162 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
2163 default:
2164 break;
2165 }
2166 return "--unknown--";
2167 }
2168
2169 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002170 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002171 for (int i=list.size()-1; i>=0; i--) {
2172 Alarm a = list.get(i);
2173 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002174 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2175 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002176 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002177 }
2178 }
2179
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002180 private native long init();
2181 private native void close(long nativeData);
2182 private native void set(long nativeData, int type, long seconds, long nanoseconds);
2183 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08002184 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002185 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002186
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002187 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002188 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002189 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002190 // batches are temporally sorted, so we need only pull from the
2191 // start of the list until we either empty it or hit a batch
2192 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07002193 while (mAlarmBatches.size() > 0) {
2194 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002195 if (batch.start > nowELAPSED) {
2196 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002197 break;
2198 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002199
Christopher Tatee0a22b32013-07-11 14:43:13 -07002200 // We will (re)schedule some alarms now; don't let that interfere
2201 // with delivery of this current batch
2202 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002203
Christopher Tatee0a22b32013-07-11 14:43:13 -07002204 final int N = batch.size();
2205 for (int i = 0; i < N; i++) {
2206 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002207
2208 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
2209 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
2210 // schedule such alarms.
2211 long lastTime = mLastAllowWhileIdleDispatch.get(alarm.uid, 0);
2212 long minTime = lastTime + mAllowWhileIdleMinTime;
2213 if (nowELAPSED < minTime) {
2214 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
2215 // alarm went off for this app. Reschedule the alarm to be in the
2216 // correct time period.
2217 alarm.whenElapsed = minTime;
2218 if (alarm.maxWhenElapsed < minTime) {
2219 alarm.maxWhenElapsed = minTime;
2220 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002221 if (RECORD_DEVICE_IDLE_ALARMS) {
2222 IdleDispatchEntry ent = new IdleDispatchEntry();
2223 ent.uid = alarm.uid;
2224 ent.pkg = alarm.operation.getCreatorPackage();
2225 ent.tag = alarm.operation.getTag("");
2226 ent.op = "RESCHEDULE";
2227 ent.elapsedRealtime = nowELAPSED;
2228 ent.argRealtime = lastTime;
2229 mAllowWhileIdleDispatches.add(ent);
2230 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002231 setImplLocked(alarm, true, false);
2232 continue;
2233 }
2234 }
2235
Christopher Tatee0a22b32013-07-11 14:43:13 -07002236 alarm.count = 1;
2237 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002238 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
2239 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002240 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002241 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002242 if (mPendingIdleUntil == alarm) {
2243 mPendingIdleUntil = null;
2244 rebatchAllAlarmsLocked(false);
2245 restorePendingWhileIdleAlarmsLocked();
2246 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002247 if (mNextWakeFromIdle == alarm) {
2248 mNextWakeFromIdle = null;
2249 rebatchAllAlarmsLocked(false);
2250 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002251
2252 // Recurring alarms may have passed several alarm intervals while the
2253 // phone was asleep or off, so pass a trigger count when sending them.
2254 if (alarm.repeatInterval > 0) {
2255 // this adjustment will be zero if we're late by
2256 // less than one full repeat interval
2257 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
2258
2259 // Also schedule its next recurrence
2260 final long delta = alarm.count * alarm.repeatInterval;
2261 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07002262 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07002263 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07002264 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
2265 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08002266 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002267
Christopher Tate864d42e2014-12-02 11:48:53 -08002268 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002269 hasWakeup = true;
2270 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002271
2272 // We removed an alarm clock. Let the caller recompute the next alarm clock.
2273 if (alarm.alarmClock != null) {
2274 mNextAlarmClockMayChange = true;
2275 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07002276 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002277 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002278
Christopher Tate1590f1e2014-10-02 17:27:57 -07002279 // This is a new alarm delivery set; bump the sequence number to indicate that
2280 // all apps' alarm delivery classes should be recalculated.
2281 mCurrentSeq++;
2282 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002283 Collections.sort(triggerList, mAlarmDispatchComparator);
2284
2285 if (localLOGV) {
2286 for (int i=0; i<triggerList.size(); i++) {
2287 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
2288 }
2289 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002290
2291 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002292 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002294 /**
2295 * This Comparator sorts Alarms into increasing time order.
2296 */
2297 public static class IncreasingTimeOrder implements Comparator<Alarm> {
2298 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09002299 long when1 = a1.whenElapsed;
2300 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002301 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002302 return 1;
2303 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002304 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002305 return -1;
2306 }
2307 return 0;
2308 }
2309 }
2310
2311 private static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002312 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002313 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002314 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002315 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002316 public final IAlarmListener listener;
2317 public final String listenerTag;
2318 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002319 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002320 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002321 public final AlarmManager.AlarmClockInfo alarmClock;
2322 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002323 public final int creatorUid;
2324 public final String packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002325 public int count;
2326 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07002327 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002328 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002329 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002330 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07002331 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002332
Christopher Tate3e04b472013-10-21 17:51:31 -07002333 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002334 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
2335 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
2336 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002337 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002338 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002339 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
2340 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002341 when = _when;
2342 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07002343 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002344 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002345 repeatInterval = _interval;
2346 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002347 listener = _rec;
2348 listenerTag = _listenerTag;
2349 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07002350 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002351 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002352 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002353 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002354 packageName = _pkgName;
2355
2356 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002357 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002358
Christopher Tate14a7bb02015-10-01 10:24:31 -07002359 public static String makeTag(PendingIntent pi, String tag, int type) {
2360 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
2361 ? "*walarm*:" : "*alarm*:";
2362 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
2363 }
2364
2365 public WakeupEvent makeWakeupEvent(long nowRTC) {
2366 return new WakeupEvent(nowRTC, creatorUid,
2367 (operation != null)
2368 ? operation.getIntent().getAction()
2369 : ("<listener>:" + listenerTag));
2370 }
2371
2372 // Returns true if either matches
2373 public boolean matches(PendingIntent pi, IAlarmListener rec) {
2374 return (operation != null)
2375 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09002376 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07002377 }
2378
2379 public boolean matches(String packageName) {
2380 return (operation != null)
2381 ? packageName.equals(operation.getTargetPackage())
2382 : packageName.equals(this.packageName);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002383 }
2384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002385 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002386 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002387 StringBuilder sb = new StringBuilder(128);
2388 sb.append("Alarm{");
2389 sb.append(Integer.toHexString(System.identityHashCode(this)));
2390 sb.append(" type ");
2391 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002392 sb.append(" when ");
2393 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002394 sb.append(" ");
Christopher Tate14a7bb02015-10-01 10:24:31 -07002395 if (operation != null) {
2396 sb.append(operation.getTargetPackage());
2397 } else {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002398 sb.append(packageName);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002399 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002400 sb.append('}');
2401 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002402 }
2403
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002404 public void dump(PrintWriter pw, String prefix, long nowRTC, long nowELAPSED,
2405 SimpleDateFormat sdf) {
2406 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002407 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002408 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002409 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
2410 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002411 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002412 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002413 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002414 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002415 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002416 }
2417 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002418 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002419 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002420 pw.print(" count="); pw.print(count);
2421 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002422 if (alarmClock != null) {
2423 pw.print(prefix); pw.println("Alarm clock:");
2424 pw.print(prefix); pw.print(" triggerTime=");
2425 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
2426 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
2427 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002428 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002429 if (listener != null) {
2430 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
2431 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 }
2433 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002434
Christopher Tatee0a22b32013-07-11 14:43:13 -07002435 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
2436 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002437 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
2438 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002439 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07002440 break;
2441 }
2442
Christopher Tatee0a22b32013-07-11 14:43:13 -07002443 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002444 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
2445 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002446 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07002447 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002448 }
2449 }
2450
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002451 long currentNonWakeupFuzzLocked(long nowELAPSED) {
2452 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
2453 if (timeSinceOn < 5*60*1000) {
2454 // If the screen has been off for 5 minutes, only delay by at most two minutes.
2455 return 2*60*1000;
2456 } else if (timeSinceOn < 30*60*1000) {
2457 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
2458 return 15*60*1000;
2459 } else {
2460 // Otherwise, we will delay by at most an hour.
2461 return 60*60*1000;
2462 }
2463 }
2464
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002465 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002466 if (duration < 15*60*1000) {
2467 // If the duration until the time is less than 15 minutes, the maximum fuzz
2468 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002469 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002470 } else if (duration < 90*60*1000) {
2471 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
2472 return 15*60*1000;
2473 } else {
2474 // Otherwise, we will fuzz by at most half an hour.
2475 return 30*60*1000;
2476 }
2477 }
2478
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002479 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
2480 if (mInteractive) {
2481 return false;
2482 }
2483 if (mLastAlarmDeliveryTime <= 0) {
2484 return false;
2485 }
minho.choo649acab2014-12-12 16:13:55 +09002486 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002487 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
2488 // and the next delivery time is in the past, then just deliver them all. This
2489 // avoids bugs where we get stuck in a loop trying to poll for alarms.
2490 return false;
2491 }
2492 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
2493 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
2494 }
2495
2496 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
2497 mLastAlarmDeliveryTime = nowELAPSED;
2498 for (int i=0; i<triggerList.size(); i++) {
2499 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07002500 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002501 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07002502 if (localLOGV) {
2503 Slog.v(TAG, "sending alarm " + alarm);
2504 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07002505 if (RECORD_ALARMS_IN_HISTORY) {
2506 if (alarm.workSource != null && alarm.workSource.size() > 0) {
2507 for (int wi=0; wi<alarm.workSource.size(); wi++) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002508 ActivityManager.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002509 alarm.operation, alarm.workSource.get(wi), alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002510 }
2511 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002512 ActivityManager.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002513 alarm.operation, alarm.uid, alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002514 }
2515 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002516 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002517 } catch (RuntimeException e) {
2518 Slog.w(TAG, "Failure sending alarm.", e);
2519 }
2520 }
2521 }
2522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 private class AlarmThread extends Thread
2524 {
2525 public AlarmThread()
2526 {
2527 super("AlarmManager");
2528 }
2529
2530 public void run()
2531 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002532 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 while (true)
2535 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002536 int result = waitForAlarm(mNativeData);
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002537 mLastWakeup = SystemClock.elapsedRealtime();
Dianne Hackborn390517b2013-05-30 15:03:32 -07002538
2539 triggerList.clear();
2540
Dianne Hackbornc3527222015-05-13 14:03:20 -07002541 final long nowRTC = System.currentTimeMillis();
2542 final long nowELAPSED = SystemClock.elapsedRealtime();
2543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002545 // The kernel can give us spurious time change notifications due to
2546 // small adjustments it makes internally; we want to filter those out.
2547 final long lastTimeChangeClockTime;
2548 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07002549 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002550 lastTimeChangeClockTime = mLastTimeChangeClockTime;
2551 expectedClockTime = lastTimeChangeClockTime
2552 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07002553 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08002554 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
2555 || nowRTC > (expectedClockTime+1000)) {
2556 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07002557 // let's do it!
2558 if (DEBUG_BATCH) {
2559 Slog.v(TAG, "Time changed notification from kernel; rebatching");
2560 }
2561 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07002562 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07002563 rebatchAllAlarms();
2564 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07002565 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07002566 synchronized (mLock) {
2567 mNumTimeChanged++;
2568 mLastTimeChangeClockTime = nowRTC;
2569 mLastTimeChangeRealtime = nowELAPSED;
2570 }
2571 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
2572 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08002573 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07002574 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
2575 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07002576 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
2577
2578 // The world has changed on us, so we need to re-evaluate alarms
2579 // regardless of whether the kernel has told us one went off.
2580 result |= IS_WAKEUP_MASK;
2581 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002583
Dianne Hackbornc3527222015-05-13 14:03:20 -07002584 if (result != TIME_CHANGED_MASK) {
2585 // If this was anything besides just a time change, then figure what if
2586 // anything to do about alarms.
2587 synchronized (mLock) {
2588 if (localLOGV) Slog.v(
2589 TAG, "Checking for alarms... rtc=" + nowRTC
2590 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07002591
Dianne Hackbornc3527222015-05-13 14:03:20 -07002592 if (WAKEUP_STATS) {
2593 if ((result & IS_WAKEUP_MASK) != 0) {
2594 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
2595 int n = 0;
2596 for (WakeupEvent event : mRecentWakeups) {
2597 if (event.when > newEarliest) break;
2598 n++; // number of now-stale entries at the list head
2599 }
2600 for (int i = 0; i < n; i++) {
2601 mRecentWakeups.remove();
2602 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002603
Dianne Hackbornc3527222015-05-13 14:03:20 -07002604 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002605 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002606 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002607
2608 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2609 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
2610 // if there are no wakeup alarms and the screen is off, we can
2611 // delay what we have so far until the future.
2612 if (mPendingNonWakeupAlarms.size() == 0) {
2613 mStartCurrentDelayTime = nowELAPSED;
2614 mNextNonWakeupDeliveryTime = nowELAPSED
2615 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
2616 }
2617 mPendingNonWakeupAlarms.addAll(triggerList);
2618 mNumDelayedAlarms += triggerList.size();
2619 rescheduleKernelAlarmsLocked();
2620 updateNextAlarmClockLocked();
2621 } else {
2622 // now deliver the alarm intents; if there are pending non-wakeup
2623 // alarms, we need to merge them in to the list. note we don't
2624 // just deliver them first because we generally want non-wakeup
2625 // alarms delivered after wakeup alarms.
2626 rescheduleKernelAlarmsLocked();
2627 updateNextAlarmClockLocked();
2628 if (mPendingNonWakeupAlarms.size() > 0) {
2629 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
2630 triggerList.addAll(mPendingNonWakeupAlarms);
2631 Collections.sort(triggerList, mAlarmDispatchComparator);
2632 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2633 mTotalDelayTime += thisDelayTime;
2634 if (mMaxDelayTime < thisDelayTime) {
2635 mMaxDelayTime = thisDelayTime;
2636 }
2637 mPendingNonWakeupAlarms.clear();
2638 }
2639 deliverAlarmsLocked(triggerList, nowELAPSED);
2640 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002641 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002642
2643 } else {
2644 // Just in case -- even though no wakeup flag was set, make sure
2645 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07002646 synchronized (mLock) {
2647 rescheduleKernelAlarmsLocked();
2648 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002649 }
2650 }
2651 }
2652 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002653
David Christieebe51fc2013-07-26 13:23:29 -07002654 /**
2655 * Attribute blame for a WakeLock.
2656 * @param pi PendingIntent to attribute blame to if ws is null.
2657 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002658 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07002659 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002660 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002661 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07002662 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002663 final boolean unimportant = pi == mTimeTickSender;
2664 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002665 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002666 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002667 } else {
2668 mWakeLock.setHistoryTag(null);
2669 }
2670 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07002671 if (ws != null) {
2672 mWakeLock.setWorkSource(ws);
2673 return;
2674 }
2675
Christopher Tate14a7bb02015-10-01 10:24:31 -07002676 final int uid = (knownUid >= 0)
2677 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002678 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07002679 if (uid >= 0) {
2680 mWakeLock.setWorkSource(new WorkSource(uid));
2681 return;
2682 }
2683 } catch (Exception e) {
2684 }
2685
2686 // Something went wrong; fall back to attributing the lock to the OS
2687 mWakeLock.setWorkSource(null);
2688 }
2689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002690 private class AlarmHandler extends Handler {
2691 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002692 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
2693 public static final int LISTENER_TIMEOUT = 3;
2694 public static final int REPORT_ALARMS_ACTIVE = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002695
2696 public AlarmHandler() {
2697 }
2698
2699 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002700 switch (msg.what) {
2701 case ALARM_EVENT: {
2702 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2703 synchronized (mLock) {
2704 final long nowRTC = System.currentTimeMillis();
2705 final long nowELAPSED = SystemClock.elapsedRealtime();
2706 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2707 updateNextAlarmClockLocked();
2708 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002709
Christopher Tate14a7bb02015-10-01 10:24:31 -07002710 // now trigger the alarms without the lock held
2711 for (int i=0; i<triggerList.size(); i++) {
2712 Alarm alarm = triggerList.get(i);
2713 try {
2714 alarm.operation.send();
2715 } catch (PendingIntent.CanceledException e) {
2716 if (alarm.repeatInterval > 0) {
2717 // This IntentSender is no longer valid, but this
2718 // is a repeating alarm, so toss the hoser.
2719 removeImpl(alarm.operation);
2720 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002721 }
2722 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002723 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002724 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002725
2726 case SEND_NEXT_ALARM_CLOCK_CHANGED:
2727 sendNextAlarmClockChanged();
2728 break;
2729
2730 case LISTENER_TIMEOUT:
2731 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
2732 break;
2733
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002734 case REPORT_ALARMS_ACTIVE:
2735 if (mLocalDeviceIdleController != null) {
2736 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
2737 }
2738 break;
2739
Christopher Tate14a7bb02015-10-01 10:24:31 -07002740 default:
2741 // nope, just ignore it
2742 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002743 }
2744 }
2745 }
2746
2747 class ClockReceiver extends BroadcastReceiver {
2748 public ClockReceiver() {
2749 IntentFilter filter = new IntentFilter();
2750 filter.addAction(Intent.ACTION_TIME_TICK);
2751 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002752 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002753 }
2754
2755 @Override
2756 public void onReceive(Context context, Intent intent) {
2757 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07002758 if (DEBUG_BATCH) {
2759 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
2760 }
2761 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002762 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
2763 // Since the kernel does not keep track of DST, we need to
2764 // reset the TZ information at the beginning of each day
2765 // based off of the current Zone gmt offset + userspace tracked
2766 // daylight savings information.
2767 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02002768 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002769 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07002770 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002771 }
2772 }
2773
2774 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07002775 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09002776 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07002777
2778 // Schedule this event for the amount of time that it would take to get to
2779 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09002780 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07002781
David Christieebe51fc2013-07-26 13:23:29 -07002782 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08002783 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002784 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
2785 null, Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002786 }
Christopher Tate385e4982013-07-23 18:22:29 -07002787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002788 public void scheduleDateChangedEvent() {
2789 Calendar calendar = Calendar.getInstance();
2790 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07002791 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002792 calendar.set(Calendar.MINUTE, 0);
2793 calendar.set(Calendar.SECOND, 0);
2794 calendar.set(Calendar.MILLISECOND, 0);
2795 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07002796
2797 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002798 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
2799 AlarmManager.FLAG_STANDALONE, workSource, null,
2800 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002801 }
2802 }
2803
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002804 class InteractiveStateReceiver extends BroadcastReceiver {
2805 public InteractiveStateReceiver() {
2806 IntentFilter filter = new IntentFilter();
2807 filter.addAction(Intent.ACTION_SCREEN_OFF);
2808 filter.addAction(Intent.ACTION_SCREEN_ON);
2809 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
2810 getContext().registerReceiver(this, filter);
2811 }
2812
2813 @Override
2814 public void onReceive(Context context, Intent intent) {
2815 synchronized (mLock) {
2816 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
2817 }
2818 }
2819 }
2820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002821 class UninstallReceiver extends BroadcastReceiver {
2822 public UninstallReceiver() {
2823 IntentFilter filter = new IntentFilter();
2824 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2825 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002826 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002827 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08002828 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002829 // Register for events related to sdcard installation.
2830 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08002831 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002832 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002833 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002834 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 }
2836
2837 @Override
2838 public void onReceive(Context context, Intent intent) {
2839 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002840 String action = intent.getAction();
2841 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002842 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
2843 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
2844 for (String packageName : pkgList) {
2845 if (lookForPackageLocked(packageName)) {
2846 setResultCode(Activity.RESULT_OK);
2847 return;
2848 }
2849 }
2850 return;
2851 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002852 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002853 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
2854 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
2855 if (userHandle >= 0) {
2856 removeUserLocked(userHandle);
2857 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002858 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
2859 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
2860 if (uid >= 0) {
2861 mLastAllowWhileIdleDispatch.delete(uid);
2862 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002863 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08002864 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
2865 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
2866 // This package is being updated; don't kill its alarms.
2867 return;
2868 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002869 Uri data = intent.getData();
2870 if (data != null) {
2871 String pkg = data.getSchemeSpecificPart();
2872 if (pkg != null) {
2873 pkgList = new String[]{pkg};
2874 }
2875 }
2876 }
2877 if (pkgList != null && (pkgList.length > 0)) {
2878 for (String pkg : pkgList) {
2879 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07002880 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002881 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
2882 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
2883 if (uidStats.remove(pkg) != null) {
2884 if (uidStats.size() <= 0) {
2885 mBroadcastStats.removeAt(i);
2886 }
2887 }
2888 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002889 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002890 }
2891 }
2892 }
2893 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002894
2895 final class UidObserver extends IUidObserver.Stub {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07002896 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002897 }
2898
Dianne Hackborn3e99f652017-07-05 16:33:56 -07002899 @Override public void onUidGone(int uid, boolean disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -08002900 if (disabled) {
2901 synchronized (mLock) {
2902 removeForStoppedLocked(uid);
2903 }
2904 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002905 }
2906
Dianne Hackborn3e99f652017-07-05 16:33:56 -07002907 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002908 }
2909
Dianne Hackborn3e99f652017-07-05 16:33:56 -07002910 @Override public void onUidIdle(int uid, boolean disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -08002911 if (disabled) {
2912 synchronized (mLock) {
2913 removeForStoppedLocked(uid);
2914 }
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08002915 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002916 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -07002917
2918 @Override public void onUidCachedChanged(int uid, boolean cached) {
2919 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002920 };
2921
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002922 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002923 String pkg = pi.getCreatorPackage();
2924 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002925 return getStatsLocked(uid, pkg);
2926 }
2927
2928 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002929 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
2930 if (uidStats == null) {
2931 uidStats = new ArrayMap<String, BroadcastStats>();
2932 mBroadcastStats.put(uid, uidStats);
2933 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002934 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002935 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002936 bs = new BroadcastStats(uid, pkgName);
2937 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002938 }
2939 return bs;
2940 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002941
Christopher Tate14a7bb02015-10-01 10:24:31 -07002942 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
2943 private InFlight removeLocked(PendingIntent pi, Intent intent) {
2944 for (int i = 0; i < mInFlight.size(); i++) {
2945 if (mInFlight.get(i).mPendingIntent == pi) {
2946 return mInFlight.remove(i);
2947 }
2948 }
2949 mLog.w("No in-flight alarm for " + pi + " " + intent);
2950 return null;
2951 }
2952
2953 private InFlight removeLocked(IBinder listener) {
2954 for (int i = 0; i < mInFlight.size(); i++) {
2955 if (mInFlight.get(i).mListener == listener) {
2956 return mInFlight.remove(i);
2957 }
2958 }
2959 mLog.w("No in-flight alarm for listener " + listener);
2960 return null;
2961 }
2962
2963 private void updateStatsLocked(InFlight inflight) {
2964 final long nowELAPSED = SystemClock.elapsedRealtime();
2965 BroadcastStats bs = inflight.mBroadcastStats;
2966 bs.nesting--;
2967 if (bs.nesting <= 0) {
2968 bs.nesting = 0;
2969 bs.aggregateTime += nowELAPSED - bs.startTime;
2970 }
2971 FilterStats fs = inflight.mFilterStats;
2972 fs.nesting--;
2973 if (fs.nesting <= 0) {
2974 fs.nesting = 0;
2975 fs.aggregateTime += nowELAPSED - fs.startTime;
2976 }
2977 if (RECORD_ALARMS_IN_HISTORY) {
2978 if (inflight.mWorkSource != null && inflight.mWorkSource.size() > 0) {
2979 for (int wi=0; wi<inflight.mWorkSource.size(); wi++) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002980 ActivityManager.noteAlarmFinish(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002981 inflight.mPendingIntent, inflight.mWorkSource.get(wi), inflight.mTag);
2982 }
2983 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002984 ActivityManager.noteAlarmFinish(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002985 inflight.mPendingIntent, inflight.mUid, inflight.mTag);
2986 }
2987 }
2988 }
2989
2990 private void updateTrackingLocked(InFlight inflight) {
2991 if (inflight != null) {
2992 updateStatsLocked(inflight);
2993 }
2994 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08002995 if (DEBUG_WAKELOCK) {
2996 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
2997 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002998 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002999 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003000 mWakeLock.release();
3001 if (mInFlight.size() > 0) {
3002 mLog.w("Finished all dispatches with " + mInFlight.size()
3003 + " remaining inflights");
3004 for (int i=0; i<mInFlight.size(); i++) {
3005 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
3006 }
3007 mInFlight.clear();
3008 }
3009 } else {
3010 // the next of our alarms is now in flight. reattribute the wakelock.
3011 if (mInFlight.size() > 0) {
3012 InFlight inFlight = mInFlight.get(0);
3013 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
3014 inFlight.mAlarmType, inFlight.mTag, -1, false);
3015 } else {
3016 // should never happen
3017 mLog.w("Alarm wakelock still held but sent queue empty");
3018 mWakeLock.setWorkSource(null);
3019 }
3020 }
3021 }
3022
3023 /**
3024 * Callback that arrives when a direct-call alarm reports that delivery has finished
3025 */
3026 @Override
3027 public void alarmComplete(IBinder who) {
3028 if (who == null) {
3029 Slog.w(TAG, "Invalid alarmComplete: uid=" + Binder.getCallingUid()
3030 + " pid=" + Binder.getCallingPid());
3031 return;
3032 }
3033
3034 final long ident = Binder.clearCallingIdentity();
3035 try {
3036 synchronized (mLock) {
3037 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
3038 InFlight inflight = removeLocked(who);
3039 if (inflight != null) {
3040 if (DEBUG_LISTENER_CALLBACK) {
3041 Slog.i(TAG, "alarmComplete() from " + who);
3042 }
3043 updateTrackingLocked(inflight);
3044 } else {
3045 // Delivery timed out, and the timeout handling already took care of
3046 // updating our tracking here, so we needn't do anything further.
3047 if (DEBUG_LISTENER_CALLBACK) {
3048 Slog.i(TAG, "Late alarmComplete() from " + who);
3049 }
3050 }
3051 }
3052 } finally {
3053 Binder.restoreCallingIdentity(ident);
3054 }
3055 }
3056
3057 /**
3058 * Callback that arrives when a PendingIntent alarm has finished delivery
3059 */
3060 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003061 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
3062 String resultData, Bundle resultExtras) {
3063 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003064 updateTrackingLocked(removeLocked(pi, intent));
3065 }
3066 }
3067
3068 /**
3069 * Timeout of a direct-call alarm delivery
3070 */
3071 public void alarmTimedOut(IBinder who) {
3072 synchronized (mLock) {
3073 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08003074 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003075 // TODO: implement ANR policy for the target
3076 if (DEBUG_LISTENER_CALLBACK) {
3077 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003078 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003079 updateTrackingLocked(inflight);
Dianne Hackborn81038902012-11-26 17:04:09 -08003080 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003081 if (DEBUG_LISTENER_CALLBACK) {
3082 Slog.i(TAG, "Spurious timeout of listener " + who);
3083 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003084 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003085 }
3086 }
3087
3088 /**
3089 * Deliver an alarm and set up the post-delivery handling appropriately
3090 */
3091 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
3092 if (alarm.operation != null) {
3093 // PendingIntent alarm
3094 try {
3095 alarm.operation.send(getContext(), 0,
3096 mBackgroundIntent.putExtra(
3097 Intent.EXTRA_ALARM_COUNT, alarm.count),
3098 mDeliveryTracker, mHandler, null,
3099 allowWhileIdle ? mIdleOptions : null);
3100 } catch (PendingIntent.CanceledException e) {
3101 if (alarm.repeatInterval > 0) {
3102 // This IntentSender is no longer valid, but this
3103 // is a repeating alarm, so toss it
3104 removeImpl(alarm.operation);
3105 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003106 // No actual delivery was possible, so the delivery tracker's
3107 // 'finished' callback won't be invoked. We also don't need
3108 // to do any wakelock or stats tracking, so we have nothing
3109 // left to do here but go on to the next thing.
3110 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003111 }
3112 } else {
3113 // Direct listener callback alarm
3114 try {
3115 if (DEBUG_LISTENER_CALLBACK) {
3116 Slog.v(TAG, "Alarm to uid=" + alarm.uid
3117 + " listener=" + alarm.listener.asBinder());
3118 }
3119 alarm.listener.doAlarm(this);
3120 mHandler.sendMessageDelayed(
3121 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
3122 alarm.listener.asBinder()),
3123 mConstants.LISTENER_TIMEOUT);
3124 } catch (Exception e) {
3125 if (DEBUG_LISTENER_CALLBACK) {
3126 Slog.i(TAG, "Alarm undeliverable to listener "
3127 + alarm.listener.asBinder(), e);
3128 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003129 // As in the PendingIntent.CanceledException case, delivery of the
3130 // alarm was not possible, so we have no wakelock or timeout or
3131 // stats management to do. It threw before we posted the delayed
3132 // timeout message, so we're done here.
3133 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003134 }
3135 }
3136
3137 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08003138 if (DEBUG_WAKELOCK) {
3139 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
3140 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003141 if (mBroadcastRefCount == 0) {
3142 setWakelockWorkSource(alarm.operation, alarm.workSource,
3143 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
3144 true);
3145 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003146 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003147 }
3148 final InFlight inflight = new InFlight(AlarmManagerService.this,
3149 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
3150 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
3151 mInFlight.add(inflight);
3152 mBroadcastRefCount++;
3153
3154 if (allowWhileIdle) {
3155 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
3156 mLastAllowWhileIdleDispatch.put(alarm.uid, nowELAPSED);
3157 if (RECORD_DEVICE_IDLE_ALARMS) {
3158 IdleDispatchEntry ent = new IdleDispatchEntry();
3159 ent.uid = alarm.uid;
3160 ent.pkg = alarm.packageName;
3161 ent.tag = alarm.statsTag;
3162 ent.op = "DELIVER";
3163 ent.elapsedRealtime = nowELAPSED;
3164 mAllowWhileIdleDispatches.add(ent);
3165 }
3166 }
3167
3168 final BroadcastStats bs = inflight.mBroadcastStats;
3169 bs.count++;
3170 if (bs.nesting == 0) {
3171 bs.nesting = 1;
3172 bs.startTime = nowELAPSED;
3173 } else {
3174 bs.nesting++;
3175 }
3176 final FilterStats fs = inflight.mFilterStats;
3177 fs.count++;
3178 if (fs.nesting == 0) {
3179 fs.nesting = 1;
3180 fs.startTime = nowELAPSED;
3181 } else {
3182 fs.nesting++;
3183 }
3184 if (alarm.type == ELAPSED_REALTIME_WAKEUP
3185 || alarm.type == RTC_WAKEUP) {
3186 bs.numWakeup++;
3187 fs.numWakeup++;
3188 if (alarm.workSource != null && alarm.workSource.size() > 0) {
3189 for (int wi=0; wi<alarm.workSource.size(); wi++) {
Christopher Tate0029f572016-06-14 10:16:28 -07003190 final String wsName = alarm.workSource.getName(wi);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003191 ActivityManager.noteWakeupAlarm(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003192 alarm.operation, alarm.workSource.get(wi),
Christopher Tate0029f572016-06-14 10:16:28 -07003193 (wsName != null) ? wsName : alarm.packageName,
3194 alarm.statsTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08003195 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003196 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003197 ActivityManager.noteWakeupAlarm(
Joe Onorato78bcdf92016-05-09 10:10:29 -07003198 alarm.operation, alarm.uid, alarm.packageName, alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003199 }
3200 }
3201 }
3202 }
3203}