blob: 342b48ee7f7227040d8599ff5ff25e1705abaf0a [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.pm.PackageManager;
Christopher Tatebb9cce52017-04-18 14:19:43 -070036import android.content.pm.PackageManager.NameNotFoundException;
37import android.content.pm.PermissionInfo;
Dianne Hackborna750a632015-06-16 17:18:23 -070038import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.net.Uri;
40import android.os.Binder;
41import android.os.Bundle;
Christopher Tate247571462017-04-10 11:45:05 -070042import android.os.Environment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.os.Handler;
Adam Lesinski182f73f2013-12-05 16:48:06 -080044import android.os.IBinder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.os.Message;
46import android.os.PowerManager;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070047import android.os.Process;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070048import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.os.SystemClock;
50import android.os.SystemProperties;
Tim Murray175c0f92017-11-28 15:01:04 -080051import android.os.Trace;
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;
Kweku Adams61e03292017-10-19 14:27:12 -070065import android.util.proto.ProtoOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066
Christopher Tate4cb338d2013-07-26 13:11:31 -070067import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import java.io.FileDescriptor;
69import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070070import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -080072import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import java.util.Calendar;
74import java.util.Collections;
75import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -050076import java.util.Date;
Christopher Tate1590f1e2014-10-02 17:27:57 -070077import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -070078import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +020079import java.util.Locale;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070080import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import java.util.TimeZone;
John Spurlock604a5ee2015-06-01 12:27:22 -040082import java.util.TreeSet;
Makoto Onuki2206af32017-11-21 16:25:35 -080083import java.util.function.Predicate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084
Suprabh Shuklac25447d2018-01-19 16:43:35 -080085import static android.app.AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Christopher Tatee0a22b32013-07-11 14:43:13 -070086import static android.app.AlarmManager.RTC_WAKEUP;
87import static android.app.AlarmManager.RTC;
88import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
89import static android.app.AlarmManager.ELAPSED_REALTIME;
90
Christopher Tate21e9f192017-08-08 13:49:11 -070091import com.android.internal.annotations.GuardedBy;
Makoto Onuki2206af32017-11-21 16:25:35 -080092import com.android.internal.annotations.VisibleForTesting;
Makoto Onuki5d93b832018-01-10 16:12:39 -080093import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060094import com.android.internal.util.DumpUtils;
Dianne Hackborn81038902012-11-26 17:04:09 -080095import com.android.internal.util.LocalLog;
Makoto Onuki2206af32017-11-21 16:25:35 -080096import com.android.server.ForceAppStandbyTracker.Listener;
Dianne Hackborn81038902012-11-26 17:04:09 -080097
Makoto Onuki2206af32017-11-21 16:25:35 -080098/**
99 * Alarm manager implementaion.
100 *
101 * Unit test:
102 atest $ANDROID_BUILD_TOP/frameworks/base/services/tests/servicestests/src/com/android/server/AlarmManagerServiceTest.java
103 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800104class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700105 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
106 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800107 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700108 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800109 static final int TIME_CHANGED_MASK = 1 << 16;
110 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -0800111
Christopher Tatee0a22b32013-07-11 14:43:13 -0700112 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -0800113 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -0800114
Adam Lesinski182f73f2013-12-05 16:48:06 -0800115 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -0800116 static final boolean localLOGV = false;
117 static final boolean DEBUG_BATCH = localLOGV || false;
118 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200119 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700120 static final boolean DEBUG_LISTENER_CALLBACK = localLOGV || false;
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800121 static final boolean DEBUG_WAKELOCK = localLOGV || false;
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700122 static final boolean DEBUG_BG_LIMIT = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700123 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700124 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800125 static final int ALARM_EVENT = 1;
126 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200127
Christopher Tate14a7bb02015-10-01 10:24:31 -0700128 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800130 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700131
Adam Lesinski182f73f2013-12-05 16:48:06 -0800132 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700133
Christopher Tate24cd46f2016-02-02 14:28:01 -0800134 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT =
135 new Intent(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED)
Christopher Tate50191db2017-05-09 16:02:25 -0700136 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
137 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Adrian Roosc42a1e12014-07-07 23:35:53 +0200138
Adam Lesinski182f73f2013-12-05 16:48:06 -0800139 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800140
Christopher Tate14a7bb02015-10-01 10:24:31 -0700141 AppOpsManager mAppOps;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800142 DeviceIdleController.LocalService mLocalDeviceIdleController;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700143
Adam Lesinski182f73f2013-12-05 16:48:06 -0800144 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800145
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700146 // List of alarms per uid deferred due to user applied background restrictions on the source app
147 SparseArray<ArrayList<Alarm>> mPendingBackgroundAlarms = new SparseArray<>();
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800148 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800149 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700150 private long mNextNonWakeup;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -0700151 private long mLastWakeupSet;
152 private long mLastWakeup;
Christopher Tate12cf0b62018-01-05 18:40:14 -0800153 private long mLastTickSet;
154 private long mLastTickIssued; // elapsed
155 private long mLastTickReceived;
Makoto Onuki5d93b832018-01-10 16:12:39 -0800156 private long mLastTickAdded;
157 private long mLastTickRemoved;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800158 int mBroadcastRefCount = 0;
159 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700160 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700161 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
162 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800163 final AlarmHandler mHandler = new AlarmHandler();
164 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700165 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700167 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800168 PendingIntent mTimeTickSender;
169 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700170 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700171 boolean mInteractive = true;
172 long mNonInteractiveStartTime;
173 long mNonInteractiveTime;
174 long mLastAlarmDeliveryTime;
175 long mStartCurrentDelayTime;
176 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700177 long mLastTimeChangeClockTime;
178 long mLastTimeChangeRealtime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700179 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800180
Christopher Tatebb9cce52017-04-18 14:19:43 -0700181 // Bookkeeping about the identity of the "System UI" package, determined at runtime.
182
183 /**
184 * This permission must be defined by the canonical System UI package,
185 * with protection level "signature".
186 */
187 private static final String SYSTEM_UI_SELF_PERMISSION =
188 "android.permission.systemui.IDENTITY";
189
190 /**
191 * At boot we use SYSTEM_UI_SELF_PERMISSION to look up the definer's uid.
192 */
193 int mSystemUiUid;
194
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700195 /**
196 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
Kweku Adams61e03292017-10-19 14:27:12 -0700197 * used to determine the earliest we can dispatch the next such alarm. Times are in the
198 * 'elapsed' timebase.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700199 */
200 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
201
Suprabh Shuklac25447d2018-01-19 16:43:35 -0800202 /**
203 * For each uid, we store whether the last allow-while-idle alarm was dispatched while
204 * the uid was in foreground or not. We will use the allow_while_idle_short_time in such cases.
205 */
206 final SparseBooleanArray mUseAllowWhileIdleShortTime = new SparseBooleanArray();
207
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700208 final static class IdleDispatchEntry {
209 int uid;
210 String pkg;
211 String tag;
212 String op;
213 long elapsedRealtime;
214 long argRealtime;
215 }
216 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
217
Dianne Hackborna750a632015-06-16 17:18:23 -0700218 /**
219 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
220 */
221 Bundle mIdleOptions;
222
Jose Lima235510e2014-08-13 12:50:01 -0700223 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
224 new SparseArray<>();
225 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
226 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200227 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
228 new SparseBooleanArray();
229 private boolean mNextAlarmClockMayChange;
230
231 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700232 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
233 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200234
Makoto Onuki2206af32017-11-21 16:25:35 -0800235 private final ForceAppStandbyTracker mForceAppStandbyTracker;
236
Dianne Hackborna750a632015-06-16 17:18:23 -0700237 /**
238 * All times are in milliseconds. These constants are kept synchronized with the system
239 * global Settings. Any access to this class or its fields should be done while
240 * holding the AlarmManagerService.mLock lock.
241 */
242 private final class Constants extends ContentObserver {
243 // Key names stored in the settings value.
244 private static final String KEY_MIN_FUTURITY = "min_futurity";
245 private static final String KEY_MIN_INTERVAL = "min_interval";
246 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
247 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
248 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
249 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700250 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Dianne Hackborna750a632015-06-16 17:18:23 -0700251
252 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
253 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tateaa244da2015-08-27 15:57:57 -0700254 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700255 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700256 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
257
Christopher Tate14a7bb02015-10-01 10:24:31 -0700258 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
259
Dianne Hackborna750a632015-06-16 17:18:23 -0700260 // Minimum futurity of a new alarm
261 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
262
263 // Minimum alarm recurrence interval
264 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
265
266 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
267 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
268
269 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
270 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
271
272 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
273 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
274 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
275
Christopher Tate14a7bb02015-10-01 10:24:31 -0700276 // Direct alarm listener callback timeout
277 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
278
Dianne Hackborna750a632015-06-16 17:18:23 -0700279 private ContentResolver mResolver;
280 private final KeyValueListParser mParser = new KeyValueListParser(',');
281 private long mLastAllowWhileIdleWhitelistDuration = -1;
282
283 public Constants(Handler handler) {
284 super(handler);
Dianne Hackborna750a632015-06-16 17:18:23 -0700285 updateAllowWhileIdleWhitelistDurationLocked();
286 }
287
288 public void start(ContentResolver resolver) {
289 mResolver = resolver;
290 mResolver.registerContentObserver(Settings.Global.getUriFor(
291 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
292 updateConstants();
293 }
294
Dianne Hackborna750a632015-06-16 17:18:23 -0700295 public void updateAllowWhileIdleWhitelistDurationLocked() {
296 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
297 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
298 BroadcastOptions opts = BroadcastOptions.makeBasic();
299 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
300 mIdleOptions = opts.toBundle();
301 }
302 }
303
304 @Override
305 public void onChange(boolean selfChange, Uri uri) {
306 updateConstants();
307 }
308
309 private void updateConstants() {
310 synchronized (mLock) {
311 try {
312 mParser.setString(Settings.Global.getString(mResolver,
313 Settings.Global.ALARM_MANAGER_CONSTANTS));
314 } catch (IllegalArgumentException e) {
315 // Failed to parse the settings string, log this and move on
316 // with defaults.
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800317 Slog.e(TAG, "Bad alarm manager settings", e);
Dianne Hackborna750a632015-06-16 17:18:23 -0700318 }
319
320 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
321 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
322 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
323 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
324 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
325 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
326 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
327 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
328 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700329 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
330 DEFAULT_LISTENER_TIMEOUT);
Dianne Hackborna750a632015-06-16 17:18:23 -0700331
Dianne Hackborna750a632015-06-16 17:18:23 -0700332 updateAllowWhileIdleWhitelistDurationLocked();
333 }
334 }
335
336 void dump(PrintWriter pw) {
337 pw.println(" Settings:");
338
339 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
340 TimeUtils.formatDuration(MIN_FUTURITY, pw);
341 pw.println();
342
343 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
344 TimeUtils.formatDuration(MIN_INTERVAL, pw);
345 pw.println();
346
Christopher Tate14a7bb02015-10-01 10:24:31 -0700347 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
348 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
349 pw.println();
350
Dianne Hackborna750a632015-06-16 17:18:23 -0700351 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
352 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
353 pw.println();
354
355 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
356 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
357 pw.println();
358
359 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
360 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
361 pw.println();
362 }
Kweku Adams61e03292017-10-19 14:27:12 -0700363
364 void dumpProto(ProtoOutputStream proto, long fieldId) {
365 final long token = proto.start(fieldId);
366
367 proto.write(ConstantsProto.MIN_FUTURITY_DURATION_MS, MIN_FUTURITY);
368 proto.write(ConstantsProto.MIN_INTERVAL_DURATION_MS, MIN_INTERVAL);
369 proto.write(ConstantsProto.LISTENER_TIMEOUT_DURATION_MS, LISTENER_TIMEOUT);
370 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_SHORT_DURATION_MS,
371 ALLOW_WHILE_IDLE_SHORT_TIME);
372 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_LONG_DURATION_MS,
373 ALLOW_WHILE_IDLE_LONG_TIME);
374 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_WHITELIST_DURATION_MS,
375 ALLOW_WHILE_IDLE_WHITELIST_DURATION);
376
377 proto.end(token);
378 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700379 }
380
381 final Constants mConstants;
382
Christopher Tate1590f1e2014-10-02 17:27:57 -0700383 // Alarm delivery ordering bookkeeping
384 static final int PRIO_TICK = 0;
385 static final int PRIO_WAKEUP = 1;
386 static final int PRIO_NORMAL = 2;
387
Dianne Hackborna750a632015-06-16 17:18:23 -0700388 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700389 int seq;
390 int priority;
391
392 PriorityClass() {
393 seq = mCurrentSeq - 1;
394 priority = PRIO_NORMAL;
395 }
396 }
397
Dianne Hackborna750a632015-06-16 17:18:23 -0700398 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700399 int mCurrentSeq = 0;
400
Dianne Hackborna750a632015-06-16 17:18:23 -0700401 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700402 public long when;
403 public int uid;
404 public String action;
405
406 public WakeupEvent(long theTime, int theUid, String theAction) {
407 when = theTime;
408 uid = theUid;
409 action = theAction;
410 }
411 }
412
Adam Lesinski182f73f2013-12-05 16:48:06 -0800413 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
414 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700415
Adrian Roosc42a1e12014-07-07 23:35:53 +0200416 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700417 long start; // These endpoints are always in ELAPSED
418 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700419 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700420
421 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
422
423 Batch() {
424 start = 0;
425 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700426 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700427 }
428
429 Batch(Alarm seed) {
430 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700431 end = seed.maxWhenElapsed;
432 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700433 alarms.add(seed);
Makoto Onuki5d93b832018-01-10 16:12:39 -0800434 if (seed.operation == mTimeTickSender) {
435 mLastTickAdded = System.currentTimeMillis();
436 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700437 }
438
439 int size() {
440 return alarms.size();
441 }
442
443 Alarm get(int index) {
444 return alarms.get(index);
445 }
446
447 boolean canHold(long whenElapsed, long maxWhen) {
448 return (end >= whenElapsed) && (start <= maxWhen);
449 }
450
451 boolean add(Alarm alarm) {
452 boolean newStart = false;
453 // narrows the batch if necessary; presumes that canHold(alarm) is true
454 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
455 if (index < 0) {
456 index = 0 - index - 1;
457 }
458 alarms.add(index, alarm);
Makoto Onuki5d93b832018-01-10 16:12:39 -0800459 if (alarm.operation == mTimeTickSender) {
460 mLastTickAdded = System.currentTimeMillis();
461 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700462 if (DEBUG_BATCH) {
463 Slog.v(TAG, "Adding " + alarm + " to " + this);
464 }
465 if (alarm.whenElapsed > start) {
466 start = alarm.whenElapsed;
467 newStart = true;
468 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700469 if (alarm.maxWhenElapsed < end) {
470 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700471 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700472 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700473
474 if (DEBUG_BATCH) {
475 Slog.v(TAG, " => now " + this);
476 }
477 return newStart;
478 }
479
Christopher Tate1d99c392017-12-07 16:54:04 -0800480 boolean remove(Predicate<Alarm> predicate) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700481 boolean didRemove = false;
482 long newStart = 0; // recalculate endpoints as we go
483 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700484 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700485 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700486 Alarm alarm = alarms.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -0800487 if (predicate.test(alarm)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700488 alarms.remove(i);
489 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200490 if (alarm.alarmClock != null) {
491 mNextAlarmClockMayChange = true;
492 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800493 if (alarm.operation == mTimeTickSender) {
494 mLastTickRemoved = System.currentTimeMillis();
495 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700496 } else {
497 if (alarm.whenElapsed > newStart) {
498 newStart = alarm.whenElapsed;
499 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700500 if (alarm.maxWhenElapsed < newEnd) {
501 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700502 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700503 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700504 i++;
505 }
506 }
507 if (didRemove) {
508 // commit the new batch bounds
509 start = newStart;
510 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700511 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700512 }
513 return didRemove;
514 }
515
Christopher Tatee0a22b32013-07-11 14:43:13 -0700516 boolean hasPackage(final String packageName) {
517 final int N = alarms.size();
518 for (int i = 0; i < N; i++) {
519 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700520 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700521 return true;
522 }
523 }
524 return false;
525 }
526
527 boolean hasWakeups() {
528 final int N = alarms.size();
529 for (int i = 0; i < N; i++) {
530 Alarm a = alarms.get(i);
531 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
532 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
533 return true;
534 }
535 }
536 return false;
537 }
538
539 @Override
540 public String toString() {
541 StringBuilder b = new StringBuilder(40);
542 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
543 b.append(" num="); b.append(size());
544 b.append(" start="); b.append(start);
545 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700546 if (flags != 0) {
547 b.append(" flgs=0x");
548 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700549 }
550 b.append('}');
551 return b.toString();
552 }
Kweku Adams61e03292017-10-19 14:27:12 -0700553
554 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
555 long nowRTC) {
556 final long token = proto.start(fieldId);
557
558 proto.write(BatchProto.START_REALTIME, start);
559 proto.write(BatchProto.END_REALTIME, end);
560 proto.write(BatchProto.FLAGS, flags);
561 for (Alarm a : alarms) {
562 a.writeToProto(proto, BatchProto.ALARMS, nowElapsed, nowRTC);
563 }
564
565 proto.end(token);
566 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700567 }
568
569 static class BatchTimeOrder implements Comparator<Batch> {
570 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800571 long when1 = b1.start;
572 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800573 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700574 return 1;
575 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800576 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700577 return -1;
578 }
579 return 0;
580 }
581 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800582
583 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
584 @Override
585 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700586 // priority class trumps everything. TICK < WAKEUP < NORMAL
587 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
588 return -1;
589 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
590 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800591 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700592
593 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800594 if (lhs.whenElapsed < rhs.whenElapsed) {
595 return -1;
596 } else if (lhs.whenElapsed > rhs.whenElapsed) {
597 return 1;
598 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700599
600 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800601 return 0;
602 }
603 };
604
Christopher Tate1590f1e2014-10-02 17:27:57 -0700605 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
606 final int N = alarms.size();
607 for (int i = 0; i < N; i++) {
608 Alarm a = alarms.get(i);
609
610 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700611 if (a.operation != null
612 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700613 alarmPrio = PRIO_TICK;
614 } else if (a.wakeup) {
615 alarmPrio = PRIO_WAKEUP;
616 } else {
617 alarmPrio = PRIO_NORMAL;
618 }
619
620 PriorityClass packagePrio = a.priorityClass;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700621 String alarmPackage = (a.operation != null)
622 ? a.operation.getCreatorPackage()
623 : a.packageName;
624 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700625 if (packagePrio == null) {
626 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700627 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700628 }
629 a.priorityClass = packagePrio;
630
631 if (packagePrio.seq != mCurrentSeq) {
632 // first alarm we've seen in the current delivery generation from this package
633 packagePrio.priority = alarmPrio;
634 packagePrio.seq = mCurrentSeq;
635 } else {
636 // Multiple alarms from this package being delivered in this generation;
637 // bump the package's delivery class if it's warranted.
638 // TICK < WAKEUP < NORMAL
639 if (alarmPrio < packagePrio.priority) {
640 packagePrio.priority = alarmPrio;
641 }
642 }
643 }
644 }
645
Christopher Tatee0a22b32013-07-11 14:43:13 -0700646 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800647 static final long MIN_FUZZABLE_INTERVAL = 10000;
648 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700649 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
650
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700651 // set to non-null if in idle mode; while in this mode, any alarms we don't want
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700652 // to run during this time are placed in mPendingWhileIdleAlarms
653 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700654 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700655 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700656
Jeff Brownb880d882014-02-10 19:47:07 -0800657 public AlarmManagerService(Context context) {
658 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700659 mConstants = new Constants(mHandler);
Makoto Onuki2206af32017-11-21 16:25:35 -0800660
661 mForceAppStandbyTracker = ForceAppStandbyTracker.getInstance(context);
662 mForceAppStandbyTracker.addListener(mForceAppStandbyListener);
Christopher Tate1d99c392017-12-07 16:54:04 -0800663
664 publishLocalService(AlarmManagerInternal.class, new LocalService());
Jeff Brownb880d882014-02-10 19:47:07 -0800665 }
666
Christopher Tatee0a22b32013-07-11 14:43:13 -0700667 static long convertToElapsed(long when, int type) {
668 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
669 if (isRtc) {
670 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
671 }
672 return when;
673 }
674
675 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
676 // calculate the end of our nominal delivery window for the alarm.
677 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
678 // Current heuristic: batchable window is 75% of either the recurrence interval
679 // [for a periodic alarm] or of the time from now to the desired delivery time,
680 // with a minimum delay/interval of 10 seconds, under which we will simply not
681 // defer the alarm.
682 long futurity = (interval == 0)
683 ? (triggerAtTime - now)
684 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700685 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700686 futurity = 0;
687 }
688 return triggerAtTime + (long)(.75 * futurity);
689 }
690
691 // returns true if the batch was added at the head
692 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
693 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
694 if (index < 0) {
695 index = 0 - index - 1;
696 }
697 list.add(index, newBatch);
698 return (index == 0);
699 }
700
Christopher Tate385e4982013-07-23 18:22:29 -0700701 // Return the index of the matching batch, or -1 if none found.
702 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700703 final int N = mAlarmBatches.size();
704 for (int i = 0; i < N; i++) {
705 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700706 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700707 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700708 }
709 }
Christopher Tate385e4982013-07-23 18:22:29 -0700710 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700711 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800712 /** @return total count of the alarms in a set of alarm batches. */
713 static int getAlarmCount(ArrayList<Batch> batches) {
714 int ret = 0;
715
716 final int size = batches.size();
717 for (int i = 0; i < size; i++) {
718 ret += batches.get(i).size();
719 }
720 return ret;
721 }
722
723 boolean haveAlarmsTimeTickAlarm(ArrayList<Alarm> alarms) {
724 if (alarms.size() == 0) {
725 return false;
726 }
727 final int batchSize = alarms.size();
728 for (int j = 0; j < batchSize; j++) {
729 if (alarms.get(j).operation == mTimeTickSender) {
730 return true;
731 }
732 }
733 return false;
734 }
735
736 boolean haveBatchesTimeTickAlarm(ArrayList<Batch> batches) {
737 final int numBatches = batches.size();
738 for (int i = 0; i < numBatches; i++) {
739 if (haveAlarmsTimeTickAlarm(batches.get(i).alarms)) {
740 return true;
741 }
742 }
743 return false;
744 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700745
746 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
747 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700748 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700749 rebatchAllAlarmsLocked(true);
750 }
751 }
752
753 void rebatchAllAlarmsLocked(boolean doValidate) {
Makoto Onuki5d93b832018-01-10 16:12:39 -0800754 final int oldCount =
755 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
756 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
757 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
758
Christopher Tate4cb338d2013-07-26 13:11:31 -0700759 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
760 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700761 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700762 final long nowElapsed = SystemClock.elapsedRealtime();
763 final int oldBatches = oldSet.size();
764 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
765 Batch batch = oldSet.get(batchNum);
766 final int N = batch.size();
767 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700768 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700769 }
770 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700771 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
772 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
773 + " to " + mPendingIdleUntil);
774 if (mPendingIdleUntil == null) {
775 // Somehow we lost this... we need to restore all of the pending alarms.
776 restorePendingWhileIdleAlarmsLocked();
777 }
778 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800779 final int newCount =
780 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
781 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
782 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
783
784 if (oldCount != newCount) {
785 Slog.wtf(TAG, "Rebatching: total count changed from " + oldCount + " to " + newCount);
786 }
787 if (oldHasTick != newHasTick) {
788 Slog.wtf(TAG, "Rebatching: hasTick changed from " + oldHasTick + " to " + newHasTick);
789 }
790
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700791 rescheduleKernelAlarmsLocked();
792 updateNextAlarmClockLocked();
793 }
794
795 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
796 a.when = a.origWhen;
797 long whenElapsed = convertToElapsed(a.when, a.type);
798 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700799 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700800 // Exact
801 maxElapsed = whenElapsed;
802 } else {
803 // Not exact. Preserve any explicit window, otherwise recalculate
804 // the window based on the alarm's new futurity. Note that this
805 // reflects a policy of preferring timely to deferred delivery.
806 maxElapsed = (a.windowLength > 0)
807 ? (whenElapsed + a.windowLength)
808 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
809 }
810 a.whenElapsed = whenElapsed;
811 a.maxWhenElapsed = maxElapsed;
812 setImplLocked(a, true, doValidate);
813 }
814
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700815 /**
816 * Sends alarms that were blocked due to user applied background restrictions - either because
817 * the user lifted those or the uid came to foreground.
818 *
819 * @param uid uid to filter on
820 * @param packageName package to filter on, or null for all packages in uid
821 */
822 void sendPendingBackgroundAlarmsLocked(int uid, String packageName) {
823 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(uid);
824 if (alarmsForUid == null || alarmsForUid.size() == 0) {
825 return;
826 }
827 final ArrayList<Alarm> alarmsToDeliver;
828 if (packageName != null) {
829 if (DEBUG_BG_LIMIT) {
830 Slog.d(TAG, "Sending blocked alarms for uid " + uid + ", package " + packageName);
831 }
832 alarmsToDeliver = new ArrayList<>();
833 for (int i = alarmsForUid.size() - 1; i >= 0; i--) {
834 final Alarm a = alarmsForUid.get(i);
835 if (a.matches(packageName)) {
836 alarmsToDeliver.add(alarmsForUid.remove(i));
837 }
838 }
839 if (alarmsForUid.size() == 0) {
840 mPendingBackgroundAlarms.remove(uid);
841 }
842 } else {
843 if (DEBUG_BG_LIMIT) {
844 Slog.d(TAG, "Sending blocked alarms for uid " + uid);
845 }
846 alarmsToDeliver = alarmsForUid;
847 mPendingBackgroundAlarms.remove(uid);
848 }
849 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
850 }
851
Makoto Onuki2206af32017-11-21 16:25:35 -0800852 /**
853 * Check all alarms in {@link #mPendingBackgroundAlarms} and send the ones that are not
854 * restricted.
855 *
856 * This is only called when the global "force all apps-standby" flag changes or when the
857 * power save whitelist changes, so it's okay to be slow.
858 */
859 void sendAllUnrestrictedPendingBackgroundAlarmsLocked() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700860 final ArrayList<Alarm> alarmsToDeliver = new ArrayList<>();
Makoto Onuki2206af32017-11-21 16:25:35 -0800861
862 findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
863 mPendingBackgroundAlarms, alarmsToDeliver, this::isBackgroundRestricted);
864
865 if (alarmsToDeliver.size() > 0) {
866 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
867 }
868 }
869
870 @VisibleForTesting
871 static void findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
872 SparseArray<ArrayList<Alarm>> pendingAlarms, ArrayList<Alarm> unrestrictedAlarms,
873 Predicate<Alarm> isBackgroundRestricted) {
874
875 for (int uidIndex = pendingAlarms.size() - 1; uidIndex >= 0; uidIndex--) {
876 final int uid = pendingAlarms.keyAt(uidIndex);
877 final ArrayList<Alarm> alarmsForUid = pendingAlarms.valueAt(uidIndex);
878
879 for (int alarmIndex = alarmsForUid.size() - 1; alarmIndex >= 0; alarmIndex--) {
880 final Alarm alarm = alarmsForUid.get(alarmIndex);
881
882 if (isBackgroundRestricted.test(alarm)) {
883 continue;
884 }
885
886 unrestrictedAlarms.add(alarm);
887 alarmsForUid.remove(alarmIndex);
888 }
889
890 if (alarmsForUid.size() == 0) {
891 pendingAlarms.removeAt(uidIndex);
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700892 }
893 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700894 }
895
896 private void deliverPendingBackgroundAlarmsLocked(ArrayList<Alarm> alarms, long nowELAPSED) {
897 final int N = alarms.size();
898 boolean hasWakeup = false;
899 for (int i = 0; i < N; i++) {
900 final Alarm alarm = alarms.get(i);
901 if (alarm.wakeup) {
902 hasWakeup = true;
903 }
904 alarm.count = 1;
905 // Recurring alarms may have passed several alarm intervals while the
906 // alarm was kept pending. Send the appropriate trigger count.
907 if (alarm.repeatInterval > 0) {
908 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
909 // Also schedule its next recurrence
910 final long delta = alarm.count * alarm.repeatInterval;
911 final long nextElapsed = alarm.whenElapsed + delta;
912 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
913 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
914 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
915 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
916 // Kernel alarms will be rescheduled as needed in setImplLocked
917 }
918 }
919 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
920 // No need to wakeup for non wakeup alarms
921 if (mPendingNonWakeupAlarms.size() == 0) {
922 mStartCurrentDelayTime = nowELAPSED;
923 mNextNonWakeupDeliveryTime = nowELAPSED
924 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
925 }
926 mPendingNonWakeupAlarms.addAll(alarms);
927 mNumDelayedAlarms += alarms.size();
928 } else {
929 if (DEBUG_BG_LIMIT) {
930 Slog.d(TAG, "Waking up to deliver pending blocked alarms");
931 }
932 // Since we are waking up, also deliver any pending non wakeup alarms we have.
933 if (mPendingNonWakeupAlarms.size() > 0) {
934 alarms.addAll(mPendingNonWakeupAlarms);
935 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
936 mTotalDelayTime += thisDelayTime;
937 if (mMaxDelayTime < thisDelayTime) {
938 mMaxDelayTime = thisDelayTime;
939 }
940 mPendingNonWakeupAlarms.clear();
941 }
942 calculateDeliveryPriorities(alarms);
943 Collections.sort(alarms, mAlarmDispatchComparator);
944 deliverAlarmsLocked(alarms, nowELAPSED);
945 }
946 }
947
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700948 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700949 if (RECORD_DEVICE_IDLE_ALARMS) {
950 IdleDispatchEntry ent = new IdleDispatchEntry();
951 ent.uid = 0;
952 ent.pkg = "FINISH IDLE";
953 ent.elapsedRealtime = SystemClock.elapsedRealtime();
954 mAllowWhileIdleDispatches.add(ent);
955 }
956
Dianne Hackborn35d54032015-04-23 10:30:43 -0700957 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700958 if (mPendingWhileIdleAlarms.size() > 0) {
959 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
960 mPendingWhileIdleAlarms = new ArrayList<>();
961 final long nowElapsed = SystemClock.elapsedRealtime();
962 for (int i=alarms.size() - 1; i >= 0; i--) {
963 Alarm a = alarms.get(i);
964 reAddAlarmLocked(a, nowElapsed, false);
965 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700966 }
Dianne Hackborn35d54032015-04-23 10:30:43 -0700967
968 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700969 rescheduleKernelAlarmsLocked();
970 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -0700971
972 // And send a TIME_TICK right now, since it is important to get the UI updated.
973 try {
974 mTimeTickSender.send();
975 } catch (PendingIntent.CanceledException e) {
976 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700977 }
978
Christopher Tate14a7bb02015-10-01 10:24:31 -0700979 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -0800980 final PendingIntent mPendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -0700981 final long mWhenElapsed;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700982 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -0700983 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700984 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700985 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800986 final BroadcastStats mBroadcastStats;
987 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800988 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800989
Christopher Tate14a7bb02015-10-01 10:24:31 -0700990 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
991 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
992 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800993 mPendingIntent = pendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -0700994 mWhenElapsed = nowELAPSED;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700995 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -0700996 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700997 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700998 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700999 mBroadcastStats = (pendingIntent != null)
1000 ? service.getStatsLocked(pendingIntent)
1001 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001002 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001003 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001004 fs = new FilterStats(mBroadcastStats, mTag);
1005 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -08001006 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001007 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -08001008 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001009 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001010 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001011
1012 @Override
1013 public String toString() {
1014 return "InFlight{"
1015 + "pendingIntent=" + mPendingIntent
Christopher Tateeabba732017-08-17 17:12:52 -07001016 + ", when=" + mWhenElapsed
Makoto Onuki33955e12017-03-01 18:11:00 -08001017 + ", workSource=" + mWorkSource
1018 + ", uid=" + mUid
1019 + ", tag=" + mTag
1020 + ", broadcastStats=" + mBroadcastStats
1021 + ", filterStats=" + mFilterStats
1022 + ", alarmType=" + mAlarmType
1023 + "}";
1024 }
Kweku Adams61e03292017-10-19 14:27:12 -07001025
1026 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1027 final long token = proto.start(fieldId);
1028
1029 proto.write(InFlightProto.UID, mUid);
1030 proto.write(InFlightProto.TAG, mTag);
1031 proto.write(InFlightProto.WHEN_ELAPSED_MS, mWhenElapsed);
1032 proto.write(InFlightProto.ALARM_TYPE, mAlarmType);
1033 if (mPendingIntent != null) {
1034 mPendingIntent.writeToProto(proto, InFlightProto.PENDING_INTENT);
1035 }
1036 if (mBroadcastStats != null) {
1037 mBroadcastStats.writeToProto(proto, InFlightProto.BROADCAST_STATS);
1038 }
1039 if (mFilterStats != null) {
1040 mFilterStats.writeToProto(proto, InFlightProto.FILTER_STATS);
1041 }
1042 if (mWorkSource != null) {
1043 mWorkSource.writeToProto(proto, InFlightProto.WORK_SOURCE);
1044 }
1045
1046 proto.end(token);
1047 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001049
Adam Lesinski182f73f2013-12-05 16:48:06 -08001050 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -08001051 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001052 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001053
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001054 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -08001056 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 int numWakeup;
1058 long startTime;
1059 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -08001060
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001061 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001062 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001063 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001064 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001065
1066 @Override
1067 public String toString() {
1068 return "FilterStats{"
1069 + "tag=" + mTag
1070 + ", lastTime=" + lastTime
1071 + ", aggregateTime=" + aggregateTime
1072 + ", count=" + count
1073 + ", numWakeup=" + numWakeup
1074 + ", startTime=" + startTime
1075 + ", nesting=" + nesting
1076 + "}";
1077 }
Kweku Adams61e03292017-10-19 14:27:12 -07001078
1079 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1080 final long token = proto.start(fieldId);
1081
1082 proto.write(FilterStatsProto.TAG, mTag);
1083 proto.write(FilterStatsProto.LAST_FLIGHT_TIME_REALTIME, lastTime);
1084 proto.write(FilterStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1085 proto.write(FilterStatsProto.COUNT, count);
1086 proto.write(FilterStatsProto.WAKEUP_COUNT, numWakeup);
1087 proto.write(FilterStatsProto.START_TIME_REALTIME, startTime);
1088 proto.write(FilterStatsProto.NESTING, nesting);
1089
1090 proto.end(token);
1091 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001092 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001093
Adam Lesinski182f73f2013-12-05 16:48:06 -08001094 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001095 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001096 final String mPackageName;
1097
1098 long aggregateTime;
1099 int count;
1100 int numWakeup;
1101 long startTime;
1102 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001103 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -08001104
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001105 BroadcastStats(int uid, String packageName) {
1106 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001107 mPackageName = packageName;
1108 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001109
1110 @Override
1111 public String toString() {
1112 return "BroadcastStats{"
1113 + "uid=" + mUid
1114 + ", packageName=" + mPackageName
1115 + ", aggregateTime=" + aggregateTime
1116 + ", count=" + count
1117 + ", numWakeup=" + numWakeup
1118 + ", startTime=" + startTime
1119 + ", nesting=" + nesting
1120 + "}";
1121 }
Kweku Adams61e03292017-10-19 14:27:12 -07001122
1123 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1124 final long token = proto.start(fieldId);
1125
1126 proto.write(BroadcastStatsProto.UID, mUid);
1127 proto.write(BroadcastStatsProto.PACKAGE_NAME, mPackageName);
1128 proto.write(BroadcastStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1129 proto.write(BroadcastStatsProto.COUNT, count);
1130 proto.write(BroadcastStatsProto.WAKEUP_COUNT, numWakeup);
1131 proto.write(BroadcastStatsProto.START_TIME_REALTIME, startTime);
1132 proto.write(BroadcastStatsProto.NESTING, nesting);
1133
1134 proto.end(token);
1135 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001136 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001137
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001138 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
1139 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001140
1141 int mNumDelayedAlarms = 0;
1142 long mTotalDelayTime = 0;
1143 long mMaxDelayTime = 0;
1144
Adam Lesinski182f73f2013-12-05 16:48:06 -08001145 @Override
1146 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001147 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001148 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001149
1150 // We have to set current TimeZone info to kernel
1151 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -08001152 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001153
Christopher Tate247571462017-04-10 11:45:05 -07001154 // Also sure that we're booting with a halfway sensible current time
1155 if (mNativeData != 0) {
1156 final long systemBuildTime = Environment.getRootDirectory().lastModified();
1157 if (System.currentTimeMillis() < systemBuildTime) {
1158 Slog.i(TAG, "Current time only " + System.currentTimeMillis()
1159 + ", advancing to build time " + systemBuildTime);
1160 setKernelTime(mNativeData, systemBuildTime);
1161 }
1162 }
1163
Christopher Tatebb9cce52017-04-18 14:19:43 -07001164 // Determine SysUI's uid
1165 final PackageManager packMan = getContext().getPackageManager();
1166 try {
1167 PermissionInfo sysUiPerm = packMan.getPermissionInfo(SYSTEM_UI_SELF_PERMISSION, 0);
1168 ApplicationInfo sysUi = packMan.getApplicationInfo(sysUiPerm.packageName, 0);
1169 if ((sysUi.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1170 mSystemUiUid = sysUi.uid;
1171 } else {
1172 Slog.e(TAG, "SysUI permission " + SYSTEM_UI_SELF_PERMISSION
1173 + " defined by non-privileged app " + sysUi.packageName
1174 + " - ignoring");
1175 }
1176 } catch (NameNotFoundException e) {
1177 }
1178
1179 if (mSystemUiUid <= 0) {
1180 Slog.wtf(TAG, "SysUI package not found!");
1181 }
1182
Adam Lesinski182f73f2013-12-05 16:48:06 -08001183 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001184 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001185
Adam Lesinski182f73f2013-12-05 16:48:06 -08001186 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001187 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001188 Intent.FLAG_RECEIVER_REGISTERED_ONLY
Chad Brubaker291df4f2017-03-14 10:23:02 -07001189 | Intent.FLAG_RECEIVER_FOREGROUND
1190 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001191 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001192 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001193 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1194 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001195 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001196 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
Kweku Adams61e03292017-10-19 14:27:12 -07001197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -08001199 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 mClockReceiver.scheduleTimeTickEvent();
1201 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001202 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001203 mUninstallReceiver = new UninstallReceiver();
Kweku Adams61e03292017-10-19 14:27:12 -07001204
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001205 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001206 AlarmThread waitThread = new AlarmThread();
1207 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001209 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001211
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001212 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001213 ActivityManager.getService().registerUidObserver(new UidObserver(),
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001214 ActivityManager.UID_OBSERVER_GONE | ActivityManager.UID_OBSERVER_IDLE
1215 | ActivityManager.UID_OBSERVER_ACTIVE,
1216 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001217 } catch (RemoteException e) {
1218 // ignored; both services live in system_server
1219 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001220 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001221 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001222
1223 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001224 public void onBootPhase(int phase) {
1225 if (phase == PHASE_SYSTEM_SERVICES_READY) {
Suprabh Shukla4deb8522018-01-08 16:27:10 -08001226 mForceAppStandbyTracker.start();
Dianne Hackborna750a632015-06-16 17:18:23 -07001227 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -07001228 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001229 mLocalDeviceIdleController
1230 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackborna750a632015-06-16 17:18:23 -07001231 }
1232 }
1233
1234 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 protected void finalize() throws Throwable {
1236 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001237 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001238 } finally {
1239 super.finalize();
1240 }
1241 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001242
Adam Lesinski182f73f2013-12-05 16:48:06 -08001243 void setTimeZoneImpl(String tz) {
1244 if (TextUtils.isEmpty(tz)) {
1245 return;
David Christieebe51fc2013-07-26 13:23:29 -07001246 }
1247
Adam Lesinski182f73f2013-12-05 16:48:06 -08001248 TimeZone zone = TimeZone.getTimeZone(tz);
1249 // Prevent reentrant calls from stepping on each other when writing
1250 // the time zone property
1251 boolean timeZoneWasChanged = false;
1252 synchronized (this) {
1253 String current = SystemProperties.get(TIMEZONE_PROPERTY);
1254 if (current == null || !current.equals(zone.getID())) {
1255 if (localLOGV) {
1256 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
1257 }
1258 timeZoneWasChanged = true;
1259 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
1260 }
1261
1262 // Update the kernel timezone information
1263 // Kernel tracks time offsets as 'minutes west of GMT'
1264 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001265 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001266 }
1267
1268 TimeZone.setDefault(null);
1269
1270 if (timeZoneWasChanged) {
1271 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001272 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate5cdf9f82017-05-03 18:10:39 -07001273 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
Chad Brubaker291df4f2017-03-14 10:23:02 -07001274 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001275 intent.putExtra("time-zone", zone.getID());
1276 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1277 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001279
Adam Lesinski182f73f2013-12-05 16:48:06 -08001280 void removeImpl(PendingIntent operation) {
1281 if (operation == null) {
1282 return;
1283 }
1284 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001285 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001286 }
1287 }
1288
1289 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001290 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1291 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1292 int callingUid, String callingPackage) {
1293 // must be *either* PendingIntent or AlarmReceiver, but not both
1294 if ((operation == null && directReceiver == null)
1295 || (operation != null && directReceiver != null)) {
1296 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1297 // NB: previous releases failed silently here, so we are continuing to do the same
1298 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 return;
1300 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001301
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001302 // Sanity check the window length. This will catch people mistakenly
1303 // trying to pass an end-of-window timestamp rather than a duration.
1304 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1305 Slog.w(TAG, "Window length " + windowLength
1306 + "ms suspiciously long; limiting to 1 hour");
1307 windowLength = AlarmManager.INTERVAL_HOUR;
1308 }
1309
Christopher Tate498c6cb2014-11-17 16:09:27 -08001310 // Sanity check the recurrence interval. This will catch people who supply
1311 // seconds when the API expects milliseconds.
Dianne Hackborna750a632015-06-16 17:18:23 -07001312 final long minInterval = mConstants.MIN_INTERVAL;
1313 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001314 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001315 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001316 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001317 interval = minInterval;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001318 }
1319
Christopher Tatee0a22b32013-07-11 14:43:13 -07001320 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1321 throw new IllegalArgumentException("Invalid alarm type " + type);
1322 }
1323
Christopher Tate5f221e82013-07-30 17:13:15 -07001324 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001325 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001326 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001327 + " pid=" + what);
1328 triggerAtTime = 0;
1329 }
1330
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001331 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001332 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1333 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001334 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001335 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1336
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001337 final long maxElapsed;
1338 if (windowLength == AlarmManager.WINDOW_EXACT) {
1339 maxElapsed = triggerElapsed;
1340 } else if (windowLength < 0) {
1341 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001342 // Fix this window in place, so that as time approaches we don't collapse it.
1343 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001344 } else {
1345 maxElapsed = triggerElapsed + windowLength;
1346 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001349 if (DEBUG_BATCH) {
1350 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001351 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001352 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001353 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001355 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001356 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1357 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358 }
1359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360
Christopher Tate3e04b472013-10-21 17:51:31 -07001361 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001362 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1363 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1364 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001365 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001366 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1367 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001368 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001369 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001370 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1371 + " -- package not allowed to start");
1372 return;
1373 }
1374 } catch (RemoteException e) {
1375 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001376 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001377 setImplLocked(a, false, doValidate);
1378 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001379
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001380 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1381 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001382 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001383 // The caller has given the time they want this to happen at, however we need
1384 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001385 // bring us out of idle at an earlier time.
1386 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001387 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001388 }
1389 // Add fuzz to make the alarm go off some time before the actual desired time.
1390 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001391 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001392 if (fuzz > 0) {
1393 if (mRandom == null) {
1394 mRandom = new Random();
1395 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001396 final int delta = mRandom.nextInt(fuzz);
1397 a.whenElapsed -= delta;
1398 if (false) {
1399 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1400 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1401 Slog.d(TAG, "Applied fuzz: " + fuzz);
1402 Slog.d(TAG, "Final delta: " + delta);
1403 Slog.d(TAG, "Final when: " + a.whenElapsed);
1404 }
1405 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001406 }
1407
1408 } else if (mPendingIdleUntil != null) {
1409 // We currently have an idle until alarm scheduled; if the new alarm has
1410 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001411 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1412 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1413 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001414 == 0) {
1415 mPendingWhileIdleAlarms.add(a);
1416 return;
1417 }
1418 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001419 if (RECORD_DEVICE_IDLE_ALARMS) {
1420 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1421 IdleDispatchEntry ent = new IdleDispatchEntry();
1422 ent.uid = a.uid;
1423 ent.pkg = a.operation.getCreatorPackage();
1424 ent.tag = a.operation.getTag("");
1425 ent.op = "SET";
1426 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1427 ent.argRealtime = a.whenElapsed;
1428 mAllowWhileIdleDispatches.add(ent);
1429 }
1430 }
1431
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001432 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
1433 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -07001434 if (whichBatch < 0) {
1435 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001436 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 } else {
Christopher Tate385e4982013-07-23 18:22:29 -07001438 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001439 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001440 // The start time of this batch advanced, so batch ordering may
1441 // have just been broken. Move it to where it now belongs.
1442 mAlarmBatches.remove(whichBatch);
1443 addBatchLocked(mAlarmBatches, batch);
1444 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 }
1446
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001447 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001448 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001449 }
1450
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001451 boolean needRebatch = false;
1452
1453 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001454 if (RECORD_DEVICE_IDLE_ALARMS) {
1455 if (mPendingIdleUntil == null) {
1456 IdleDispatchEntry ent = new IdleDispatchEntry();
1457 ent.uid = 0;
1458 ent.pkg = "START IDLE";
1459 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1460 mAllowWhileIdleDispatches.add(ent);
1461 }
1462 }
Makoto Onuki4274a6d2017-04-21 12:21:25 -07001463 if ((mPendingIdleUntil != a) && (mPendingIdleUntil != null)) {
1464 Slog.wtfStack(TAG, "setImplLocked: idle until changed from " + mPendingIdleUntil
1465 + " to " + a);
1466 }
1467
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001468 mPendingIdleUntil = a;
1469 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001470 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1471 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1472 mNextWakeFromIdle = a;
1473 // If this wake from idle is earlier than whatever was previously scheduled,
1474 // and we are currently idling, then we need to rebatch alarms in case the idle
1475 // until time needs to be updated.
1476 if (mPendingIdleUntil != null) {
1477 needRebatch = true;
1478 }
1479 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001480 }
1481
1482 if (!rebatching) {
1483 if (DEBUG_VALIDATE) {
1484 if (doValidate && !validateConsistencyLocked()) {
1485 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1486 + " when(hex)=" + Long.toHexString(a.when)
1487 + " whenElapsed=" + a.whenElapsed
1488 + " maxWhenElapsed=" + a.maxWhenElapsed
1489 + " interval=" + a.repeatInterval + " op=" + a.operation
1490 + " flags=0x" + Integer.toHexString(a.flags));
1491 rebatchAllAlarmsLocked(false);
1492 needRebatch = false;
1493 }
1494 }
1495
1496 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001497 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001498 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001499
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001500 rescheduleKernelAlarmsLocked();
1501 updateNextAlarmClockLocked();
1502 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001503 }
1504
Christopher Tate1d99c392017-12-07 16:54:04 -08001505 /**
1506 * System-process internal API
1507 */
1508 private final class LocalService implements AlarmManagerInternal {
1509 @Override
1510 public void removeAlarmsForUid(int uid) {
1511 synchronized (mLock) {
1512 removeLocked(uid);
1513 }
1514 }
1515 }
1516
1517 /**
1518 * Public-facing binder interface
1519 */
Adam Lesinski182f73f2013-12-05 16:48:06 -08001520 private final IBinder mService = new IAlarmManager.Stub() {
1521 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001522 public void set(String callingPackage,
1523 int type, long triggerAtTime, long windowLength, long interval, int flags,
1524 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1525 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001526 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001527
1528 // make sure the caller is not lying about which package should be blamed for
1529 // wakelock time spent in alarm delivery
1530 mAppOps.checkPackage(callingUid, callingPackage);
1531
1532 // Repeating alarms must use PendingIntent, not direct listener
1533 if (interval != 0) {
1534 if (directReceiver != null) {
1535 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1536 }
1537 }
1538
Adam Lesinski182f73f2013-12-05 16:48:06 -08001539 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001540 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001541 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001542 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001543 }
1544
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001545 // No incoming callers can request either WAKE_FROM_IDLE or
1546 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1547 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1548 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1549
1550 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1551 // manager when to come out of idle mode, which is only for DeviceIdleController.
1552 if (callingUid != Process.SYSTEM_UID) {
1553 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1554 }
1555
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001556 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001557 if (windowLength == AlarmManager.WINDOW_EXACT) {
1558 flags |= AlarmManager.FLAG_STANDALONE;
1559 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001560
1561 // If this alarm is for an alarm clock, then it must be standalone and we will
1562 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001563 if (alarmClock != null) {
1564 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001565
1566 // If the caller is a core system component or on the user's whitelist, and not calling
1567 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1568 // This means we will allow these alarms to go off as normal even while idle, with no
1569 // timing restrictions.
1570 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
Christopher Tatebb9cce52017-04-18 14:19:43 -07001571 || callingUid == mSystemUiUid
Makoto Onuki2206af32017-11-21 16:25:35 -08001572 || mForceAppStandbyTracker.isUidPowerSaveWhitelisted(callingUid))) {
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001573 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1574 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001575 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001576
Christopher Tate14a7bb02015-10-01 10:24:31 -07001577 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1578 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001579 }
Christopher Tate89779822012-08-31 14:40:03 -07001580
Adam Lesinski182f73f2013-12-05 16:48:06 -08001581 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001582 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001583 getContext().enforceCallingOrSelfPermission(
1584 "android.permission.SET_TIME",
1585 "setTime");
1586
Greg Hackmann0cab8962014-02-21 16:35:52 -08001587 if (mNativeData == 0) {
1588 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1589 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001590 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001591
1592 synchronized (mLock) {
1593 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001596
1597 @Override
1598 public void setTimeZone(String tz) {
1599 getContext().enforceCallingOrSelfPermission(
1600 "android.permission.SET_TIME_ZONE",
1601 "setTimeZone");
1602
1603 final long oldId = Binder.clearCallingIdentity();
1604 try {
1605 setTimeZoneImpl(tz);
1606 } finally {
1607 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001608 }
1609 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001610
Adam Lesinski182f73f2013-12-05 16:48:06 -08001611 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001612 public void remove(PendingIntent operation, IAlarmListener listener) {
1613 if (operation == null && listener == null) {
1614 Slog.w(TAG, "remove() with no intent or listener");
1615 return;
1616 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001617
Christopher Tate14a7bb02015-10-01 10:24:31 -07001618 synchronized (mLock) {
1619 removeLocked(operation, listener);
1620 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001622
Adam Lesinski182f73f2013-12-05 16:48:06 -08001623 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001624 public long getNextWakeFromIdleTime() {
1625 return getNextWakeFromIdleTimeImpl();
1626 }
1627
1628 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001629 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001630 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1631 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1632 "getNextAlarmClock", null);
1633
1634 return getNextAlarmClockImpl(userId);
1635 }
1636
1637 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001638 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06001639 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Kweku Adams61e03292017-10-19 14:27:12 -07001640
1641 if (args.length > 0 && "--proto".equals(args[0])) {
1642 dumpProto(fd);
1643 } else {
1644 dumpImpl(pw);
1645 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001646 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001647 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001648
Adam Lesinski182f73f2013-12-05 16:48:06 -08001649 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 synchronized (mLock) {
1651 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001652 mConstants.dump(pw);
1653 pw.println();
1654
Makoto Onuki2206af32017-11-21 16:25:35 -08001655 mForceAppStandbyTracker.dump(pw, " ");
Christopher Tate12cf0b62018-01-05 18:40:14 -08001656 pw.println();
Makoto Onuki2206af32017-11-21 16:25:35 -08001657
Christopher Tatee0a22b32013-07-11 14:43:13 -07001658 final long nowRTC = System.currentTimeMillis();
1659 final long nowELAPSED = SystemClock.elapsedRealtime();
Makoto Onuki5d93b832018-01-10 16:12:39 -08001660 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001661
Dianne Hackborna750a632015-06-16 17:18:23 -07001662 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001663 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001664 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001665 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001666 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001667 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001668 pw.print(" mLastTimeChangeRealtime="); pw.println(mLastTimeChangeRealtime);
1669 pw.print(" mLastTickIssued=");
Makoto Onuki5d93b832018-01-10 16:12:39 -08001670 pw.println(sdf.format(new Date(nowRTC - (nowELAPSED - mLastTickIssued))));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001671 pw.print(" mLastTickReceived="); pw.println(sdf.format(new Date(mLastTickReceived)));
1672 pw.print(" mLastTickSet="); pw.println(sdf.format(new Date(mLastTickSet)));
Makoto Onuki5d93b832018-01-10 16:12:39 -08001673 pw.print(" mLastTickAdded="); pw.println(sdf.format(new Date(mLastTickAdded)));
1674 pw.print(" mLastTickRemoved="); pw.println(sdf.format(new Date(mLastTickRemoved)));
Dianne Hackbornc3527222015-05-13 14:03:20 -07001675 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001676 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001677 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001678 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1679 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001680 pw.print(" Max wakeup delay: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001681 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1682 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001683 pw.print(" Time since last dispatch: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001684 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1685 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001686 pw.print(" Next non-wakeup delivery time: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001687 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1688 pw.println();
1689 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001690
1691 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1692 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001693 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001694 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001695 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001696 pw.print(" Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001697 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001698 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
1699 pw.print(" set at "); TimeUtils.formatDuration(mLastWakeupSet, nowELAPSED, pw);
1700 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001701 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001702
John Spurlock604a5ee2015-06-01 12:27:22 -04001703 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001704 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001705 final TreeSet<Integer> users = new TreeSet<>();
1706 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1707 users.add(mNextAlarmClockForUser.keyAt(i));
1708 }
1709 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1710 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1711 }
1712 for (int user : users) {
1713 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1714 final long time = next != null ? next.getTriggerTime() : 0;
1715 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001716 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001717 pw.print(" pendingSend:"); pw.print(pendingSend);
1718 pw.print(" time:"); pw.print(time);
1719 if (time > 0) {
1720 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1721 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1722 }
1723 pw.println();
1724 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001725 if (mAlarmBatches.size() > 0) {
1726 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001727 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001728 pw.println(mAlarmBatches.size());
1729 for (Batch b : mAlarmBatches) {
1730 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001731 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001733 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001734 pw.println();
1735 pw.println(" Pending user blocked background alarms: ");
1736 boolean blocked = false;
1737 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
1738 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
1739 if (blockedAlarms != null && blockedAlarms.size() > 0) {
1740 blocked = true;
1741 dumpAlarmList(pw, blockedAlarms, " ", nowELAPSED, nowRTC, sdf);
1742 }
1743 }
1744 if (!blocked) {
1745 pw.println(" none");
1746 }
Suprabh Shuklac25447d2018-01-19 16:43:35 -08001747 pw.print(" mUseAllowWhileIdleShortTime: [");
1748 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
1749 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
1750 UserHandle.formatUid(pw, mUseAllowWhileIdleShortTime.keyAt(i));
1751 pw.print(" ");
1752 }
1753 }
1754 pw.println("]");
1755
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001756 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001757 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001758 pw.println(" Idle mode state:");
1759 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001760 if (mPendingIdleUntil != null) {
1761 pw.println(mPendingIdleUntil);
Kweku Adams61e03292017-10-19 14:27:12 -07001762 mPendingIdleUntil.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001763 } else {
1764 pw.println("null");
1765 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001766 pw.println(" Pending alarms:");
1767 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001768 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001769 if (mNextWakeFromIdle != null) {
1770 pw.println();
1771 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
Kweku Adams61e03292017-10-19 14:27:12 -07001772 mNextWakeFromIdle.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001773 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001774
1775 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001776 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001777 if (mPendingNonWakeupAlarms.size() > 0) {
1778 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001779 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001780 } else {
1781 pw.println("(none)");
1782 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001783 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001784 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1785 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001786 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001787 pw.print(", max non-interactive time: ");
1788 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1789 pw.println();
1790
1791 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001792 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Christopher Tateeabba732017-08-17 17:12:52 -07001793 pw.print(" PendingIntent send count: "); pw.println(mSendCount);
1794 pw.print(" PendingIntent finish count: "); pw.println(mSendFinishCount);
1795 pw.print(" Listener send count: "); pw.println(mListenerCount);
1796 pw.print(" Listener finish count: "); pw.println(mListenerFinishCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001797 pw.println();
1798
Christopher Tate7f2a0352015-12-08 10:24:33 -08001799 if (mInFlight.size() > 0) {
1800 pw.println("Outstanding deliveries:");
1801 for (int i = 0; i < mInFlight.size(); i++) {
1802 pw.print(" #"); pw.print(i); pw.print(": ");
1803 pw.println(mInFlight.get(i));
1804 }
1805 pw.println();
1806 }
1807
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001808 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001809 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001810 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
1811 pw.print(" UID ");
1812 UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
1813 pw.print(": ");
1814 TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i),
1815 nowELAPSED, pw);
1816 pw.println();
1817 }
1818 }
1819 pw.println();
1820
Dianne Hackborn81038902012-11-26 17:04:09 -08001821 if (mLog.dump(pw, " Recent problems", " ")) {
1822 pw.println();
1823 }
1824
1825 final FilterStats[] topFilters = new FilterStats[10];
1826 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1827 @Override
1828 public int compare(FilterStats lhs, FilterStats rhs) {
1829 if (lhs.aggregateTime < rhs.aggregateTime) {
1830 return 1;
1831 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1832 return -1;
1833 }
1834 return 0;
1835 }
1836 };
1837 int len = 0;
Kweku Adams61e03292017-10-19 14:27:12 -07001838 // Get the top 10 FilterStats, ordered by aggregateTime.
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001839 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1840 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1841 for (int ip=0; ip<uidStats.size(); ip++) {
1842 BroadcastStats bs = uidStats.valueAt(ip);
1843 for (int is=0; is<bs.filterStats.size(); is++) {
1844 FilterStats fs = bs.filterStats.valueAt(is);
1845 int pos = len > 0
1846 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1847 if (pos < 0) {
1848 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001849 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001850 if (pos < topFilters.length) {
1851 int copylen = topFilters.length - pos - 1;
1852 if (copylen > 0) {
1853 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1854 }
1855 topFilters[pos] = fs;
1856 if (len < topFilters.length) {
1857 len++;
1858 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001859 }
1860 }
1861 }
1862 }
1863 if (len > 0) {
1864 pw.println(" Top Alarms:");
1865 for (int i=0; i<len; i++) {
1866 FilterStats fs = topFilters[i];
1867 pw.print(" ");
1868 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1869 TimeUtils.formatDuration(fs.aggregateTime, pw);
1870 pw.print(" running, "); pw.print(fs.numWakeup);
1871 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001872 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1873 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001874 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001875 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001876 pw.println();
1877 }
1878 }
1879
1880 pw.println(" ");
1881 pw.println(" Alarm Stats:");
1882 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001883 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1884 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1885 for (int ip=0; ip<uidStats.size(); ip++) {
1886 BroadcastStats bs = uidStats.valueAt(ip);
1887 pw.print(" ");
1888 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1889 UserHandle.formatUid(pw, bs.mUid);
1890 pw.print(":");
1891 pw.print(bs.mPackageName);
1892 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1893 pw.print(" running, "); pw.print(bs.numWakeup);
1894 pw.println(" wakeups:");
1895 tmpFilters.clear();
1896 for (int is=0; is<bs.filterStats.size(); is++) {
1897 tmpFilters.add(bs.filterStats.valueAt(is));
1898 }
1899 Collections.sort(tmpFilters, comparator);
1900 for (int i=0; i<tmpFilters.size(); i++) {
1901 FilterStats fs = tmpFilters.get(i);
1902 pw.print(" ");
1903 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1904 TimeUtils.formatDuration(fs.aggregateTime, pw);
1905 pw.print(" "); pw.print(fs.numWakeup);
1906 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001907 pw.print(" alarms, last ");
1908 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1909 pw.println(":");
1910 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001911 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001912 pw.println();
1913 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001914 }
1915 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001916
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001917 if (RECORD_DEVICE_IDLE_ALARMS) {
1918 pw.println();
1919 pw.println(" Allow while idle dispatches:");
1920 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
1921 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
1922 pw.print(" ");
1923 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
1924 pw.print(": ");
1925 UserHandle.formatUid(pw, ent.uid);
1926 pw.print(":");
1927 pw.println(ent.pkg);
1928 if (ent.op != null) {
1929 pw.print(" ");
1930 pw.print(ent.op);
1931 pw.print(" / ");
1932 pw.print(ent.tag);
1933 if (ent.argRealtime != 0) {
1934 pw.print(" (");
1935 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
1936 pw.print(")");
1937 }
1938 pw.println();
1939 }
1940 }
1941 }
1942
Christopher Tate18a75f12013-07-01 18:18:59 -07001943 if (WAKEUP_STATS) {
1944 pw.println();
1945 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001946 long last = -1;
1947 for (WakeupEvent event : mRecentWakeups) {
1948 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1949 pw.print('|');
1950 if (last < 0) {
1951 pw.print('0');
1952 } else {
1953 pw.print(event.when - last);
1954 }
1955 last = event.when;
1956 pw.print('|'); pw.print(event.uid);
1957 pw.print('|'); pw.print(event.action);
1958 pw.println();
1959 }
1960 pw.println();
1961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962 }
1963 }
1964
Kweku Adams61e03292017-10-19 14:27:12 -07001965 void dumpProto(FileDescriptor fd) {
1966 final ProtoOutputStream proto = new ProtoOutputStream(fd);
1967
1968 synchronized (mLock) {
1969 final long nowRTC = System.currentTimeMillis();
1970 final long nowElapsed = SystemClock.elapsedRealtime();
1971 proto.write(AlarmManagerServiceProto.CURRENT_TIME, nowRTC);
1972 proto.write(AlarmManagerServiceProto.ELAPSED_REALTIME, nowElapsed);
1973 proto.write(AlarmManagerServiceProto.LAST_TIME_CHANGE_CLOCK_TIME,
1974 mLastTimeChangeClockTime);
1975 proto.write(AlarmManagerServiceProto.LAST_TIME_CHANGE_REALTIME,
1976 mLastTimeChangeRealtime);
1977
1978 mConstants.dumpProto(proto, AlarmManagerServiceProto.SETTINGS);
1979
Makoto Onuki2206af32017-11-21 16:25:35 -08001980 mForceAppStandbyTracker.dumpProto(proto,
1981 AlarmManagerServiceProto.FORCE_APP_STANDBY_TRACKER);
Kweku Adams61e03292017-10-19 14:27:12 -07001982
1983 proto.write(AlarmManagerServiceProto.IS_INTERACTIVE, mInteractive);
1984 if (!mInteractive) {
1985 // Durations
1986 proto.write(AlarmManagerServiceProto.TIME_SINCE_NON_INTERACTIVE_MS,
1987 nowElapsed - mNonInteractiveStartTime);
1988 proto.write(AlarmManagerServiceProto.MAX_WAKEUP_DELAY_MS,
1989 currentNonWakeupFuzzLocked(nowElapsed));
1990 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_DISPATCH_MS,
1991 nowElapsed - mLastAlarmDeliveryTime);
1992 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_NON_WAKEUP_DELIVERY_MS,
1993 nowElapsed - mNextNonWakeupDeliveryTime);
1994 }
1995
1996 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_NON_WAKEUP_ALARM_MS,
1997 mNextNonWakeup - nowElapsed);
1998 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_WAKEUP_MS,
1999 mNextWakeup - nowElapsed);
2000 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_WAKEUP_MS,
2001 nowElapsed - mLastWakeup);
2002 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_WAKEUP_SET_MS,
2003 nowElapsed - mLastWakeupSet);
2004 proto.write(AlarmManagerServiceProto.TIME_CHANGE_EVENT_COUNT, mNumTimeChanged);
Kweku Adams61e03292017-10-19 14:27:12 -07002005
2006 final TreeSet<Integer> users = new TreeSet<>();
2007 final int nextAlarmClockForUserSize = mNextAlarmClockForUser.size();
2008 for (int i = 0; i < nextAlarmClockForUserSize; i++) {
2009 users.add(mNextAlarmClockForUser.keyAt(i));
2010 }
2011 final int pendingSendNextAlarmClockChangedForUserSize =
2012 mPendingSendNextAlarmClockChangedForUser.size();
2013 for (int i = 0; i < pendingSendNextAlarmClockChangedForUserSize; i++) {
2014 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2015 }
2016 for (int user : users) {
2017 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2018 final long time = next != null ? next.getTriggerTime() : 0;
2019 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
2020 final long aToken = proto.start(AlarmManagerServiceProto.NEXT_ALARM_CLOCK_METADATA);
2021 proto.write(AlarmClockMetadataProto.USER, user);
2022 proto.write(AlarmClockMetadataProto.IS_PENDING_SEND, pendingSend);
2023 proto.write(AlarmClockMetadataProto.TRIGGER_TIME_MS, time);
2024 proto.end(aToken);
2025 }
2026 for (Batch b : mAlarmBatches) {
2027 b.writeToProto(proto, AlarmManagerServiceProto.PENDING_ALARM_BATCHES,
2028 nowElapsed, nowRTC);
2029 }
2030 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2031 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2032 if (blockedAlarms != null) {
2033 for (Alarm a : blockedAlarms) {
2034 a.writeToProto(proto,
2035 AlarmManagerServiceProto.PENDING_USER_BLOCKED_BACKGROUND_ALARMS,
2036 nowElapsed, nowRTC);
2037 }
2038 }
2039 }
2040 if (mPendingIdleUntil != null) {
2041 mPendingIdleUntil.writeToProto(
2042 proto, AlarmManagerServiceProto.PENDING_IDLE_UNTIL, nowElapsed, nowRTC);
2043 }
2044 for (Alarm a : mPendingWhileIdleAlarms) {
2045 a.writeToProto(proto, AlarmManagerServiceProto.PENDING_WHILE_IDLE_ALARMS,
2046 nowElapsed, nowRTC);
2047 }
2048 if (mNextWakeFromIdle != null) {
2049 mNextWakeFromIdle.writeToProto(proto, AlarmManagerServiceProto.NEXT_WAKE_FROM_IDLE,
2050 nowElapsed, nowRTC);
2051 }
2052
2053 for (Alarm a : mPendingNonWakeupAlarms) {
2054 a.writeToProto(proto, AlarmManagerServiceProto.PAST_DUE_NON_WAKEUP_ALARMS,
2055 nowElapsed, nowRTC);
2056 }
2057
2058 proto.write(AlarmManagerServiceProto.DELAYED_ALARM_COUNT, mNumDelayedAlarms);
2059 proto.write(AlarmManagerServiceProto.TOTAL_DELAY_TIME_MS, mTotalDelayTime);
2060 proto.write(AlarmManagerServiceProto.MAX_DELAY_DURATION_MS, mMaxDelayTime);
2061 proto.write(AlarmManagerServiceProto.MAX_NON_INTERACTIVE_DURATION_MS,
2062 mNonInteractiveTime);
2063
2064 proto.write(AlarmManagerServiceProto.BROADCAST_REF_COUNT, mBroadcastRefCount);
2065 proto.write(AlarmManagerServiceProto.PENDING_INTENT_SEND_COUNT, mSendCount);
2066 proto.write(AlarmManagerServiceProto.PENDING_INTENT_FINISH_COUNT, mSendFinishCount);
2067 proto.write(AlarmManagerServiceProto.LISTENER_SEND_COUNT, mListenerCount);
2068 proto.write(AlarmManagerServiceProto.LISTENER_FINISH_COUNT, mListenerFinishCount);
2069
2070 for (InFlight f : mInFlight) {
2071 f.writeToProto(proto, AlarmManagerServiceProto.OUTSTANDING_DELIVERIES);
2072 }
2073
Kweku Adams61e03292017-10-19 14:27:12 -07002074 for (int i = 0; i < mLastAllowWhileIdleDispatch.size(); ++i) {
2075 final long token = proto.start(
2076 AlarmManagerServiceProto.LAST_ALLOW_WHILE_IDLE_DISPATCH_TIMES);
2077 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.UID,
2078 mLastAllowWhileIdleDispatch.keyAt(i));
2079 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.TIME_MS,
2080 mLastAllowWhileIdleDispatch.valueAt(i));
2081 proto.end(token);
2082 }
2083
2084 mLog.writeToProto(proto, AlarmManagerServiceProto.RECENT_PROBLEMS);
2085
2086 final FilterStats[] topFilters = new FilterStats[10];
2087 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2088 @Override
2089 public int compare(FilterStats lhs, FilterStats rhs) {
2090 if (lhs.aggregateTime < rhs.aggregateTime) {
2091 return 1;
2092 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2093 return -1;
2094 }
2095 return 0;
2096 }
2097 };
2098 int len = 0;
2099 // Get the top 10 FilterStats, ordered by aggregateTime.
2100 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2101 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2102 for (int ip = 0; ip < uidStats.size(); ++ip) {
2103 BroadcastStats bs = uidStats.valueAt(ip);
2104 for (int is = 0; is < bs.filterStats.size(); ++is) {
2105 FilterStats fs = bs.filterStats.valueAt(is);
2106 int pos = len > 0
2107 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2108 if (pos < 0) {
2109 pos = -pos - 1;
2110 }
2111 if (pos < topFilters.length) {
2112 int copylen = topFilters.length - pos - 1;
2113 if (copylen > 0) {
2114 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2115 }
2116 topFilters[pos] = fs;
2117 if (len < topFilters.length) {
2118 len++;
2119 }
2120 }
2121 }
2122 }
2123 }
2124 for (int i = 0; i < len; ++i) {
2125 final long token = proto.start(AlarmManagerServiceProto.TOP_ALARMS);
2126 FilterStats fs = topFilters[i];
2127
2128 proto.write(AlarmManagerServiceProto.TopAlarm.UID, fs.mBroadcastStats.mUid);
2129 proto.write(AlarmManagerServiceProto.TopAlarm.PACKAGE_NAME,
2130 fs.mBroadcastStats.mPackageName);
2131 fs.writeToProto(proto, AlarmManagerServiceProto.TopAlarm.FILTER);
2132
2133 proto.end(token);
2134 }
2135
2136 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
2137 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2138 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2139 for (int ip = 0; ip < uidStats.size(); ++ip) {
2140 final long token = proto.start(AlarmManagerServiceProto.ALARM_STATS);
2141
2142 BroadcastStats bs = uidStats.valueAt(ip);
2143 bs.writeToProto(proto, AlarmManagerServiceProto.AlarmStat.BROADCAST);
2144
2145 // uidStats is an ArrayMap, which we can't sort.
2146 tmpFilters.clear();
2147 for (int is = 0; is < bs.filterStats.size(); ++is) {
2148 tmpFilters.add(bs.filterStats.valueAt(is));
2149 }
2150 Collections.sort(tmpFilters, comparator);
2151 for (FilterStats fs : tmpFilters) {
2152 fs.writeToProto(proto, AlarmManagerServiceProto.AlarmStat.FILTERS);
2153 }
2154
2155 proto.end(token);
2156 }
2157 }
2158
2159 if (RECORD_DEVICE_IDLE_ALARMS) {
2160 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2161 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2162 final long token = proto.start(
2163 AlarmManagerServiceProto.ALLOW_WHILE_IDLE_DISPATCHES);
2164
2165 proto.write(IdleDispatchEntryProto.UID, ent.uid);
2166 proto.write(IdleDispatchEntryProto.PKG, ent.pkg);
2167 proto.write(IdleDispatchEntryProto.TAG, ent.tag);
2168 proto.write(IdleDispatchEntryProto.OP, ent.op);
2169 proto.write(IdleDispatchEntryProto.ENTRY_CREATION_REALTIME,
2170 ent.elapsedRealtime);
2171 proto.write(IdleDispatchEntryProto.ARG_REALTIME, ent.argRealtime);
2172
2173 proto.end(token);
2174 }
2175 }
2176
2177 if (WAKEUP_STATS) {
2178 for (WakeupEvent event : mRecentWakeups) {
2179 final long token = proto.start(AlarmManagerServiceProto.RECENT_WAKEUP_HISTORY);
2180 proto.write(WakeupEventProto.UID, event.uid);
2181 proto.write(WakeupEventProto.ACTION, event.action);
2182 proto.write(WakeupEventProto.WHEN, event.when);
2183 proto.end(token);
2184 }
2185 }
2186 }
2187
2188 proto.flush();
2189 }
2190
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002191 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002192 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
2193 PrintWriter pw = new PrintWriter(bs);
2194 final long nowRTC = System.currentTimeMillis();
2195 final long nowELAPSED = SystemClock.elapsedRealtime();
2196 final int NZ = mAlarmBatches.size();
2197 for (int iz = 0; iz < NZ; iz++) {
2198 Batch bz = mAlarmBatches.get(iz);
2199 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002200 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002201 pw.flush();
2202 Slog.v(TAG, bs.toString());
2203 bs.reset();
2204 }
2205 }
2206
2207 private boolean validateConsistencyLocked() {
2208 if (DEBUG_VALIDATE) {
2209 long lastTime = Long.MIN_VALUE;
2210 final int N = mAlarmBatches.size();
2211 for (int i = 0; i < N; i++) {
2212 Batch b = mAlarmBatches.get(i);
2213 if (b.start >= lastTime) {
2214 // duplicate start times are okay because of standalone batches
2215 lastTime = b.start;
2216 } else {
2217 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002218 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2219 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002220 return false;
2221 }
2222 }
2223 }
2224 return true;
2225 }
2226
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002227 private Batch findFirstWakeupBatchLocked() {
2228 final int N = mAlarmBatches.size();
2229 for (int i = 0; i < N; i++) {
2230 Batch b = mAlarmBatches.get(i);
2231 if (b.hasWakeups()) {
2232 return b;
2233 }
2234 }
2235 return null;
2236 }
2237
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002238 long getNextWakeFromIdleTimeImpl() {
2239 synchronized (mLock) {
2240 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
2241 }
2242 }
2243
2244 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002245 synchronized (mLock) {
2246 return mNextAlarmClockForUser.get(userId);
2247 }
2248 }
2249
2250 /**
2251 * Recomputes the next alarm clock for all users.
2252 */
2253 private void updateNextAlarmClockLocked() {
2254 if (!mNextAlarmClockMayChange) {
2255 return;
2256 }
2257 mNextAlarmClockMayChange = false;
2258
Jose Lima235510e2014-08-13 12:50:01 -07002259 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002260 nextForUser.clear();
2261
2262 final int N = mAlarmBatches.size();
2263 for (int i = 0; i < N; i++) {
2264 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
2265 final int M = alarms.size();
2266
2267 for (int j = 0; j < M; j++) {
2268 Alarm a = alarms.get(j);
2269 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002270 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07002271 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002272
2273 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07002274 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002275 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02002276 " for user " + userId);
2277 }
2278
2279 // Alarms and batches are sorted by time, no need to compare times here.
2280 if (nextForUser.get(userId) == null) {
2281 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07002282 } else if (a.alarmClock.equals(current)
2283 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
2284 // same/earlier time and it's the one we cited before, so stick with it
2285 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002286 }
2287 }
2288 }
2289 }
2290
2291 // Update mNextAlarmForUser with new values.
2292 final int NN = nextForUser.size();
2293 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07002294 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002295 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002296 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002297 if (!newAlarm.equals(currentAlarm)) {
2298 updateNextAlarmInfoForUserLocked(userId, newAlarm);
2299 }
2300 }
2301
2302 // Remove users without any alarm clocks scheduled.
2303 final int NNN = mNextAlarmClockForUser.size();
2304 for (int i = NNN - 1; i >= 0; i--) {
2305 int userId = mNextAlarmClockForUser.keyAt(i);
2306 if (nextForUser.get(userId) == null) {
2307 updateNextAlarmInfoForUserLocked(userId, null);
2308 }
2309 }
2310 }
2311
Jose Lima235510e2014-08-13 12:50:01 -07002312 private void updateNextAlarmInfoForUserLocked(int userId,
2313 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002314 if (alarmClock != null) {
2315 if (DEBUG_ALARM_CLOCK) {
2316 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002317 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02002318 }
2319 mNextAlarmClockForUser.put(userId, alarmClock);
2320 } else {
2321 if (DEBUG_ALARM_CLOCK) {
2322 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
2323 }
2324 mNextAlarmClockForUser.remove(userId);
2325 }
2326
2327 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
2328 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2329 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2330 }
2331
2332 /**
2333 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
2334 * for which alarm clocks have changed since the last call to this.
2335 *
2336 * Do not call with a lock held. Only call from mHandler's thread.
2337 *
2338 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
2339 */
2340 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07002341 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002342 pendingUsers.clear();
2343
2344 synchronized (mLock) {
2345 final int N = mPendingSendNextAlarmClockChangedForUser.size();
2346 for (int i = 0; i < N; i++) {
2347 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
2348 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
2349 }
2350 mPendingSendNextAlarmClockChangedForUser.clear();
2351 }
2352
2353 final int N = pendingUsers.size();
2354 for (int i = 0; i < N; i++) {
2355 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002356 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002357 Settings.System.putStringForUser(getContext().getContentResolver(),
2358 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01002359 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02002360 userId);
2361
2362 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
2363 new UserHandle(userId));
2364 }
2365 }
2366
2367 /**
2368 * Formats an alarm like platform/packages/apps/DeskClock used to.
2369 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01002370 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
2371 int userId) {
2372 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02002373 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
2374 return (info == null) ? "" :
2375 DateFormat.format(pattern, info.getTriggerTime()).toString();
2376 }
2377
Adam Lesinski182f73f2013-12-05 16:48:06 -08002378 void rescheduleKernelAlarmsLocked() {
2379 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
2380 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002381 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002382 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002383 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002384 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07002385 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002386 mNextWakeup = firstWakeup.start;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002387 mLastWakeupSet = SystemClock.elapsedRealtime();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002388 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002389 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002390 if (firstBatch != firstWakeup) {
2391 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002392 }
2393 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002394 if (mPendingNonWakeupAlarms.size() > 0) {
2395 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
2396 nextNonWakeup = mNextNonWakeupDeliveryTime;
2397 }
2398 }
Prashant Malani753e9e02015-06-10 17:43:49 -07002399 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002400 mNextNonWakeup = nextNonWakeup;
2401 setLocked(ELAPSED_REALTIME, nextNonWakeup);
2402 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002403 }
2404
Christopher Tate14a7bb02015-10-01 10:24:31 -07002405 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Christopher Tate1d99c392017-12-07 16:54:04 -08002406 if (operation == null && directReceiver == null) {
2407 if (localLOGV) {
2408 Slog.w(TAG, "requested remove() of null operation",
2409 new RuntimeException("here"));
2410 }
2411 return;
2412 }
2413
Adam Lesinski182f73f2013-12-05 16:48:06 -08002414 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002415 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002416 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2417 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002418 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002419 if (b.size() == 0) {
2420 mAlarmBatches.remove(i);
2421 }
2422 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002423 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002424 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002425 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2426 mPendingWhileIdleAlarms.remove(i);
2427 }
2428 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002429 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2430 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2431 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2432 if (alarmsForUid.get(j).matches(operation, directReceiver)) {
2433 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2434 alarmsForUid.remove(j);
2435 }
2436 }
2437 if (alarmsForUid.size() == 0) {
2438 mPendingBackgroundAlarms.removeAt(i);
2439 }
2440 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002441 if (didRemove) {
2442 if (DEBUG_BATCH) {
2443 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
2444 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002445 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002446 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002447 mPendingIdleUntil = null;
2448 restorePending = true;
2449 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002450 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002451 mNextWakeFromIdle = null;
2452 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002453 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002454 if (restorePending) {
2455 restorePendingWhileIdleAlarmsLocked();
2456 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002457 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002458 }
2459 }
2460
Christopher Tate1d99c392017-12-07 16:54:04 -08002461 void removeLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002462 if (uid == Process.SYSTEM_UID) {
2463 Slog.wtf(TAG, "removeLocked: Shouldn't for UID=" + uid);
2464 return;
2465 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002466 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002467 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.uid == uid;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002468 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2469 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002470 didRemove |= b.remove(whichAlarms);
2471 if (b.size() == 0) {
2472 mAlarmBatches.remove(i);
2473 }
2474 }
2475 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2476 final Alarm a = mPendingWhileIdleAlarms.get(i);
2477 if (a.uid == uid) {
2478 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2479 mPendingWhileIdleAlarms.remove(i);
2480 }
2481 }
2482 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2483 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2484 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2485 if (alarmsForUid.get(j).uid == uid) {
2486 alarmsForUid.remove(j);
2487 }
2488 }
2489 if (alarmsForUid.size() == 0) {
2490 mPendingBackgroundAlarms.removeAt(i);
2491 }
2492 }
2493 if (didRemove) {
2494 if (DEBUG_BATCH) {
2495 Slog.v(TAG, "remove(uid) changed bounds; rebatching");
2496 }
2497 rebatchAllAlarmsLocked(true);
2498 rescheduleKernelAlarmsLocked();
2499 updateNextAlarmClockLocked();
2500 }
2501 }
2502
2503 void removeLocked(final String packageName) {
2504 if (packageName == null) {
2505 if (localLOGV) {
2506 Slog.w(TAG, "requested remove() of null packageName",
2507 new RuntimeException("here"));
2508 }
2509 return;
2510 }
2511
2512 boolean didRemove = false;
2513 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(packageName);
Makoto Onuki5d93b832018-01-10 16:12:39 -08002514 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
Christopher Tate1d99c392017-12-07 16:54:04 -08002515 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2516 Batch b = mAlarmBatches.get(i);
2517 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002518 if (b.size() == 0) {
2519 mAlarmBatches.remove(i);
2520 }
2521 }
Makoto Onuki5d93b832018-01-10 16:12:39 -08002522 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
2523 if (oldHasTick != newHasTick) {
2524 Slog.wtf(TAG, "removeLocked: hasTick changed from " + oldHasTick + " to " + newHasTick);
2525 }
2526
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002527 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002528 final Alarm a = mPendingWhileIdleAlarms.get(i);
2529 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002530 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2531 mPendingWhileIdleAlarms.remove(i);
2532 }
2533 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002534 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2535 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2536 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2537 if (alarmsForUid.get(j).matches(packageName)) {
2538 alarmsForUid.remove(j);
2539 }
2540 }
2541 if (alarmsForUid.size() == 0) {
2542 mPendingBackgroundAlarms.removeAt(i);
2543 }
2544 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002545 if (didRemove) {
2546 if (DEBUG_BATCH) {
2547 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2548 }
2549 rebatchAllAlarmsLocked(true);
2550 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002551 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002552 }
2553 }
2554
Christopher Tate1d99c392017-12-07 16:54:04 -08002555 void removeForStoppedLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002556 if (uid == Process.SYSTEM_UID) {
2557 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for UID=" + uid);
2558 return;
2559 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002560 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002561 final Predicate<Alarm> whichAlarms = (Alarm a) -> {
2562 try {
2563 if (a.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
2564 uid, a.packageName)) {
2565 return true;
2566 }
2567 } catch (RemoteException e) { /* fall through */}
2568 return false;
2569 };
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002570 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2571 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002572 didRemove |= b.remove(whichAlarms);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002573 if (b.size() == 0) {
2574 mAlarmBatches.remove(i);
2575 }
2576 }
2577 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2578 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08002579 if (a.uid == uid) {
2580 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2581 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002582 }
2583 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002584 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2585 if (mPendingBackgroundAlarms.keyAt(i) == uid) {
2586 mPendingBackgroundAlarms.removeAt(i);
2587 }
2588 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002589 if (didRemove) {
2590 if (DEBUG_BATCH) {
2591 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2592 }
2593 rebatchAllAlarmsLocked(true);
2594 rescheduleKernelAlarmsLocked();
2595 updateNextAlarmClockLocked();
2596 }
2597 }
2598
Adam Lesinski182f73f2013-12-05 16:48:06 -08002599 void removeUserLocked(int userHandle) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002600 if (userHandle == UserHandle.USER_SYSTEM) {
2601 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for user=" + userHandle);
2602 return;
2603 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002604 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002605 final Predicate<Alarm> whichAlarms =
2606 (Alarm a) -> UserHandle.getUserId(a.creatorUid) == userHandle;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002607 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2608 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002609 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002610 if (b.size() == 0) {
2611 mAlarmBatches.remove(i);
2612 }
2613 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002614 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002615 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002616 == userHandle) {
2617 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2618 mPendingWhileIdleAlarms.remove(i);
2619 }
2620 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002621 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2622 if (UserHandle.getUserId(mPendingBackgroundAlarms.keyAt(i)) == userHandle) {
2623 mPendingBackgroundAlarms.removeAt(i);
2624 }
2625 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002626 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
2627 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
2628 mLastAllowWhileIdleDispatch.removeAt(i);
2629 }
2630 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002631
2632 if (didRemove) {
2633 if (DEBUG_BATCH) {
2634 Slog.v(TAG, "remove(user) changed bounds; rebatching");
2635 }
2636 rebatchAllAlarmsLocked(true);
2637 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002638 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002639 }
2640 }
2641
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002642 void interactiveStateChangedLocked(boolean interactive) {
2643 if (mInteractive != interactive) {
2644 mInteractive = interactive;
2645 final long nowELAPSED = SystemClock.elapsedRealtime();
2646 if (interactive) {
2647 if (mPendingNonWakeupAlarms.size() > 0) {
2648 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2649 mTotalDelayTime += thisDelayTime;
2650 if (mMaxDelayTime < thisDelayTime) {
2651 mMaxDelayTime = thisDelayTime;
2652 }
2653 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2654 mPendingNonWakeupAlarms.clear();
2655 }
2656 if (mNonInteractiveStartTime > 0) {
2657 long dur = nowELAPSED - mNonInteractiveStartTime;
2658 if (dur > mNonInteractiveTime) {
2659 mNonInteractiveTime = dur;
2660 }
2661 }
2662 } else {
2663 mNonInteractiveStartTime = nowELAPSED;
2664 }
2665 }
2666 }
2667
Adam Lesinski182f73f2013-12-05 16:48:06 -08002668 boolean lookForPackageLocked(String packageName) {
2669 for (int i = 0; i < mAlarmBatches.size(); i++) {
2670 Batch b = mAlarmBatches.get(i);
2671 if (b.hasPackage(packageName)) {
2672 return true;
2673 }
2674 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002675 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002676 final Alarm a = mPendingWhileIdleAlarms.get(i);
2677 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002678 return true;
2679 }
2680 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002681 return false;
2682 }
2683
2684 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002685 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002686 // The kernel never triggers alarms with negative wakeup times
2687 // so we ensure they are positive.
2688 long alarmSeconds, alarmNanoseconds;
2689 if (when < 0) {
2690 alarmSeconds = 0;
2691 alarmNanoseconds = 0;
2692 } else {
2693 alarmSeconds = when / 1000;
2694 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2695 }
Kweku Adams61e03292017-10-19 14:27:12 -07002696
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002697 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002698 } else {
2699 Message msg = Message.obtain();
2700 msg.what = ALARM_EVENT;
Kweku Adams61e03292017-10-19 14:27:12 -07002701
Adam Lesinski182f73f2013-12-05 16:48:06 -08002702 mHandler.removeMessages(ALARM_EVENT);
2703 mHandler.sendMessageAtTime(msg, when);
2704 }
2705 }
2706
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002707 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Kweku Adams61e03292017-10-19 14:27:12 -07002708 String prefix, String label, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002709 for (int i=list.size()-1; i>=0; i--) {
2710 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002711 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2712 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002713 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002714 }
2715 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002716
2717 private static final String labelForType(int type) {
2718 switch (type) {
2719 case RTC: return "RTC";
2720 case RTC_WAKEUP : return "RTC_WAKEUP";
2721 case ELAPSED_REALTIME : return "ELAPSED";
2722 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
Christopher Tatee0a22b32013-07-11 14:43:13 -07002723 }
2724 return "--unknown--";
2725 }
2726
2727 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002728 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002729 for (int i=list.size()-1; i>=0; i--) {
2730 Alarm a = list.get(i);
2731 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002732 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2733 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002734 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002735 }
2736 }
2737
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002738 private boolean isBackgroundRestricted(Alarm alarm) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08002739 final boolean allowWhileIdle = (alarm.flags & FLAG_ALLOW_WHILE_IDLE) != 0;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002740 if (alarm.alarmClock != null) {
2741 // Don't block alarm clocks
2742 return false;
2743 }
2744 if (alarm.operation != null
2745 && (alarm.operation.isActivity() || alarm.operation.isForegroundService())) {
2746 // Don't block starting foreground components
2747 return false;
2748 }
2749 final String sourcePackage =
2750 (alarm.operation != null) ? alarm.operation.getCreatorPackage() : alarm.packageName;
2751 final int sourceUid = alarm.creatorUid;
Suprabh Shuklac25447d2018-01-19 16:43:35 -08002752 return mForceAppStandbyTracker.areAlarmsRestricted(sourceUid, sourcePackage,
2753 allowWhileIdle);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002754 }
2755
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002756 private native long init();
2757 private native void close(long nativeData);
2758 private native void set(long nativeData, int type, long seconds, long nanoseconds);
2759 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08002760 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002761 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002762
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002763 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002764 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002765 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002766 // batches are temporally sorted, so we need only pull from the
2767 // start of the list until we either empty it or hit a batch
2768 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07002769 while (mAlarmBatches.size() > 0) {
2770 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002771 if (batch.start > nowELAPSED) {
2772 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002773 break;
2774 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002775
Christopher Tatee0a22b32013-07-11 14:43:13 -07002776 // We will (re)schedule some alarms now; don't let that interfere
2777 // with delivery of this current batch
2778 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002779
Christopher Tatee0a22b32013-07-11 14:43:13 -07002780 final int N = batch.size();
2781 for (int i = 0; i < N; i++) {
2782 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002783
2784 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
2785 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
2786 // schedule such alarms.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08002787 final long lastTime = mLastAllowWhileIdleDispatch.get(alarm.creatorUid, 0);
2788 final boolean dozing = mPendingIdleUntil != null;
2789 final boolean ebs = mForceAppStandbyTracker.isForceAllAppsStandbyEnabled();
2790 final long minTime;
2791 if (!dozing && !ebs) {
2792 minTime = lastTime + mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
2793 } else if (dozing) {
2794 minTime = lastTime + mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
2795 } else if (mUseAllowWhileIdleShortTime.get(alarm.creatorUid)) {
2796 // if the last allow-while-idle went off while uid was fg, or the uid
2797 // recently came into fg, don't block the alarm for long.
2798 minTime = lastTime + mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
2799 } else {
2800 minTime = lastTime + mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
2801 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002802 if (nowELAPSED < minTime) {
2803 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
2804 // alarm went off for this app. Reschedule the alarm to be in the
2805 // correct time period.
2806 alarm.whenElapsed = minTime;
2807 if (alarm.maxWhenElapsed < minTime) {
2808 alarm.maxWhenElapsed = minTime;
2809 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002810 if (RECORD_DEVICE_IDLE_ALARMS) {
2811 IdleDispatchEntry ent = new IdleDispatchEntry();
2812 ent.uid = alarm.uid;
2813 ent.pkg = alarm.operation.getCreatorPackage();
2814 ent.tag = alarm.operation.getTag("");
2815 ent.op = "RESCHEDULE";
2816 ent.elapsedRealtime = nowELAPSED;
2817 ent.argRealtime = lastTime;
2818 mAllowWhileIdleDispatches.add(ent);
2819 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002820 setImplLocked(alarm, true, false);
2821 continue;
2822 }
2823 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002824 if (isBackgroundRestricted(alarm)) {
2825 // Alarms with FLAG_WAKE_FROM_IDLE or mPendingIdleUntil alarm are not deferred
2826 if (DEBUG_BG_LIMIT) {
2827 Slog.d(TAG, "Deferring alarm " + alarm + " due to user forced app standby");
2828 }
2829 ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(alarm.creatorUid);
2830 if (alarmsForUid == null) {
2831 alarmsForUid = new ArrayList<>();
2832 mPendingBackgroundAlarms.put(alarm.creatorUid, alarmsForUid);
2833 }
2834 alarmsForUid.add(alarm);
2835 continue;
2836 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002837
Christopher Tatee0a22b32013-07-11 14:43:13 -07002838 alarm.count = 1;
2839 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002840 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
2841 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002842 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002843 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002844 if (mPendingIdleUntil == alarm) {
2845 mPendingIdleUntil = null;
2846 rebatchAllAlarmsLocked(false);
2847 restorePendingWhileIdleAlarmsLocked();
2848 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002849 if (mNextWakeFromIdle == alarm) {
2850 mNextWakeFromIdle = null;
2851 rebatchAllAlarmsLocked(false);
2852 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002853
2854 // Recurring alarms may have passed several alarm intervals while the
2855 // phone was asleep or off, so pass a trigger count when sending them.
2856 if (alarm.repeatInterval > 0) {
2857 // this adjustment will be zero if we're late by
2858 // less than one full repeat interval
2859 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
2860
2861 // Also schedule its next recurrence
2862 final long delta = alarm.count * alarm.repeatInterval;
2863 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07002864 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07002865 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07002866 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
2867 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08002868 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002869
Christopher Tate864d42e2014-12-02 11:48:53 -08002870 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002871 hasWakeup = true;
2872 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002873
2874 // We removed an alarm clock. Let the caller recompute the next alarm clock.
2875 if (alarm.alarmClock != null) {
2876 mNextAlarmClockMayChange = true;
2877 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07002878 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002879 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002880
Christopher Tate1590f1e2014-10-02 17:27:57 -07002881 // This is a new alarm delivery set; bump the sequence number to indicate that
2882 // all apps' alarm delivery classes should be recalculated.
2883 mCurrentSeq++;
2884 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002885 Collections.sort(triggerList, mAlarmDispatchComparator);
2886
2887 if (localLOGV) {
2888 for (int i=0; i<triggerList.size(); i++) {
2889 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
2890 }
2891 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002892
2893 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002894 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002895
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002896 /**
2897 * This Comparator sorts Alarms into increasing time order.
2898 */
2899 public static class IncreasingTimeOrder implements Comparator<Alarm> {
2900 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09002901 long when1 = a1.whenElapsed;
2902 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002903 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002904 return 1;
2905 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002906 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002907 return -1;
2908 }
2909 return 0;
2910 }
2911 }
Kweku Adams61e03292017-10-19 14:27:12 -07002912
Makoto Onuki2206af32017-11-21 16:25:35 -08002913 @VisibleForTesting
2914 static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002915 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002916 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002917 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002918 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002919 public final IAlarmListener listener;
2920 public final String listenerTag;
2921 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002922 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002923 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002924 public final AlarmManager.AlarmClockInfo alarmClock;
2925 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002926 public final int creatorUid;
2927 public final String packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002928 public int count;
2929 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07002930 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002931 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002932 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002933 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07002934 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002935
Christopher Tate3e04b472013-10-21 17:51:31 -07002936 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002937 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
2938 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
2939 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002940 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002941 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002942 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
2943 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002944 when = _when;
2945 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07002946 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002947 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002948 repeatInterval = _interval;
2949 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002950 listener = _rec;
2951 listenerTag = _listenerTag;
2952 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07002953 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002954 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002955 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002956 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002957 packageName = _pkgName;
2958
2959 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002960 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002961
Christopher Tate14a7bb02015-10-01 10:24:31 -07002962 public static String makeTag(PendingIntent pi, String tag, int type) {
2963 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
2964 ? "*walarm*:" : "*alarm*:";
2965 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
2966 }
2967
2968 public WakeupEvent makeWakeupEvent(long nowRTC) {
2969 return new WakeupEvent(nowRTC, creatorUid,
2970 (operation != null)
2971 ? operation.getIntent().getAction()
2972 : ("<listener>:" + listenerTag));
2973 }
2974
2975 // Returns true if either matches
2976 public boolean matches(PendingIntent pi, IAlarmListener rec) {
2977 return (operation != null)
2978 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09002979 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07002980 }
2981
2982 public boolean matches(String packageName) {
2983 return (operation != null)
2984 ? packageName.equals(operation.getTargetPackage())
2985 : packageName.equals(this.packageName);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002986 }
2987
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002988 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002989 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002990 StringBuilder sb = new StringBuilder(128);
2991 sb.append("Alarm{");
2992 sb.append(Integer.toHexString(System.identityHashCode(this)));
2993 sb.append(" type ");
2994 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002995 sb.append(" when ");
2996 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002997 sb.append(" ");
Christopher Tate14a7bb02015-10-01 10:24:31 -07002998 if (operation != null) {
2999 sb.append(operation.getTargetPackage());
3000 } else {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07003001 sb.append(packageName);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003002 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003003 sb.append('}');
3004 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003005 }
3006
Kweku Adams61e03292017-10-19 14:27:12 -07003007 public void dump(PrintWriter pw, String prefix, long nowELAPSED, long nowRTC,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003008 SimpleDateFormat sdf) {
3009 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003010 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003011 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003012 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
3013 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003014 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003015 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003016 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003017 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003018 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003019 }
3020 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003021 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003022 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003023 pw.print(" count="); pw.print(count);
3024 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003025 if (alarmClock != null) {
3026 pw.print(prefix); pw.println("Alarm clock:");
3027 pw.print(prefix); pw.print(" triggerTime=");
3028 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
3029 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
3030 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003031 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003032 if (listener != null) {
3033 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
3034 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003035 }
Kweku Adams61e03292017-10-19 14:27:12 -07003036
3037 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
3038 long nowRTC) {
3039 final long token = proto.start(fieldId);
3040
3041 proto.write(AlarmProto.TAG, statsTag);
3042 proto.write(AlarmProto.TYPE, type);
Kweku Adams923ec432017-12-11 18:05:38 -08003043 proto.write(AlarmProto.TIME_UNTIL_WHEN_ELAPSED_MS, whenElapsed - nowElapsed);
Kweku Adams61e03292017-10-19 14:27:12 -07003044 proto.write(AlarmProto.WINDOW_LENGTH_MS, windowLength);
3045 proto.write(AlarmProto.REPEAT_INTERVAL_MS, repeatInterval);
3046 proto.write(AlarmProto.COUNT, count);
3047 proto.write(AlarmProto.FLAGS, flags);
3048 if (alarmClock != null) {
3049 alarmClock.writeToProto(proto, AlarmProto.ALARM_CLOCK);
3050 }
3051 if (operation != null) {
3052 operation.writeToProto(proto, AlarmProto.OPERATION);
3053 }
3054 if (listener != null) {
3055 proto.write(AlarmProto.LISTENER, listener.asBinder().toString());
3056 }
3057
3058 proto.end(token);
3059 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003060 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003061
Christopher Tatee0a22b32013-07-11 14:43:13 -07003062 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
3063 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003064 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
3065 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003066 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07003067 break;
3068 }
3069
Christopher Tatee0a22b32013-07-11 14:43:13 -07003070 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003071 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
3072 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003073 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07003074 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003075 }
3076 }
3077
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003078 long currentNonWakeupFuzzLocked(long nowELAPSED) {
3079 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
3080 if (timeSinceOn < 5*60*1000) {
3081 // If the screen has been off for 5 minutes, only delay by at most two minutes.
3082 return 2*60*1000;
3083 } else if (timeSinceOn < 30*60*1000) {
3084 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
3085 return 15*60*1000;
3086 } else {
3087 // Otherwise, we will delay by at most an hour.
3088 return 60*60*1000;
3089 }
3090 }
3091
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003092 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003093 if (duration < 15*60*1000) {
3094 // If the duration until the time is less than 15 minutes, the maximum fuzz
3095 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003096 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003097 } else if (duration < 90*60*1000) {
3098 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
3099 return 15*60*1000;
3100 } else {
3101 // Otherwise, we will fuzz by at most half an hour.
3102 return 30*60*1000;
3103 }
3104 }
3105
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003106 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
3107 if (mInteractive) {
3108 return false;
3109 }
3110 if (mLastAlarmDeliveryTime <= 0) {
3111 return false;
3112 }
minho.choo649acab2014-12-12 16:13:55 +09003113 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003114 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
3115 // and the next delivery time is in the past, then just deliver them all. This
3116 // avoids bugs where we get stuck in a loop trying to poll for alarms.
3117 return false;
3118 }
3119 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
3120 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
3121 }
3122
3123 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
3124 mLastAlarmDeliveryTime = nowELAPSED;
3125 for (int i=0; i<triggerList.size(); i++) {
3126 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07003127 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Tim Murray175c0f92017-11-28 15:01:04 -08003128 if (alarm.wakeup) {
3129 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch wakeup alarm to " + alarm.packageName);
3130 } else {
3131 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch non-wakeup alarm to " + alarm.packageName);
3132 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003133 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07003134 if (localLOGV) {
3135 Slog.v(TAG, "sending alarm " + alarm);
3136 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07003137 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003138 ActivityManager.noteAlarmStart(alarm.operation, alarm.workSource, alarm.uid,
3139 alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003140 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003141 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003142 } catch (RuntimeException e) {
3143 Slog.w(TAG, "Failure sending alarm.", e);
3144 }
Tim Murray175c0f92017-11-28 15:01:04 -08003145 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003146 }
3147 }
3148
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003149 private class AlarmThread extends Thread
3150 {
3151 public AlarmThread()
3152 {
3153 super("AlarmManager");
3154 }
Kweku Adams61e03292017-10-19 14:27:12 -07003155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003156 public void run()
3157 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003158 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003160 while (true)
3161 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003162 int result = waitForAlarm(mNativeData);
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003163 mLastWakeup = SystemClock.elapsedRealtime();
Dianne Hackborn390517b2013-05-30 15:03:32 -07003164
3165 triggerList.clear();
3166
Dianne Hackbornc3527222015-05-13 14:03:20 -07003167 final long nowRTC = System.currentTimeMillis();
3168 final long nowELAPSED = SystemClock.elapsedRealtime();
3169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003170 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003171 // The kernel can give us spurious time change notifications due to
3172 // small adjustments it makes internally; we want to filter those out.
3173 final long lastTimeChangeClockTime;
3174 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07003175 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003176 lastTimeChangeClockTime = mLastTimeChangeClockTime;
3177 expectedClockTime = lastTimeChangeClockTime
3178 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07003179 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003180 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
3181 || nowRTC > (expectedClockTime+1000)) {
3182 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07003183 // let's do it!
3184 if (DEBUG_BATCH) {
3185 Slog.v(TAG, "Time changed notification from kernel; rebatching");
3186 }
3187 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07003188 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003189 rebatchAllAlarms();
3190 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07003191 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003192 synchronized (mLock) {
3193 mNumTimeChanged++;
3194 mLastTimeChangeClockTime = nowRTC;
3195 mLastTimeChangeRealtime = nowELAPSED;
3196 }
3197 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
3198 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003199 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07003200 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
3201 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003202 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
3203
3204 // The world has changed on us, so we need to re-evaluate alarms
3205 // regardless of whether the kernel has told us one went off.
3206 result |= IS_WAKEUP_MASK;
3207 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003209
Dianne Hackbornc3527222015-05-13 14:03:20 -07003210 if (result != TIME_CHANGED_MASK) {
3211 // If this was anything besides just a time change, then figure what if
3212 // anything to do about alarms.
3213 synchronized (mLock) {
3214 if (localLOGV) Slog.v(
3215 TAG, "Checking for alarms... rtc=" + nowRTC
3216 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07003217
Dianne Hackbornc3527222015-05-13 14:03:20 -07003218 if (WAKEUP_STATS) {
3219 if ((result & IS_WAKEUP_MASK) != 0) {
3220 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
3221 int n = 0;
3222 for (WakeupEvent event : mRecentWakeups) {
3223 if (event.when > newEarliest) break;
3224 n++; // number of now-stale entries at the list head
3225 }
3226 for (int i = 0; i < n; i++) {
3227 mRecentWakeups.remove();
3228 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003229
Dianne Hackbornc3527222015-05-13 14:03:20 -07003230 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003231 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003232 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003233
3234 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3235 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
3236 // if there are no wakeup alarms and the screen is off, we can
3237 // delay what we have so far until the future.
3238 if (mPendingNonWakeupAlarms.size() == 0) {
3239 mStartCurrentDelayTime = nowELAPSED;
3240 mNextNonWakeupDeliveryTime = nowELAPSED
3241 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
3242 }
3243 mPendingNonWakeupAlarms.addAll(triggerList);
3244 mNumDelayedAlarms += triggerList.size();
3245 rescheduleKernelAlarmsLocked();
3246 updateNextAlarmClockLocked();
3247 } else {
3248 // now deliver the alarm intents; if there are pending non-wakeup
3249 // alarms, we need to merge them in to the list. note we don't
3250 // just deliver them first because we generally want non-wakeup
3251 // alarms delivered after wakeup alarms.
3252 rescheduleKernelAlarmsLocked();
3253 updateNextAlarmClockLocked();
3254 if (mPendingNonWakeupAlarms.size() > 0) {
3255 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
3256 triggerList.addAll(mPendingNonWakeupAlarms);
3257 Collections.sort(triggerList, mAlarmDispatchComparator);
3258 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3259 mTotalDelayTime += thisDelayTime;
3260 if (mMaxDelayTime < thisDelayTime) {
3261 mMaxDelayTime = thisDelayTime;
3262 }
3263 mPendingNonWakeupAlarms.clear();
3264 }
3265 deliverAlarmsLocked(triggerList, nowELAPSED);
3266 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003267 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003268
3269 } else {
3270 // Just in case -- even though no wakeup flag was set, make sure
3271 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07003272 synchronized (mLock) {
3273 rescheduleKernelAlarmsLocked();
3274 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003275 }
3276 }
3277 }
3278 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003279
David Christieebe51fc2013-07-26 13:23:29 -07003280 /**
3281 * Attribute blame for a WakeLock.
3282 * @param pi PendingIntent to attribute blame to if ws is null.
3283 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003284 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07003285 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003286 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003287 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07003288 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003289 final boolean unimportant = pi == mTimeTickSender;
3290 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003291 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003292 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003293 } else {
3294 mWakeLock.setHistoryTag(null);
3295 }
3296 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07003297 if (ws != null) {
3298 mWakeLock.setWorkSource(ws);
3299 return;
3300 }
3301
Christopher Tate14a7bb02015-10-01 10:24:31 -07003302 final int uid = (knownUid >= 0)
3303 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003304 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07003305 if (uid >= 0) {
3306 mWakeLock.setWorkSource(new WorkSource(uid));
3307 return;
3308 }
3309 } catch (Exception e) {
3310 }
3311
3312 // Something went wrong; fall back to attributing the lock to the OS
3313 mWakeLock.setWorkSource(null);
3314 }
3315
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003316 private class AlarmHandler extends Handler {
3317 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003318 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
3319 public static final int LISTENER_TIMEOUT = 3;
3320 public static final int REPORT_ALARMS_ACTIVE = 4;
Kweku Adams61e03292017-10-19 14:27:12 -07003321
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003322 public AlarmHandler() {
3323 }
Kweku Adams61e03292017-10-19 14:27:12 -07003324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003325 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003326 switch (msg.what) {
3327 case ALARM_EVENT: {
3328 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3329 synchronized (mLock) {
3330 final long nowRTC = System.currentTimeMillis();
3331 final long nowELAPSED = SystemClock.elapsedRealtime();
3332 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3333 updateNextAlarmClockLocked();
3334 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003335
Christopher Tate14a7bb02015-10-01 10:24:31 -07003336 // now trigger the alarms without the lock held
3337 for (int i=0; i<triggerList.size(); i++) {
3338 Alarm alarm = triggerList.get(i);
3339 try {
3340 alarm.operation.send();
3341 } catch (PendingIntent.CanceledException e) {
3342 if (alarm.repeatInterval > 0) {
3343 // This IntentSender is no longer valid, but this
3344 // is a repeating alarm, so toss the hoser.
3345 removeImpl(alarm.operation);
3346 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003347 }
3348 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003349 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003350 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003351
3352 case SEND_NEXT_ALARM_CLOCK_CHANGED:
3353 sendNextAlarmClockChanged();
3354 break;
3355
3356 case LISTENER_TIMEOUT:
3357 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
3358 break;
3359
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003360 case REPORT_ALARMS_ACTIVE:
3361 if (mLocalDeviceIdleController != null) {
3362 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
3363 }
3364 break;
3365
Christopher Tate14a7bb02015-10-01 10:24:31 -07003366 default:
3367 // nope, just ignore it
3368 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003369 }
3370 }
3371 }
Kweku Adams61e03292017-10-19 14:27:12 -07003372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003373 class ClockReceiver extends BroadcastReceiver {
3374 public ClockReceiver() {
3375 IntentFilter filter = new IntentFilter();
3376 filter.addAction(Intent.ACTION_TIME_TICK);
3377 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003378 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003379 }
Kweku Adams61e03292017-10-19 14:27:12 -07003380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003381 @Override
3382 public void onReceive(Context context, Intent intent) {
3383 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07003384 if (DEBUG_BATCH) {
3385 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
3386 }
Christopher Tate12cf0b62018-01-05 18:40:14 -08003387 synchronized (mLock) {
3388 mLastTickReceived = System.currentTimeMillis();
3389 }
Christopher Tate385e4982013-07-23 18:22:29 -07003390 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003391 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
3392 // Since the kernel does not keep track of DST, we need to
3393 // reset the TZ information at the beginning of each day
3394 // based off of the current Zone gmt offset + userspace tracked
3395 // daylight savings information.
3396 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02003397 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003398 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07003399 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003400 }
3401 }
Kweku Adams61e03292017-10-19 14:27:12 -07003402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003403 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07003404 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09003405 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07003406
3407 // Schedule this event for the amount of time that it would take to get to
3408 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09003409 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07003410
David Christieebe51fc2013-07-26 13:23:29 -07003411 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08003412 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003413 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
3414 null, Process.myUid(), "android");
Christopher Tate12cf0b62018-01-05 18:40:14 -08003415
3416 // Finally, remember when we set the tick alarm
3417 synchronized (mLock) {
3418 mLastTickSet = currentTime;
3419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003420 }
Christopher Tate385e4982013-07-23 18:22:29 -07003421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003422 public void scheduleDateChangedEvent() {
3423 Calendar calendar = Calendar.getInstance();
3424 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07003425 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003426 calendar.set(Calendar.MINUTE, 0);
3427 calendar.set(Calendar.SECOND, 0);
3428 calendar.set(Calendar.MILLISECOND, 0);
3429 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07003430
3431 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003432 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
3433 AlarmManager.FLAG_STANDALONE, workSource, null,
3434 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003435 }
3436 }
Kweku Adams61e03292017-10-19 14:27:12 -07003437
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003438 class InteractiveStateReceiver extends BroadcastReceiver {
3439 public InteractiveStateReceiver() {
3440 IntentFilter filter = new IntentFilter();
3441 filter.addAction(Intent.ACTION_SCREEN_OFF);
3442 filter.addAction(Intent.ACTION_SCREEN_ON);
3443 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
3444 getContext().registerReceiver(this, filter);
3445 }
3446
3447 @Override
3448 public void onReceive(Context context, Intent intent) {
3449 synchronized (mLock) {
3450 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
3451 }
3452 }
3453 }
3454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003455 class UninstallReceiver extends BroadcastReceiver {
3456 public UninstallReceiver() {
3457 IntentFilter filter = new IntentFilter();
3458 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
3459 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003460 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003461 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08003462 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003463 // Register for events related to sdcard installation.
3464 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08003465 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003466 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003467 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003468 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003469 }
Kweku Adams61e03292017-10-19 14:27:12 -07003470
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003471 @Override
3472 public void onReceive(Context context, Intent intent) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003473 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003474 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003475 String action = intent.getAction();
3476 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003477 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
3478 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
3479 for (String packageName : pkgList) {
3480 if (lookForPackageLocked(packageName)) {
3481 setResultCode(Activity.RESULT_OK);
3482 return;
3483 }
3484 }
3485 return;
3486 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003487 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003488 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
3489 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
3490 if (userHandle >= 0) {
3491 removeUserLocked(userHandle);
3492 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003493 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003494 if (uid >= 0) {
3495 mLastAllowWhileIdleDispatch.delete(uid);
3496 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003497 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08003498 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
3499 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
3500 // This package is being updated; don't kill its alarms.
3501 return;
3502 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003503 Uri data = intent.getData();
3504 if (data != null) {
3505 String pkg = data.getSchemeSpecificPart();
3506 if (pkg != null) {
3507 pkgList = new String[]{pkg};
3508 }
3509 }
3510 }
3511 if (pkgList != null && (pkgList.length > 0)) {
3512 for (String pkg : pkgList) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003513 if (uid >= 0) {
3514 // package-removed case
3515 removeLocked(uid);
3516 } else {
3517 // external-applications-unavailable etc case
3518 removeLocked(pkg);
3519 }
Christopher Tate1590f1e2014-10-02 17:27:57 -07003520 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003521 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
3522 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
3523 if (uidStats.remove(pkg) != null) {
3524 if (uidStats.size() <= 0) {
3525 mBroadcastStats.removeAt(i);
3526 }
3527 }
3528 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003529 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003530 }
3531 }
3532 }
3533 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003534
3535 final class UidObserver extends IUidObserver.Stub {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003536 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003537 }
3538
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003539 @Override public void onUidGone(int uid, boolean disabled) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003540 synchronized (mLock) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08003541 mUseAllowWhileIdleShortTime.delete(uid);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003542 if (disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -08003543 removeForStoppedLocked(uid);
3544 }
3545 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003546 }
3547
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003548 @Override public void onUidActive(int uid) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08003549 synchronized (mLock) {
3550 mUseAllowWhileIdleShortTime.put(uid, true);
3551 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003552 }
3553
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003554 @Override public void onUidIdle(int uid, boolean disabled) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003555 synchronized (mLock) {
3556 if (disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -08003557 removeForStoppedLocked(uid);
3558 }
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08003559 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003560 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003561
3562 @Override public void onUidCachedChanged(int uid, boolean cached) {
3563 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003564 };
3565
Makoto Onuki2206af32017-11-21 16:25:35 -08003566 private final Listener mForceAppStandbyListener = new Listener() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003567 @Override
Makoto Onuki2206af32017-11-21 16:25:35 -08003568 public void unblockAllUnrestrictedAlarms() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003569 synchronized (mLock) {
Makoto Onuki2206af32017-11-21 16:25:35 -08003570 sendAllUnrestrictedPendingBackgroundAlarmsLocked();
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003571 }
3572 }
Makoto Onuki2206af32017-11-21 16:25:35 -08003573
3574 @Override
3575 public void unblockAlarmsForUid(int uid) {
3576 synchronized (mLock) {
3577 sendPendingBackgroundAlarmsLocked(uid, null);
3578 }
3579 }
3580
3581 @Override
3582 public void unblockAlarmsForUidPackage(int uid, String packageName) {
3583 synchronized (mLock) {
3584 sendPendingBackgroundAlarmsLocked(uid, packageName);
3585 }
3586 }
3587 };
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003589 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003590 String pkg = pi.getCreatorPackage();
3591 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003592 return getStatsLocked(uid, pkg);
3593 }
3594
3595 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003596 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
3597 if (uidStats == null) {
3598 uidStats = new ArrayMap<String, BroadcastStats>();
3599 mBroadcastStats.put(uid, uidStats);
3600 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003601 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003602 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003603 bs = new BroadcastStats(uid, pkgName);
3604 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003605 }
3606 return bs;
3607 }
Dianne Hackborn81038902012-11-26 17:04:09 -08003608
Christopher Tate21e9f192017-08-08 13:49:11 -07003609 /**
3610 * Canonical count of (operation.send() - onSendFinished()) and
3611 * listener send/complete/timeout invocations.
3612 * Guarded by the usual lock.
3613 */
3614 @GuardedBy("mLock")
3615 private int mSendCount = 0;
3616 @GuardedBy("mLock")
Christopher Tateeabba732017-08-17 17:12:52 -07003617 private int mSendFinishCount = 0;
3618 @GuardedBy("mLock")
Christopher Tate21e9f192017-08-08 13:49:11 -07003619 private int mListenerCount = 0;
Christopher Tateeabba732017-08-17 17:12:52 -07003620 @GuardedBy("mLock")
3621 private int mListenerFinishCount = 0;
Christopher Tate21e9f192017-08-08 13:49:11 -07003622
Christopher Tate14a7bb02015-10-01 10:24:31 -07003623 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
Christopher Tate21e9f192017-08-08 13:49:11 -07003624
Christopher Tate14a7bb02015-10-01 10:24:31 -07003625 private InFlight removeLocked(PendingIntent pi, Intent intent) {
3626 for (int i = 0; i < mInFlight.size(); i++) {
Christopher Tatedb9ae422017-08-21 11:24:30 -07003627 if (mInFlight.get(i).mPendingIntent == pi) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003628 return mInFlight.remove(i);
3629 }
3630 }
3631 mLog.w("No in-flight alarm for " + pi + " " + intent);
3632 return null;
3633 }
3634
3635 private InFlight removeLocked(IBinder listener) {
3636 for (int i = 0; i < mInFlight.size(); i++) {
3637 if (mInFlight.get(i).mListener == listener) {
3638 return mInFlight.remove(i);
3639 }
3640 }
3641 mLog.w("No in-flight alarm for listener " + listener);
3642 return null;
3643 }
3644
3645 private void updateStatsLocked(InFlight inflight) {
3646 final long nowELAPSED = SystemClock.elapsedRealtime();
3647 BroadcastStats bs = inflight.mBroadcastStats;
3648 bs.nesting--;
3649 if (bs.nesting <= 0) {
3650 bs.nesting = 0;
3651 bs.aggregateTime += nowELAPSED - bs.startTime;
3652 }
3653 FilterStats fs = inflight.mFilterStats;
3654 fs.nesting--;
3655 if (fs.nesting <= 0) {
3656 fs.nesting = 0;
3657 fs.aggregateTime += nowELAPSED - fs.startTime;
3658 }
3659 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003660 ActivityManager.noteAlarmFinish(inflight.mPendingIntent, inflight.mWorkSource,
3661 inflight.mUid, inflight.mTag);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003662 }
3663 }
3664
3665 private void updateTrackingLocked(InFlight inflight) {
3666 if (inflight != null) {
3667 updateStatsLocked(inflight);
3668 }
3669 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08003670 if (DEBUG_WAKELOCK) {
3671 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
3672 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003673 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003674 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003675 mWakeLock.release();
3676 if (mInFlight.size() > 0) {
3677 mLog.w("Finished all dispatches with " + mInFlight.size()
3678 + " remaining inflights");
3679 for (int i=0; i<mInFlight.size(); i++) {
3680 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
3681 }
3682 mInFlight.clear();
3683 }
3684 } else {
3685 // the next of our alarms is now in flight. reattribute the wakelock.
3686 if (mInFlight.size() > 0) {
3687 InFlight inFlight = mInFlight.get(0);
3688 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
3689 inFlight.mAlarmType, inFlight.mTag, -1, false);
3690 } else {
3691 // should never happen
3692 mLog.w("Alarm wakelock still held but sent queue empty");
3693 mWakeLock.setWorkSource(null);
3694 }
3695 }
3696 }
3697
3698 /**
3699 * Callback that arrives when a direct-call alarm reports that delivery has finished
3700 */
3701 @Override
3702 public void alarmComplete(IBinder who) {
3703 if (who == null) {
Christopher Tate21e9f192017-08-08 13:49:11 -07003704 mLog.w("Invalid alarmComplete: uid=" + Binder.getCallingUid()
Christopher Tate14a7bb02015-10-01 10:24:31 -07003705 + " pid=" + Binder.getCallingPid());
3706 return;
3707 }
3708
3709 final long ident = Binder.clearCallingIdentity();
3710 try {
3711 synchronized (mLock) {
3712 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
3713 InFlight inflight = removeLocked(who);
3714 if (inflight != null) {
3715 if (DEBUG_LISTENER_CALLBACK) {
3716 Slog.i(TAG, "alarmComplete() from " + who);
3717 }
3718 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07003719 mListenerFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003720 } else {
3721 // Delivery timed out, and the timeout handling already took care of
3722 // updating our tracking here, so we needn't do anything further.
3723 if (DEBUG_LISTENER_CALLBACK) {
3724 Slog.i(TAG, "Late alarmComplete() from " + who);
3725 }
3726 }
3727 }
3728 } finally {
3729 Binder.restoreCallingIdentity(ident);
3730 }
3731 }
3732
3733 /**
3734 * Callback that arrives when a PendingIntent alarm has finished delivery
3735 */
3736 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003737 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
3738 String resultData, Bundle resultExtras) {
3739 synchronized (mLock) {
Christopher Tateeabba732017-08-17 17:12:52 -07003740 mSendFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003741 updateTrackingLocked(removeLocked(pi, intent));
3742 }
3743 }
3744
3745 /**
3746 * Timeout of a direct-call alarm delivery
3747 */
3748 public void alarmTimedOut(IBinder who) {
3749 synchronized (mLock) {
3750 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08003751 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003752 // TODO: implement ANR policy for the target
3753 if (DEBUG_LISTENER_CALLBACK) {
3754 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003755 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003756 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07003757 mListenerFinishCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08003758 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003759 if (DEBUG_LISTENER_CALLBACK) {
3760 Slog.i(TAG, "Spurious timeout of listener " + who);
3761 }
Christopher Tate21e9f192017-08-08 13:49:11 -07003762 mLog.w("Spurious timeout of listener " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003763 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003764 }
3765 }
3766
3767 /**
3768 * Deliver an alarm and set up the post-delivery handling appropriately
3769 */
3770 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
3771 if (alarm.operation != null) {
3772 // PendingIntent alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07003773 mSendCount++;
Christopher Tate12cf0b62018-01-05 18:40:14 -08003774
3775 if (alarm.priorityClass.priority == PRIO_TICK) {
3776 mLastTickIssued = nowELAPSED;
3777 }
3778
Christopher Tate14a7bb02015-10-01 10:24:31 -07003779 try {
3780 alarm.operation.send(getContext(), 0,
3781 mBackgroundIntent.putExtra(
3782 Intent.EXTRA_ALARM_COUNT, alarm.count),
3783 mDeliveryTracker, mHandler, null,
3784 allowWhileIdle ? mIdleOptions : null);
3785 } catch (PendingIntent.CanceledException e) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08003786 if (alarm.operation == mTimeTickSender) {
3787 Slog.wtf(TAG, "mTimeTickSender canceled");
3788 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003789 if (alarm.repeatInterval > 0) {
3790 // This IntentSender is no longer valid, but this
3791 // is a repeating alarm, so toss it
3792 removeImpl(alarm.operation);
3793 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003794 // No actual delivery was possible, so the delivery tracker's
3795 // 'finished' callback won't be invoked. We also don't need
3796 // to do any wakelock or stats tracking, so we have nothing
3797 // left to do here but go on to the next thing.
Christopher Tateeabba732017-08-17 17:12:52 -07003798 mSendFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08003799 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003800 }
3801 } else {
3802 // Direct listener callback alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07003803 mListenerCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003804 try {
3805 if (DEBUG_LISTENER_CALLBACK) {
3806 Slog.v(TAG, "Alarm to uid=" + alarm.uid
3807 + " listener=" + alarm.listener.asBinder());
3808 }
3809 alarm.listener.doAlarm(this);
3810 mHandler.sendMessageDelayed(
3811 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
3812 alarm.listener.asBinder()),
3813 mConstants.LISTENER_TIMEOUT);
3814 } catch (Exception e) {
3815 if (DEBUG_LISTENER_CALLBACK) {
3816 Slog.i(TAG, "Alarm undeliverable to listener "
3817 + alarm.listener.asBinder(), e);
3818 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003819 // As in the PendingIntent.CanceledException case, delivery of the
3820 // alarm was not possible, so we have no wakelock or timeout or
3821 // stats management to do. It threw before we posted the delayed
3822 // timeout message, so we're done here.
Christopher Tateeabba732017-08-17 17:12:52 -07003823 mListenerFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08003824 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003825 }
3826 }
3827
3828 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08003829 if (DEBUG_WAKELOCK) {
3830 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
3831 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003832 if (mBroadcastRefCount == 0) {
3833 setWakelockWorkSource(alarm.operation, alarm.workSource,
3834 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
3835 true);
3836 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003837 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003838 }
3839 final InFlight inflight = new InFlight(AlarmManagerService.this,
3840 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
3841 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
3842 mInFlight.add(inflight);
3843 mBroadcastRefCount++;
3844
3845 if (allowWhileIdle) {
3846 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08003847 mLastAllowWhileIdleDispatch.put(alarm.creatorUid, nowELAPSED);
3848 if (mForceAppStandbyTracker.isInForeground(alarm.creatorUid)) {
3849 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, true);
3850 } else {
3851 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, false);
3852 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003853 if (RECORD_DEVICE_IDLE_ALARMS) {
3854 IdleDispatchEntry ent = new IdleDispatchEntry();
3855 ent.uid = alarm.uid;
3856 ent.pkg = alarm.packageName;
3857 ent.tag = alarm.statsTag;
3858 ent.op = "DELIVER";
3859 ent.elapsedRealtime = nowELAPSED;
3860 mAllowWhileIdleDispatches.add(ent);
3861 }
3862 }
3863
3864 final BroadcastStats bs = inflight.mBroadcastStats;
3865 bs.count++;
3866 if (bs.nesting == 0) {
3867 bs.nesting = 1;
3868 bs.startTime = nowELAPSED;
3869 } else {
3870 bs.nesting++;
3871 }
3872 final FilterStats fs = inflight.mFilterStats;
3873 fs.count++;
3874 if (fs.nesting == 0) {
3875 fs.nesting = 1;
3876 fs.startTime = nowELAPSED;
3877 } else {
3878 fs.nesting++;
3879 }
3880 if (alarm.type == ELAPSED_REALTIME_WAKEUP
3881 || alarm.type == RTC_WAKEUP) {
3882 bs.numWakeup++;
3883 fs.numWakeup++;
Narayan Kamath695cf722017-12-21 18:32:47 +00003884 ActivityManager.noteWakeupAlarm(
3885 alarm.operation, alarm.workSource, alarm.uid, alarm.packageName,
3886 alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003887 }
3888 }
3889 }
3890}