blob: 15c0f3c1154515592e1aab163a3623a503ebdd1e [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
Christopher Tatee0a22b32013-07-11 14:43:13 -070085import static android.app.AlarmManager.RTC_WAKEUP;
86import static android.app.AlarmManager.RTC;
87import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
88import static android.app.AlarmManager.ELAPSED_REALTIME;
89
Christopher Tate21e9f192017-08-08 13:49:11 -070090import com.android.internal.annotations.GuardedBy;
Makoto Onuki2206af32017-11-21 16:25:35 -080091import com.android.internal.annotations.VisibleForTesting;
Makoto Onuki5d93b832018-01-10 16:12:39 -080092import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060093import com.android.internal.util.DumpUtils;
Dianne Hackborn81038902012-11-26 17:04:09 -080094import com.android.internal.util.LocalLog;
Makoto Onuki2206af32017-11-21 16:25:35 -080095import com.android.server.ForceAppStandbyTracker.Listener;
Dianne Hackborn81038902012-11-26 17:04:09 -080096
Makoto Onuki2206af32017-11-21 16:25:35 -080097/**
98 * Alarm manager implementaion.
99 *
100 * Unit test:
101 atest $ANDROID_BUILD_TOP/frameworks/base/services/tests/servicestests/src/com/android/server/AlarmManagerServiceTest.java
102 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800103class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700104 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
105 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800106 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700107 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800108 static final int TIME_CHANGED_MASK = 1 << 16;
109 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -0800110
Christopher Tatee0a22b32013-07-11 14:43:13 -0700111 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -0800112 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -0800113
Adam Lesinski182f73f2013-12-05 16:48:06 -0800114 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -0800115 static final boolean localLOGV = false;
116 static final boolean DEBUG_BATCH = localLOGV || false;
117 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200118 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700119 static final boolean DEBUG_LISTENER_CALLBACK = localLOGV || false;
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800120 static final boolean DEBUG_WAKELOCK = localLOGV || false;
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700121 static final boolean DEBUG_BG_LIMIT = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700122 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700123 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800124 static final int ALARM_EVENT = 1;
125 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200126
Christopher Tate14a7bb02015-10-01 10:24:31 -0700127 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800129 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700130
Adam Lesinski182f73f2013-12-05 16:48:06 -0800131 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700132
Christopher Tate24cd46f2016-02-02 14:28:01 -0800133 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT =
134 new Intent(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED)
Christopher Tate50191db2017-05-09 16:02:25 -0700135 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
136 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Adrian Roosc42a1e12014-07-07 23:35:53 +0200137
Adam Lesinski182f73f2013-12-05 16:48:06 -0800138 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800139
Christopher Tate14a7bb02015-10-01 10:24:31 -0700140 AppOpsManager mAppOps;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800141 DeviceIdleController.LocalService mLocalDeviceIdleController;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700142
Adam Lesinski182f73f2013-12-05 16:48:06 -0800143 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800144
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700145 // List of alarms per uid deferred due to user applied background restrictions on the source app
146 SparseArray<ArrayList<Alarm>> mPendingBackgroundAlarms = new SparseArray<>();
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800147 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800148 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700149 private long mNextNonWakeup;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -0700150 private long mLastWakeupSet;
151 private long mLastWakeup;
Christopher Tate12cf0b62018-01-05 18:40:14 -0800152 private long mLastTickSet;
153 private long mLastTickIssued; // elapsed
154 private long mLastTickReceived;
Makoto Onuki5d93b832018-01-10 16:12:39 -0800155 private long mLastTickAdded;
156 private long mLastTickRemoved;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800157 int mBroadcastRefCount = 0;
158 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700159 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700160 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
161 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800162 final AlarmHandler mHandler = new AlarmHandler();
163 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700164 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700166 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800167 PendingIntent mTimeTickSender;
168 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700169 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700170 boolean mInteractive = true;
171 long mNonInteractiveStartTime;
172 long mNonInteractiveTime;
173 long mLastAlarmDeliveryTime;
174 long mStartCurrentDelayTime;
175 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700176 long mLastTimeChangeClockTime;
177 long mLastTimeChangeRealtime;
Dianne Hackborna750a632015-06-16 17:18:23 -0700178 long mAllowWhileIdleMinTime;
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
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700202 final static class IdleDispatchEntry {
203 int uid;
204 String pkg;
205 String tag;
206 String op;
207 long elapsedRealtime;
208 long argRealtime;
209 }
210 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
211
Dianne Hackborna750a632015-06-16 17:18:23 -0700212 /**
213 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
214 */
215 Bundle mIdleOptions;
216
Jose Lima235510e2014-08-13 12:50:01 -0700217 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
218 new SparseArray<>();
219 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
220 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200221 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
222 new SparseBooleanArray();
223 private boolean mNextAlarmClockMayChange;
224
225 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700226 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
227 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200228
Makoto Onuki2206af32017-11-21 16:25:35 -0800229 private final ForceAppStandbyTracker mForceAppStandbyTracker;
230
Dianne Hackborna750a632015-06-16 17:18:23 -0700231 /**
232 * All times are in milliseconds. These constants are kept synchronized with the system
233 * global Settings. Any access to this class or its fields should be done while
234 * holding the AlarmManagerService.mLock lock.
235 */
236 private final class Constants extends ContentObserver {
237 // Key names stored in the settings value.
238 private static final String KEY_MIN_FUTURITY = "min_futurity";
239 private static final String KEY_MIN_INTERVAL = "min_interval";
240 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
241 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
242 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
243 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700244 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700245 private static final String KEY_BG_RESTRICTIONS_ENABLED = "limit_bg_alarms_enabled";
Dianne Hackborna750a632015-06-16 17:18:23 -0700246
247 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
248 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tateaa244da2015-08-27 15:57:57 -0700249 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700250 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700251 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
252
Christopher Tate14a7bb02015-10-01 10:24:31 -0700253 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
254
Dianne Hackborna750a632015-06-16 17:18:23 -0700255 // Minimum futurity of a new alarm
256 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
257
258 // Minimum alarm recurrence interval
259 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
260
261 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
262 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
263
264 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
265 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
266
267 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
268 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
269 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
270
Christopher Tate14a7bb02015-10-01 10:24:31 -0700271 // Direct alarm listener callback timeout
272 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
273
Dianne Hackborna750a632015-06-16 17:18:23 -0700274 private ContentResolver mResolver;
275 private final KeyValueListParser mParser = new KeyValueListParser(',');
276 private long mLastAllowWhileIdleWhitelistDuration = -1;
277
278 public Constants(Handler handler) {
279 super(handler);
280 updateAllowWhileIdleMinTimeLocked();
281 updateAllowWhileIdleWhitelistDurationLocked();
282 }
283
284 public void start(ContentResolver resolver) {
285 mResolver = resolver;
286 mResolver.registerContentObserver(Settings.Global.getUriFor(
287 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
288 updateConstants();
289 }
290
291 public void updateAllowWhileIdleMinTimeLocked() {
292 mAllowWhileIdleMinTime = mPendingIdleUntil != null
293 ? ALLOW_WHILE_IDLE_LONG_TIME : ALLOW_WHILE_IDLE_SHORT_TIME;
294 }
295
296 public void updateAllowWhileIdleWhitelistDurationLocked() {
297 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
298 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
299 BroadcastOptions opts = BroadcastOptions.makeBasic();
300 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
301 mIdleOptions = opts.toBundle();
302 }
303 }
304
305 @Override
306 public void onChange(boolean selfChange, Uri uri) {
307 updateConstants();
308 }
309
310 private void updateConstants() {
311 synchronized (mLock) {
312 try {
313 mParser.setString(Settings.Global.getString(mResolver,
314 Settings.Global.ALARM_MANAGER_CONSTANTS));
315 } catch (IllegalArgumentException e) {
316 // Failed to parse the settings string, log this and move on
317 // with defaults.
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800318 Slog.e(TAG, "Bad alarm manager settings", e);
Dianne Hackborna750a632015-06-16 17:18:23 -0700319 }
320
321 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
322 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
323 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
324 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
325 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
326 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
327 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
328 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
329 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700330 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
331 DEFAULT_LISTENER_TIMEOUT);
Dianne Hackborna750a632015-06-16 17:18:23 -0700332
333 updateAllowWhileIdleMinTimeLocked();
334 updateAllowWhileIdleWhitelistDurationLocked();
335 }
336 }
337
338 void dump(PrintWriter pw) {
339 pw.println(" Settings:");
340
341 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
342 TimeUtils.formatDuration(MIN_FUTURITY, pw);
343 pw.println();
344
345 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
346 TimeUtils.formatDuration(MIN_INTERVAL, pw);
347 pw.println();
348
Christopher Tate14a7bb02015-10-01 10:24:31 -0700349 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
350 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
351 pw.println();
352
Dianne Hackborna750a632015-06-16 17:18:23 -0700353 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
354 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
355 pw.println();
356
357 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
358 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
359 pw.println();
360
361 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
362 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
363 pw.println();
364 }
Kweku Adams61e03292017-10-19 14:27:12 -0700365
366 void dumpProto(ProtoOutputStream proto, long fieldId) {
367 final long token = proto.start(fieldId);
368
369 proto.write(ConstantsProto.MIN_FUTURITY_DURATION_MS, MIN_FUTURITY);
370 proto.write(ConstantsProto.MIN_INTERVAL_DURATION_MS, MIN_INTERVAL);
371 proto.write(ConstantsProto.LISTENER_TIMEOUT_DURATION_MS, LISTENER_TIMEOUT);
372 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_SHORT_DURATION_MS,
373 ALLOW_WHILE_IDLE_SHORT_TIME);
374 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_LONG_DURATION_MS,
375 ALLOW_WHILE_IDLE_LONG_TIME);
376 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_WHITELIST_DURATION_MS,
377 ALLOW_WHILE_IDLE_WHITELIST_DURATION);
378
379 proto.end(token);
380 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700381 }
382
383 final Constants mConstants;
384
Christopher Tate1590f1e2014-10-02 17:27:57 -0700385 // Alarm delivery ordering bookkeeping
386 static final int PRIO_TICK = 0;
387 static final int PRIO_WAKEUP = 1;
388 static final int PRIO_NORMAL = 2;
389
Dianne Hackborna750a632015-06-16 17:18:23 -0700390 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700391 int seq;
392 int priority;
393
394 PriorityClass() {
395 seq = mCurrentSeq - 1;
396 priority = PRIO_NORMAL;
397 }
398 }
399
Dianne Hackborna750a632015-06-16 17:18:23 -0700400 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700401 int mCurrentSeq = 0;
402
Dianne Hackborna750a632015-06-16 17:18:23 -0700403 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700404 public long when;
405 public int uid;
406 public String action;
407
408 public WakeupEvent(long theTime, int theUid, String theAction) {
409 when = theTime;
410 uid = theUid;
411 action = theAction;
412 }
413 }
414
Adam Lesinski182f73f2013-12-05 16:48:06 -0800415 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
416 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700417
Adrian Roosc42a1e12014-07-07 23:35:53 +0200418 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700419 long start; // These endpoints are always in ELAPSED
420 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700421 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700422
423 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
424
425 Batch() {
426 start = 0;
427 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700428 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700429 }
430
431 Batch(Alarm seed) {
432 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700433 end = seed.maxWhenElapsed;
434 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700435 alarms.add(seed);
Makoto Onuki5d93b832018-01-10 16:12:39 -0800436 if (seed.operation == mTimeTickSender) {
437 mLastTickAdded = System.currentTimeMillis();
438 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700439 }
440
441 int size() {
442 return alarms.size();
443 }
444
445 Alarm get(int index) {
446 return alarms.get(index);
447 }
448
449 boolean canHold(long whenElapsed, long maxWhen) {
450 return (end >= whenElapsed) && (start <= maxWhen);
451 }
452
453 boolean add(Alarm alarm) {
454 boolean newStart = false;
455 // narrows the batch if necessary; presumes that canHold(alarm) is true
456 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
457 if (index < 0) {
458 index = 0 - index - 1;
459 }
460 alarms.add(index, alarm);
Makoto Onuki5d93b832018-01-10 16:12:39 -0800461 if (alarm.operation == mTimeTickSender) {
462 mLastTickAdded = System.currentTimeMillis();
463 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700464 if (DEBUG_BATCH) {
465 Slog.v(TAG, "Adding " + alarm + " to " + this);
466 }
467 if (alarm.whenElapsed > start) {
468 start = alarm.whenElapsed;
469 newStart = true;
470 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700471 if (alarm.maxWhenElapsed < end) {
472 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700473 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700474 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700475
476 if (DEBUG_BATCH) {
477 Slog.v(TAG, " => now " + this);
478 }
479 return newStart;
480 }
481
Christopher Tate1d99c392017-12-07 16:54:04 -0800482 boolean remove(Predicate<Alarm> predicate) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700483 boolean didRemove = false;
484 long newStart = 0; // recalculate endpoints as we go
485 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700486 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700487 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700488 Alarm alarm = alarms.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -0800489 if (predicate.test(alarm)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700490 alarms.remove(i);
491 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200492 if (alarm.alarmClock != null) {
493 mNextAlarmClockMayChange = true;
494 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800495 if (alarm.operation == mTimeTickSender) {
496 mLastTickRemoved = System.currentTimeMillis();
497 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700498 } else {
499 if (alarm.whenElapsed > newStart) {
500 newStart = alarm.whenElapsed;
501 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700502 if (alarm.maxWhenElapsed < newEnd) {
503 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700504 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700505 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700506 i++;
507 }
508 }
509 if (didRemove) {
510 // commit the new batch bounds
511 start = newStart;
512 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700513 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700514 }
515 return didRemove;
516 }
517
Christopher Tatee0a22b32013-07-11 14:43:13 -0700518 boolean hasPackage(final String packageName) {
519 final int N = alarms.size();
520 for (int i = 0; i < N; i++) {
521 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700522 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700523 return true;
524 }
525 }
526 return false;
527 }
528
529 boolean hasWakeups() {
530 final int N = alarms.size();
531 for (int i = 0; i < N; i++) {
532 Alarm a = alarms.get(i);
533 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
534 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
535 return true;
536 }
537 }
538 return false;
539 }
540
541 @Override
542 public String toString() {
543 StringBuilder b = new StringBuilder(40);
544 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
545 b.append(" num="); b.append(size());
546 b.append(" start="); b.append(start);
547 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700548 if (flags != 0) {
549 b.append(" flgs=0x");
550 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700551 }
552 b.append('}');
553 return b.toString();
554 }
Kweku Adams61e03292017-10-19 14:27:12 -0700555
556 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
557 long nowRTC) {
558 final long token = proto.start(fieldId);
559
560 proto.write(BatchProto.START_REALTIME, start);
561 proto.write(BatchProto.END_REALTIME, end);
562 proto.write(BatchProto.FLAGS, flags);
563 for (Alarm a : alarms) {
564 a.writeToProto(proto, BatchProto.ALARMS, nowElapsed, nowRTC);
565 }
566
567 proto.end(token);
568 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700569 }
570
571 static class BatchTimeOrder implements Comparator<Batch> {
572 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800573 long when1 = b1.start;
574 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800575 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700576 return 1;
577 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800578 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700579 return -1;
580 }
581 return 0;
582 }
583 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800584
585 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
586 @Override
587 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700588 // priority class trumps everything. TICK < WAKEUP < NORMAL
589 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
590 return -1;
591 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
592 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800593 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700594
595 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800596 if (lhs.whenElapsed < rhs.whenElapsed) {
597 return -1;
598 } else if (lhs.whenElapsed > rhs.whenElapsed) {
599 return 1;
600 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700601
602 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800603 return 0;
604 }
605 };
606
Christopher Tate1590f1e2014-10-02 17:27:57 -0700607 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
608 final int N = alarms.size();
609 for (int i = 0; i < N; i++) {
610 Alarm a = alarms.get(i);
611
612 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700613 if (a.operation != null
614 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700615 alarmPrio = PRIO_TICK;
616 } else if (a.wakeup) {
617 alarmPrio = PRIO_WAKEUP;
618 } else {
619 alarmPrio = PRIO_NORMAL;
620 }
621
622 PriorityClass packagePrio = a.priorityClass;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700623 String alarmPackage = (a.operation != null)
624 ? a.operation.getCreatorPackage()
625 : a.packageName;
626 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700627 if (packagePrio == null) {
628 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700629 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700630 }
631 a.priorityClass = packagePrio;
632
633 if (packagePrio.seq != mCurrentSeq) {
634 // first alarm we've seen in the current delivery generation from this package
635 packagePrio.priority = alarmPrio;
636 packagePrio.seq = mCurrentSeq;
637 } else {
638 // Multiple alarms from this package being delivered in this generation;
639 // bump the package's delivery class if it's warranted.
640 // TICK < WAKEUP < NORMAL
641 if (alarmPrio < packagePrio.priority) {
642 packagePrio.priority = alarmPrio;
643 }
644 }
645 }
646 }
647
Christopher Tatee0a22b32013-07-11 14:43:13 -0700648 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800649 static final long MIN_FUZZABLE_INTERVAL = 10000;
650 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700651 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
652
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700653 // 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 -0700654 // to run during this time are placed in mPendingWhileIdleAlarms
655 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700656 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700657 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700658
Jeff Brownb880d882014-02-10 19:47:07 -0800659 public AlarmManagerService(Context context) {
660 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700661 mConstants = new Constants(mHandler);
Makoto Onuki2206af32017-11-21 16:25:35 -0800662
663 mForceAppStandbyTracker = ForceAppStandbyTracker.getInstance(context);
664 mForceAppStandbyTracker.addListener(mForceAppStandbyListener);
Christopher Tate1d99c392017-12-07 16:54:04 -0800665
666 publishLocalService(AlarmManagerInternal.class, new LocalService());
Jeff Brownb880d882014-02-10 19:47:07 -0800667 }
668
Christopher Tatee0a22b32013-07-11 14:43:13 -0700669 static long convertToElapsed(long when, int type) {
670 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
671 if (isRtc) {
672 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
673 }
674 return when;
675 }
676
677 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
678 // calculate the end of our nominal delivery window for the alarm.
679 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
680 // Current heuristic: batchable window is 75% of either the recurrence interval
681 // [for a periodic alarm] or of the time from now to the desired delivery time,
682 // with a minimum delay/interval of 10 seconds, under which we will simply not
683 // defer the alarm.
684 long futurity = (interval == 0)
685 ? (triggerAtTime - now)
686 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700687 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700688 futurity = 0;
689 }
690 return triggerAtTime + (long)(.75 * futurity);
691 }
692
693 // returns true if the batch was added at the head
694 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
695 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
696 if (index < 0) {
697 index = 0 - index - 1;
698 }
699 list.add(index, newBatch);
700 return (index == 0);
701 }
702
Christopher Tate385e4982013-07-23 18:22:29 -0700703 // Return the index of the matching batch, or -1 if none found.
704 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700705 final int N = mAlarmBatches.size();
706 for (int i = 0; i < N; i++) {
707 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700708 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700709 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700710 }
711 }
Christopher Tate385e4982013-07-23 18:22:29 -0700712 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700713 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800714 /** @return total count of the alarms in a set of alarm batches. */
715 static int getAlarmCount(ArrayList<Batch> batches) {
716 int ret = 0;
717
718 final int size = batches.size();
719 for (int i = 0; i < size; i++) {
720 ret += batches.get(i).size();
721 }
722 return ret;
723 }
724
725 boolean haveAlarmsTimeTickAlarm(ArrayList<Alarm> alarms) {
726 if (alarms.size() == 0) {
727 return false;
728 }
729 final int batchSize = alarms.size();
730 for (int j = 0; j < batchSize; j++) {
731 if (alarms.get(j).operation == mTimeTickSender) {
732 return true;
733 }
734 }
735 return false;
736 }
737
738 boolean haveBatchesTimeTickAlarm(ArrayList<Batch> batches) {
739 final int numBatches = batches.size();
740 for (int i = 0; i < numBatches; i++) {
741 if (haveAlarmsTimeTickAlarm(batches.get(i).alarms)) {
742 return true;
743 }
744 }
745 return false;
746 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700747
748 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
749 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700750 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700751 rebatchAllAlarmsLocked(true);
752 }
753 }
754
755 void rebatchAllAlarmsLocked(boolean doValidate) {
Makoto Onuki5d93b832018-01-10 16:12:39 -0800756 final int oldCount =
757 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
758 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
759 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
760
Christopher Tate4cb338d2013-07-26 13:11:31 -0700761 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
762 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700763 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700764 final long nowElapsed = SystemClock.elapsedRealtime();
765 final int oldBatches = oldSet.size();
766 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
767 Batch batch = oldSet.get(batchNum);
768 final int N = batch.size();
769 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700770 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700771 }
772 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700773 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
774 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
775 + " to " + mPendingIdleUntil);
776 if (mPendingIdleUntil == null) {
777 // Somehow we lost this... we need to restore all of the pending alarms.
778 restorePendingWhileIdleAlarmsLocked();
779 }
780 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800781 final int newCount =
782 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
783 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
784 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
785
786 if (oldCount != newCount) {
787 Slog.wtf(TAG, "Rebatching: total count changed from " + oldCount + " to " + newCount);
788 }
789 if (oldHasTick != newHasTick) {
790 Slog.wtf(TAG, "Rebatching: hasTick changed from " + oldHasTick + " to " + newHasTick);
791 }
792
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700793 rescheduleKernelAlarmsLocked();
794 updateNextAlarmClockLocked();
795 }
796
797 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
798 a.when = a.origWhen;
799 long whenElapsed = convertToElapsed(a.when, a.type);
800 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700801 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700802 // Exact
803 maxElapsed = whenElapsed;
804 } else {
805 // Not exact. Preserve any explicit window, otherwise recalculate
806 // the window based on the alarm's new futurity. Note that this
807 // reflects a policy of preferring timely to deferred delivery.
808 maxElapsed = (a.windowLength > 0)
809 ? (whenElapsed + a.windowLength)
810 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
811 }
812 a.whenElapsed = whenElapsed;
813 a.maxWhenElapsed = maxElapsed;
814 setImplLocked(a, true, doValidate);
815 }
816
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700817 /**
818 * Sends alarms that were blocked due to user applied background restrictions - either because
819 * the user lifted those or the uid came to foreground.
820 *
821 * @param uid uid to filter on
822 * @param packageName package to filter on, or null for all packages in uid
823 */
824 void sendPendingBackgroundAlarmsLocked(int uid, String packageName) {
825 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(uid);
826 if (alarmsForUid == null || alarmsForUid.size() == 0) {
827 return;
828 }
829 final ArrayList<Alarm> alarmsToDeliver;
830 if (packageName != null) {
831 if (DEBUG_BG_LIMIT) {
832 Slog.d(TAG, "Sending blocked alarms for uid " + uid + ", package " + packageName);
833 }
834 alarmsToDeliver = new ArrayList<>();
835 for (int i = alarmsForUid.size() - 1; i >= 0; i--) {
836 final Alarm a = alarmsForUid.get(i);
837 if (a.matches(packageName)) {
838 alarmsToDeliver.add(alarmsForUid.remove(i));
839 }
840 }
841 if (alarmsForUid.size() == 0) {
842 mPendingBackgroundAlarms.remove(uid);
843 }
844 } else {
845 if (DEBUG_BG_LIMIT) {
846 Slog.d(TAG, "Sending blocked alarms for uid " + uid);
847 }
848 alarmsToDeliver = alarmsForUid;
849 mPendingBackgroundAlarms.remove(uid);
850 }
851 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
852 }
853
Makoto Onuki2206af32017-11-21 16:25:35 -0800854 /**
855 * Check all alarms in {@link #mPendingBackgroundAlarms} and send the ones that are not
856 * restricted.
857 *
858 * This is only called when the global "force all apps-standby" flag changes or when the
859 * power save whitelist changes, so it's okay to be slow.
860 */
861 void sendAllUnrestrictedPendingBackgroundAlarmsLocked() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700862 final ArrayList<Alarm> alarmsToDeliver = new ArrayList<>();
Makoto Onuki2206af32017-11-21 16:25:35 -0800863
864 findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
865 mPendingBackgroundAlarms, alarmsToDeliver, this::isBackgroundRestricted);
866
867 if (alarmsToDeliver.size() > 0) {
868 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
869 }
870 }
871
872 @VisibleForTesting
873 static void findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
874 SparseArray<ArrayList<Alarm>> pendingAlarms, ArrayList<Alarm> unrestrictedAlarms,
875 Predicate<Alarm> isBackgroundRestricted) {
876
877 for (int uidIndex = pendingAlarms.size() - 1; uidIndex >= 0; uidIndex--) {
878 final int uid = pendingAlarms.keyAt(uidIndex);
879 final ArrayList<Alarm> alarmsForUid = pendingAlarms.valueAt(uidIndex);
880
881 for (int alarmIndex = alarmsForUid.size() - 1; alarmIndex >= 0; alarmIndex--) {
882 final Alarm alarm = alarmsForUid.get(alarmIndex);
883
884 if (isBackgroundRestricted.test(alarm)) {
885 continue;
886 }
887
888 unrestrictedAlarms.add(alarm);
889 alarmsForUid.remove(alarmIndex);
890 }
891
892 if (alarmsForUid.size() == 0) {
893 pendingAlarms.removeAt(uidIndex);
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700894 }
895 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700896 }
897
898 private void deliverPendingBackgroundAlarmsLocked(ArrayList<Alarm> alarms, long nowELAPSED) {
899 final int N = alarms.size();
900 boolean hasWakeup = false;
901 for (int i = 0; i < N; i++) {
902 final Alarm alarm = alarms.get(i);
903 if (alarm.wakeup) {
904 hasWakeup = true;
905 }
906 alarm.count = 1;
907 // Recurring alarms may have passed several alarm intervals while the
908 // alarm was kept pending. Send the appropriate trigger count.
909 if (alarm.repeatInterval > 0) {
910 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
911 // Also schedule its next recurrence
912 final long delta = alarm.count * alarm.repeatInterval;
913 final long nextElapsed = alarm.whenElapsed + delta;
914 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
915 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
916 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
917 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
918 // Kernel alarms will be rescheduled as needed in setImplLocked
919 }
920 }
921 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
922 // No need to wakeup for non wakeup alarms
923 if (mPendingNonWakeupAlarms.size() == 0) {
924 mStartCurrentDelayTime = nowELAPSED;
925 mNextNonWakeupDeliveryTime = nowELAPSED
926 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
927 }
928 mPendingNonWakeupAlarms.addAll(alarms);
929 mNumDelayedAlarms += alarms.size();
930 } else {
931 if (DEBUG_BG_LIMIT) {
932 Slog.d(TAG, "Waking up to deliver pending blocked alarms");
933 }
934 // Since we are waking up, also deliver any pending non wakeup alarms we have.
935 if (mPendingNonWakeupAlarms.size() > 0) {
936 alarms.addAll(mPendingNonWakeupAlarms);
937 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
938 mTotalDelayTime += thisDelayTime;
939 if (mMaxDelayTime < thisDelayTime) {
940 mMaxDelayTime = thisDelayTime;
941 }
942 mPendingNonWakeupAlarms.clear();
943 }
944 calculateDeliveryPriorities(alarms);
945 Collections.sort(alarms, mAlarmDispatchComparator);
946 deliverAlarmsLocked(alarms, nowELAPSED);
947 }
948 }
949
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700950 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700951 if (RECORD_DEVICE_IDLE_ALARMS) {
952 IdleDispatchEntry ent = new IdleDispatchEntry();
953 ent.uid = 0;
954 ent.pkg = "FINISH IDLE";
955 ent.elapsedRealtime = SystemClock.elapsedRealtime();
956 mAllowWhileIdleDispatches.add(ent);
957 }
958
Dianne Hackborn35d54032015-04-23 10:30:43 -0700959 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700960 if (mPendingWhileIdleAlarms.size() > 0) {
961 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
962 mPendingWhileIdleAlarms = new ArrayList<>();
963 final long nowElapsed = SystemClock.elapsedRealtime();
964 for (int i=alarms.size() - 1; i >= 0; i--) {
965 Alarm a = alarms.get(i);
966 reAddAlarmLocked(a, nowElapsed, false);
967 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700968 }
Dianne Hackborn35d54032015-04-23 10:30:43 -0700969
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700970 // Make sure we are using the correct ALLOW_WHILE_IDLE min time.
Dianne Hackborna750a632015-06-16 17:18:23 -0700971 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700972
Dianne Hackborn35d54032015-04-23 10:30:43 -0700973 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700974 rescheduleKernelAlarmsLocked();
975 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -0700976
977 // And send a TIME_TICK right now, since it is important to get the UI updated.
978 try {
979 mTimeTickSender.send();
980 } catch (PendingIntent.CanceledException e) {
981 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700982 }
983
Christopher Tate14a7bb02015-10-01 10:24:31 -0700984 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -0800985 final PendingIntent mPendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -0700986 final long mWhenElapsed;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700987 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -0700988 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700989 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700990 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800991 final BroadcastStats mBroadcastStats;
992 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800993 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800994
Christopher Tate14a7bb02015-10-01 10:24:31 -0700995 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
996 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
997 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800998 mPendingIntent = pendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -0700999 mWhenElapsed = nowELAPSED;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001000 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -07001001 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001002 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001003 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001004 mBroadcastStats = (pendingIntent != null)
1005 ? service.getStatsLocked(pendingIntent)
1006 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001007 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001008 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001009 fs = new FilterStats(mBroadcastStats, mTag);
1010 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -08001011 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001012 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -08001013 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001014 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001015 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001016
1017 @Override
1018 public String toString() {
1019 return "InFlight{"
1020 + "pendingIntent=" + mPendingIntent
Christopher Tateeabba732017-08-17 17:12:52 -07001021 + ", when=" + mWhenElapsed
Makoto Onuki33955e12017-03-01 18:11:00 -08001022 + ", workSource=" + mWorkSource
1023 + ", uid=" + mUid
1024 + ", tag=" + mTag
1025 + ", broadcastStats=" + mBroadcastStats
1026 + ", filterStats=" + mFilterStats
1027 + ", alarmType=" + mAlarmType
1028 + "}";
1029 }
Kweku Adams61e03292017-10-19 14:27:12 -07001030
1031 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1032 final long token = proto.start(fieldId);
1033
1034 proto.write(InFlightProto.UID, mUid);
1035 proto.write(InFlightProto.TAG, mTag);
1036 proto.write(InFlightProto.WHEN_ELAPSED_MS, mWhenElapsed);
1037 proto.write(InFlightProto.ALARM_TYPE, mAlarmType);
1038 if (mPendingIntent != null) {
1039 mPendingIntent.writeToProto(proto, InFlightProto.PENDING_INTENT);
1040 }
1041 if (mBroadcastStats != null) {
1042 mBroadcastStats.writeToProto(proto, InFlightProto.BROADCAST_STATS);
1043 }
1044 if (mFilterStats != null) {
1045 mFilterStats.writeToProto(proto, InFlightProto.FILTER_STATS);
1046 }
1047 if (mWorkSource != null) {
1048 mWorkSource.writeToProto(proto, InFlightProto.WORK_SOURCE);
1049 }
1050
1051 proto.end(token);
1052 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001054
Adam Lesinski182f73f2013-12-05 16:48:06 -08001055 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -08001056 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001057 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001058
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001059 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -08001061 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 int numWakeup;
1063 long startTime;
1064 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -08001065
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001066 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001067 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001068 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001069 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001070
1071 @Override
1072 public String toString() {
1073 return "FilterStats{"
1074 + "tag=" + mTag
1075 + ", lastTime=" + lastTime
1076 + ", aggregateTime=" + aggregateTime
1077 + ", count=" + count
1078 + ", numWakeup=" + numWakeup
1079 + ", startTime=" + startTime
1080 + ", nesting=" + nesting
1081 + "}";
1082 }
Kweku Adams61e03292017-10-19 14:27:12 -07001083
1084 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1085 final long token = proto.start(fieldId);
1086
1087 proto.write(FilterStatsProto.TAG, mTag);
1088 proto.write(FilterStatsProto.LAST_FLIGHT_TIME_REALTIME, lastTime);
1089 proto.write(FilterStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1090 proto.write(FilterStatsProto.COUNT, count);
1091 proto.write(FilterStatsProto.WAKEUP_COUNT, numWakeup);
1092 proto.write(FilterStatsProto.START_TIME_REALTIME, startTime);
1093 proto.write(FilterStatsProto.NESTING, nesting);
1094
1095 proto.end(token);
1096 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001097 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001098
Adam Lesinski182f73f2013-12-05 16:48:06 -08001099 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001100 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001101 final String mPackageName;
1102
1103 long aggregateTime;
1104 int count;
1105 int numWakeup;
1106 long startTime;
1107 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001108 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -08001109
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001110 BroadcastStats(int uid, String packageName) {
1111 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001112 mPackageName = packageName;
1113 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001114
1115 @Override
1116 public String toString() {
1117 return "BroadcastStats{"
1118 + "uid=" + mUid
1119 + ", packageName=" + mPackageName
1120 + ", aggregateTime=" + aggregateTime
1121 + ", count=" + count
1122 + ", numWakeup=" + numWakeup
1123 + ", startTime=" + startTime
1124 + ", nesting=" + nesting
1125 + "}";
1126 }
Kweku Adams61e03292017-10-19 14:27:12 -07001127
1128 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1129 final long token = proto.start(fieldId);
1130
1131 proto.write(BroadcastStatsProto.UID, mUid);
1132 proto.write(BroadcastStatsProto.PACKAGE_NAME, mPackageName);
1133 proto.write(BroadcastStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1134 proto.write(BroadcastStatsProto.COUNT, count);
1135 proto.write(BroadcastStatsProto.WAKEUP_COUNT, numWakeup);
1136 proto.write(BroadcastStatsProto.START_TIME_REALTIME, startTime);
1137 proto.write(BroadcastStatsProto.NESTING, nesting);
1138
1139 proto.end(token);
1140 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001142
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001143 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
1144 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001145
1146 int mNumDelayedAlarms = 0;
1147 long mTotalDelayTime = 0;
1148 long mMaxDelayTime = 0;
1149
Adam Lesinski182f73f2013-12-05 16:48:06 -08001150 @Override
1151 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001152 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001153 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001154
1155 // We have to set current TimeZone info to kernel
1156 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -08001157 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001158
Christopher Tate247571462017-04-10 11:45:05 -07001159 // Also sure that we're booting with a halfway sensible current time
1160 if (mNativeData != 0) {
1161 final long systemBuildTime = Environment.getRootDirectory().lastModified();
1162 if (System.currentTimeMillis() < systemBuildTime) {
1163 Slog.i(TAG, "Current time only " + System.currentTimeMillis()
1164 + ", advancing to build time " + systemBuildTime);
1165 setKernelTime(mNativeData, systemBuildTime);
1166 }
1167 }
1168
Christopher Tatebb9cce52017-04-18 14:19:43 -07001169 // Determine SysUI's uid
1170 final PackageManager packMan = getContext().getPackageManager();
1171 try {
1172 PermissionInfo sysUiPerm = packMan.getPermissionInfo(SYSTEM_UI_SELF_PERMISSION, 0);
1173 ApplicationInfo sysUi = packMan.getApplicationInfo(sysUiPerm.packageName, 0);
1174 if ((sysUi.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1175 mSystemUiUid = sysUi.uid;
1176 } else {
1177 Slog.e(TAG, "SysUI permission " + SYSTEM_UI_SELF_PERMISSION
1178 + " defined by non-privileged app " + sysUi.packageName
1179 + " - ignoring");
1180 }
1181 } catch (NameNotFoundException e) {
1182 }
1183
1184 if (mSystemUiUid <= 0) {
1185 Slog.wtf(TAG, "SysUI package not found!");
1186 }
1187
Adam Lesinski182f73f2013-12-05 16:48:06 -08001188 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001189 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001190
Adam Lesinski182f73f2013-12-05 16:48:06 -08001191 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001193 Intent.FLAG_RECEIVER_REGISTERED_ONLY
Chad Brubaker291df4f2017-03-14 10:23:02 -07001194 | Intent.FLAG_RECEIVER_FOREGROUND
1195 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001196 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001197 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001198 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1199 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001200 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001201 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
Kweku Adams61e03292017-10-19 14:27:12 -07001202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001203 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -08001204 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205 mClockReceiver.scheduleTimeTickEvent();
1206 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001207 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208 mUninstallReceiver = new UninstallReceiver();
Kweku Adams61e03292017-10-19 14:27:12 -07001209
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001210 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001211 AlarmThread waitThread = new AlarmThread();
1212 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001214 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001215 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001216
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001217 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001218 ActivityManager.getService().registerUidObserver(new UidObserver(),
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001219 ActivityManager.UID_OBSERVER_GONE | ActivityManager.UID_OBSERVER_IDLE
1220 | ActivityManager.UID_OBSERVER_ACTIVE,
1221 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001222 } catch (RemoteException e) {
1223 // ignored; both services live in system_server
1224 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001225 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001227
1228 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001229 public void onBootPhase(int phase) {
1230 if (phase == PHASE_SYSTEM_SERVICES_READY) {
Suprabh Shukla4deb8522018-01-08 16:27:10 -08001231 mForceAppStandbyTracker.start();
Dianne Hackborna750a632015-06-16 17:18:23 -07001232 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -07001233 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001234 mLocalDeviceIdleController
1235 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackborna750a632015-06-16 17:18:23 -07001236 }
1237 }
1238
1239 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001240 protected void finalize() throws Throwable {
1241 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001242 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001243 } finally {
1244 super.finalize();
1245 }
1246 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001247
Adam Lesinski182f73f2013-12-05 16:48:06 -08001248 void setTimeZoneImpl(String tz) {
1249 if (TextUtils.isEmpty(tz)) {
1250 return;
David Christieebe51fc2013-07-26 13:23:29 -07001251 }
1252
Adam Lesinski182f73f2013-12-05 16:48:06 -08001253 TimeZone zone = TimeZone.getTimeZone(tz);
1254 // Prevent reentrant calls from stepping on each other when writing
1255 // the time zone property
1256 boolean timeZoneWasChanged = false;
1257 synchronized (this) {
1258 String current = SystemProperties.get(TIMEZONE_PROPERTY);
1259 if (current == null || !current.equals(zone.getID())) {
1260 if (localLOGV) {
1261 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
1262 }
1263 timeZoneWasChanged = true;
1264 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
1265 }
1266
1267 // Update the kernel timezone information
1268 // Kernel tracks time offsets as 'minutes west of GMT'
1269 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001270 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001271 }
1272
1273 TimeZone.setDefault(null);
1274
1275 if (timeZoneWasChanged) {
1276 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001277 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate5cdf9f82017-05-03 18:10:39 -07001278 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
Chad Brubaker291df4f2017-03-14 10:23:02 -07001279 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001280 intent.putExtra("time-zone", zone.getID());
1281 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1282 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001284
Adam Lesinski182f73f2013-12-05 16:48:06 -08001285 void removeImpl(PendingIntent operation) {
1286 if (operation == null) {
1287 return;
1288 }
1289 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001290 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001291 }
1292 }
1293
1294 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001295 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1296 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1297 int callingUid, String callingPackage) {
1298 // must be *either* PendingIntent or AlarmReceiver, but not both
1299 if ((operation == null && directReceiver == null)
1300 || (operation != null && directReceiver != null)) {
1301 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1302 // NB: previous releases failed silently here, so we are continuing to do the same
1303 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 return;
1305 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001306
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001307 // Sanity check the window length. This will catch people mistakenly
1308 // trying to pass an end-of-window timestamp rather than a duration.
1309 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1310 Slog.w(TAG, "Window length " + windowLength
1311 + "ms suspiciously long; limiting to 1 hour");
1312 windowLength = AlarmManager.INTERVAL_HOUR;
1313 }
1314
Christopher Tate498c6cb2014-11-17 16:09:27 -08001315 // Sanity check the recurrence interval. This will catch people who supply
1316 // seconds when the API expects milliseconds.
Dianne Hackborna750a632015-06-16 17:18:23 -07001317 final long minInterval = mConstants.MIN_INTERVAL;
1318 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001319 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001320 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001321 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001322 interval = minInterval;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001323 }
1324
Christopher Tatee0a22b32013-07-11 14:43:13 -07001325 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1326 throw new IllegalArgumentException("Invalid alarm type " + type);
1327 }
1328
Christopher Tate5f221e82013-07-30 17:13:15 -07001329 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001330 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001331 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001332 + " pid=" + what);
1333 triggerAtTime = 0;
1334 }
1335
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001336 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001337 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1338 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001339 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001340 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1341
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001342 final long maxElapsed;
1343 if (windowLength == AlarmManager.WINDOW_EXACT) {
1344 maxElapsed = triggerElapsed;
1345 } else if (windowLength < 0) {
1346 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001347 // Fix this window in place, so that as time approaches we don't collapse it.
1348 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001349 } else {
1350 maxElapsed = triggerElapsed + windowLength;
1351 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001353 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001354 if (DEBUG_BATCH) {
1355 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001356 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001357 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001358 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001359 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001360 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001361 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1362 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363 }
1364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365
Christopher Tate3e04b472013-10-21 17:51:31 -07001366 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001367 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1368 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1369 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001370 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001371 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1372 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001373 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001374 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001375 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1376 + " -- package not allowed to start");
1377 return;
1378 }
1379 } catch (RemoteException e) {
1380 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001381 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001382 setImplLocked(a, false, doValidate);
1383 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001384
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001385 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1386 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001387 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001388 // The caller has given the time they want this to happen at, however we need
1389 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001390 // bring us out of idle at an earlier time.
1391 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001392 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001393 }
1394 // Add fuzz to make the alarm go off some time before the actual desired time.
1395 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001396 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001397 if (fuzz > 0) {
1398 if (mRandom == null) {
1399 mRandom = new Random();
1400 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001401 final int delta = mRandom.nextInt(fuzz);
1402 a.whenElapsed -= delta;
1403 if (false) {
1404 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1405 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1406 Slog.d(TAG, "Applied fuzz: " + fuzz);
1407 Slog.d(TAG, "Final delta: " + delta);
1408 Slog.d(TAG, "Final when: " + a.whenElapsed);
1409 }
1410 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001411 }
1412
1413 } else if (mPendingIdleUntil != null) {
1414 // We currently have an idle until alarm scheduled; if the new alarm has
1415 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001416 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1417 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1418 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001419 == 0) {
1420 mPendingWhileIdleAlarms.add(a);
1421 return;
1422 }
1423 }
1424
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001425 if (RECORD_DEVICE_IDLE_ALARMS) {
1426 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1427 IdleDispatchEntry ent = new IdleDispatchEntry();
1428 ent.uid = a.uid;
1429 ent.pkg = a.operation.getCreatorPackage();
1430 ent.tag = a.operation.getTag("");
1431 ent.op = "SET";
1432 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1433 ent.argRealtime = a.whenElapsed;
1434 mAllowWhileIdleDispatches.add(ent);
1435 }
1436 }
1437
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001438 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
1439 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -07001440 if (whichBatch < 0) {
1441 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001442 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 } else {
Christopher Tate385e4982013-07-23 18:22:29 -07001444 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001445 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001446 // The start time of this batch advanced, so batch ordering may
1447 // have just been broken. Move it to where it now belongs.
1448 mAlarmBatches.remove(whichBatch);
1449 addBatchLocked(mAlarmBatches, batch);
1450 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451 }
1452
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001453 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001454 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001455 }
1456
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001457 boolean needRebatch = false;
1458
1459 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001460 if (RECORD_DEVICE_IDLE_ALARMS) {
1461 if (mPendingIdleUntil == null) {
1462 IdleDispatchEntry ent = new IdleDispatchEntry();
1463 ent.uid = 0;
1464 ent.pkg = "START IDLE";
1465 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1466 mAllowWhileIdleDispatches.add(ent);
1467 }
1468 }
Makoto Onuki4274a6d2017-04-21 12:21:25 -07001469 if ((mPendingIdleUntil != a) && (mPendingIdleUntil != null)) {
1470 Slog.wtfStack(TAG, "setImplLocked: idle until changed from " + mPendingIdleUntil
1471 + " to " + a);
1472 }
1473
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001474 mPendingIdleUntil = a;
Dianne Hackborna750a632015-06-16 17:18:23 -07001475 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001476 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001477 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1478 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1479 mNextWakeFromIdle = a;
1480 // If this wake from idle is earlier than whatever was previously scheduled,
1481 // and we are currently idling, then we need to rebatch alarms in case the idle
1482 // until time needs to be updated.
1483 if (mPendingIdleUntil != null) {
1484 needRebatch = true;
1485 }
1486 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001487 }
1488
1489 if (!rebatching) {
1490 if (DEBUG_VALIDATE) {
1491 if (doValidate && !validateConsistencyLocked()) {
1492 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1493 + " when(hex)=" + Long.toHexString(a.when)
1494 + " whenElapsed=" + a.whenElapsed
1495 + " maxWhenElapsed=" + a.maxWhenElapsed
1496 + " interval=" + a.repeatInterval + " op=" + a.operation
1497 + " flags=0x" + Integer.toHexString(a.flags));
1498 rebatchAllAlarmsLocked(false);
1499 needRebatch = false;
1500 }
1501 }
1502
1503 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001504 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001505 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001506
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001507 rescheduleKernelAlarmsLocked();
1508 updateNextAlarmClockLocked();
1509 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001510 }
1511
Christopher Tate1d99c392017-12-07 16:54:04 -08001512 /**
1513 * System-process internal API
1514 */
1515 private final class LocalService implements AlarmManagerInternal {
1516 @Override
1517 public void removeAlarmsForUid(int uid) {
1518 synchronized (mLock) {
1519 removeLocked(uid);
1520 }
1521 }
1522 }
1523
1524 /**
1525 * Public-facing binder interface
1526 */
Adam Lesinski182f73f2013-12-05 16:48:06 -08001527 private final IBinder mService = new IAlarmManager.Stub() {
1528 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001529 public void set(String callingPackage,
1530 int type, long triggerAtTime, long windowLength, long interval, int flags,
1531 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1532 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001533 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001534
1535 // make sure the caller is not lying about which package should be blamed for
1536 // wakelock time spent in alarm delivery
1537 mAppOps.checkPackage(callingUid, callingPackage);
1538
1539 // Repeating alarms must use PendingIntent, not direct listener
1540 if (interval != 0) {
1541 if (directReceiver != null) {
1542 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1543 }
1544 }
1545
Adam Lesinski182f73f2013-12-05 16:48:06 -08001546 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001547 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001548 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001549 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001550 }
1551
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001552 // No incoming callers can request either WAKE_FROM_IDLE or
1553 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1554 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1555 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1556
1557 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1558 // manager when to come out of idle mode, which is only for DeviceIdleController.
1559 if (callingUid != Process.SYSTEM_UID) {
1560 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1561 }
1562
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001563 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001564 if (windowLength == AlarmManager.WINDOW_EXACT) {
1565 flags |= AlarmManager.FLAG_STANDALONE;
1566 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001567
1568 // If this alarm is for an alarm clock, then it must be standalone and we will
1569 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001570 if (alarmClock != null) {
1571 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001572
1573 // If the caller is a core system component or on the user's whitelist, and not calling
1574 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1575 // This means we will allow these alarms to go off as normal even while idle, with no
1576 // timing restrictions.
1577 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
Christopher Tatebb9cce52017-04-18 14:19:43 -07001578 || callingUid == mSystemUiUid
Makoto Onuki2206af32017-11-21 16:25:35 -08001579 || mForceAppStandbyTracker.isUidPowerSaveWhitelisted(callingUid))) {
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001580 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1581 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001582 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001583
Christopher Tate14a7bb02015-10-01 10:24:31 -07001584 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1585 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001586 }
Christopher Tate89779822012-08-31 14:40:03 -07001587
Adam Lesinski182f73f2013-12-05 16:48:06 -08001588 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001589 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001590 getContext().enforceCallingOrSelfPermission(
1591 "android.permission.SET_TIME",
1592 "setTime");
1593
Greg Hackmann0cab8962014-02-21 16:35:52 -08001594 if (mNativeData == 0) {
1595 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1596 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001597 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001598
1599 synchronized (mLock) {
1600 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001603
1604 @Override
1605 public void setTimeZone(String tz) {
1606 getContext().enforceCallingOrSelfPermission(
1607 "android.permission.SET_TIME_ZONE",
1608 "setTimeZone");
1609
1610 final long oldId = Binder.clearCallingIdentity();
1611 try {
1612 setTimeZoneImpl(tz);
1613 } finally {
1614 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 }
1616 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001617
Adam Lesinski182f73f2013-12-05 16:48:06 -08001618 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001619 public void remove(PendingIntent operation, IAlarmListener listener) {
1620 if (operation == null && listener == null) {
1621 Slog.w(TAG, "remove() with no intent or listener");
1622 return;
1623 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001624
Christopher Tate14a7bb02015-10-01 10:24:31 -07001625 synchronized (mLock) {
1626 removeLocked(operation, listener);
1627 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001629
Adam Lesinski182f73f2013-12-05 16:48:06 -08001630 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001631 public long getNextWakeFromIdleTime() {
1632 return getNextWakeFromIdleTimeImpl();
1633 }
1634
1635 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001636 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001637 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1638 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1639 "getNextAlarmClock", null);
1640
1641 return getNextAlarmClockImpl(userId);
1642 }
1643
1644 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001645 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06001646 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Kweku Adams61e03292017-10-19 14:27:12 -07001647
1648 if (args.length > 0 && "--proto".equals(args[0])) {
1649 dumpProto(fd);
1650 } else {
1651 dumpImpl(pw);
1652 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001653 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001654 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001655
Adam Lesinski182f73f2013-12-05 16:48:06 -08001656 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657 synchronized (mLock) {
1658 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001659 mConstants.dump(pw);
1660 pw.println();
1661
Makoto Onuki2206af32017-11-21 16:25:35 -08001662 mForceAppStandbyTracker.dump(pw, " ");
Christopher Tate12cf0b62018-01-05 18:40:14 -08001663 pw.println();
Makoto Onuki2206af32017-11-21 16:25:35 -08001664
Christopher Tatee0a22b32013-07-11 14:43:13 -07001665 final long nowRTC = System.currentTimeMillis();
1666 final long nowELAPSED = SystemClock.elapsedRealtime();
Makoto Onuki5d93b832018-01-10 16:12:39 -08001667 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001668
Dianne Hackborna750a632015-06-16 17:18:23 -07001669 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001670 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001671 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001672 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001673 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001674 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001675 pw.print(" mLastTimeChangeRealtime="); pw.println(mLastTimeChangeRealtime);
1676 pw.print(" mLastTickIssued=");
Makoto Onuki5d93b832018-01-10 16:12:39 -08001677 pw.println(sdf.format(new Date(nowRTC - (nowELAPSED - mLastTickIssued))));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001678 pw.print(" mLastTickReceived="); pw.println(sdf.format(new Date(mLastTickReceived)));
1679 pw.print(" mLastTickSet="); pw.println(sdf.format(new Date(mLastTickSet)));
Makoto Onuki5d93b832018-01-10 16:12:39 -08001680 pw.print(" mLastTickAdded="); pw.println(sdf.format(new Date(mLastTickAdded)));
1681 pw.print(" mLastTickRemoved="); pw.println(sdf.format(new Date(mLastTickRemoved)));
Dianne Hackbornc3527222015-05-13 14:03:20 -07001682 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001683 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001684 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001685 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1686 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001687 pw.print(" Max wakeup delay: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001688 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1689 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001690 pw.print(" Time since last dispatch: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001691 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1692 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001693 pw.print(" Next non-wakeup delivery time: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001694 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1695 pw.println();
1696 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001697
1698 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1699 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001700 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001701 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001702 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001703 pw.print(" Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001704 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001705 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
1706 pw.print(" set at "); TimeUtils.formatDuration(mLastWakeupSet, nowELAPSED, pw);
1707 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001708 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001709
John Spurlock604a5ee2015-06-01 12:27:22 -04001710 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001711 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001712 final TreeSet<Integer> users = new TreeSet<>();
1713 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1714 users.add(mNextAlarmClockForUser.keyAt(i));
1715 }
1716 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1717 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1718 }
1719 for (int user : users) {
1720 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1721 final long time = next != null ? next.getTriggerTime() : 0;
1722 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001723 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001724 pw.print(" pendingSend:"); pw.print(pendingSend);
1725 pw.print(" time:"); pw.print(time);
1726 if (time > 0) {
1727 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1728 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1729 }
1730 pw.println();
1731 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001732 if (mAlarmBatches.size() > 0) {
1733 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001734 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001735 pw.println(mAlarmBatches.size());
1736 for (Batch b : mAlarmBatches) {
1737 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001738 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001739 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001741 pw.println();
1742 pw.println(" Pending user blocked background alarms: ");
1743 boolean blocked = false;
1744 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
1745 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
1746 if (blockedAlarms != null && blockedAlarms.size() > 0) {
1747 blocked = true;
1748 dumpAlarmList(pw, blockedAlarms, " ", nowELAPSED, nowRTC, sdf);
1749 }
1750 }
1751 if (!blocked) {
1752 pw.println(" none");
1753 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001754 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001755 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001756 pw.println(" Idle mode state:");
1757 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001758 if (mPendingIdleUntil != null) {
1759 pw.println(mPendingIdleUntil);
Kweku Adams61e03292017-10-19 14:27:12 -07001760 mPendingIdleUntil.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001761 } else {
1762 pw.println("null");
1763 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001764 pw.println(" Pending alarms:");
1765 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001766 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001767 if (mNextWakeFromIdle != null) {
1768 pw.println();
1769 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
Kweku Adams61e03292017-10-19 14:27:12 -07001770 mNextWakeFromIdle.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001771 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001772
1773 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001774 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001775 if (mPendingNonWakeupAlarms.size() > 0) {
1776 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001777 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001778 } else {
1779 pw.println("(none)");
1780 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001781 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001782 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1783 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001784 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001785 pw.print(", max non-interactive time: ");
1786 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1787 pw.println();
1788
1789 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001790 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Christopher Tateeabba732017-08-17 17:12:52 -07001791 pw.print(" PendingIntent send count: "); pw.println(mSendCount);
1792 pw.print(" PendingIntent finish count: "); pw.println(mSendFinishCount);
1793 pw.print(" Listener send count: "); pw.println(mListenerCount);
1794 pw.print(" Listener finish count: "); pw.println(mListenerFinishCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001795 pw.println();
1796
Christopher Tate7f2a0352015-12-08 10:24:33 -08001797 if (mInFlight.size() > 0) {
1798 pw.println("Outstanding deliveries:");
1799 for (int i = 0; i < mInFlight.size(); i++) {
1800 pw.print(" #"); pw.print(i); pw.print(": ");
1801 pw.println(mInFlight.get(i));
1802 }
1803 pw.println();
1804 }
1805
Dianne Hackborna750a632015-06-16 17:18:23 -07001806 pw.print(" mAllowWhileIdleMinTime=");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001807 TimeUtils.formatDuration(mAllowWhileIdleMinTime, pw);
1808 pw.println();
1809 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001810 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001811 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
1812 pw.print(" UID ");
1813 UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
1814 pw.print(": ");
1815 TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i),
1816 nowELAPSED, pw);
1817 pw.println();
1818 }
1819 }
1820 pw.println();
1821
Dianne Hackborn81038902012-11-26 17:04:09 -08001822 if (mLog.dump(pw, " Recent problems", " ")) {
1823 pw.println();
1824 }
1825
1826 final FilterStats[] topFilters = new FilterStats[10];
1827 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1828 @Override
1829 public int compare(FilterStats lhs, FilterStats rhs) {
1830 if (lhs.aggregateTime < rhs.aggregateTime) {
1831 return 1;
1832 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1833 return -1;
1834 }
1835 return 0;
1836 }
1837 };
1838 int len = 0;
Kweku Adams61e03292017-10-19 14:27:12 -07001839 // Get the top 10 FilterStats, ordered by aggregateTime.
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001840 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1841 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1842 for (int ip=0; ip<uidStats.size(); ip++) {
1843 BroadcastStats bs = uidStats.valueAt(ip);
1844 for (int is=0; is<bs.filterStats.size(); is++) {
1845 FilterStats fs = bs.filterStats.valueAt(is);
1846 int pos = len > 0
1847 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1848 if (pos < 0) {
1849 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001850 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001851 if (pos < topFilters.length) {
1852 int copylen = topFilters.length - pos - 1;
1853 if (copylen > 0) {
1854 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1855 }
1856 topFilters[pos] = fs;
1857 if (len < topFilters.length) {
1858 len++;
1859 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001860 }
1861 }
1862 }
1863 }
1864 if (len > 0) {
1865 pw.println(" Top Alarms:");
1866 for (int i=0; i<len; i++) {
1867 FilterStats fs = topFilters[i];
1868 pw.print(" ");
1869 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1870 TimeUtils.formatDuration(fs.aggregateTime, pw);
1871 pw.print(" running, "); pw.print(fs.numWakeup);
1872 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001873 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1874 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001875 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001876 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001877 pw.println();
1878 }
1879 }
1880
1881 pw.println(" ");
1882 pw.println(" Alarm Stats:");
1883 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001884 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1885 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1886 for (int ip=0; ip<uidStats.size(); ip++) {
1887 BroadcastStats bs = uidStats.valueAt(ip);
1888 pw.print(" ");
1889 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1890 UserHandle.formatUid(pw, bs.mUid);
1891 pw.print(":");
1892 pw.print(bs.mPackageName);
1893 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1894 pw.print(" running, "); pw.print(bs.numWakeup);
1895 pw.println(" wakeups:");
1896 tmpFilters.clear();
1897 for (int is=0; is<bs.filterStats.size(); is++) {
1898 tmpFilters.add(bs.filterStats.valueAt(is));
1899 }
1900 Collections.sort(tmpFilters, comparator);
1901 for (int i=0; i<tmpFilters.size(); i++) {
1902 FilterStats fs = tmpFilters.get(i);
1903 pw.print(" ");
1904 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1905 TimeUtils.formatDuration(fs.aggregateTime, pw);
1906 pw.print(" "); pw.print(fs.numWakeup);
1907 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001908 pw.print(" alarms, last ");
1909 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1910 pw.println(":");
1911 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001912 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001913 pw.println();
1914 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915 }
1916 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001917
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001918 if (RECORD_DEVICE_IDLE_ALARMS) {
1919 pw.println();
1920 pw.println(" Allow while idle dispatches:");
1921 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
1922 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
1923 pw.print(" ");
1924 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
1925 pw.print(": ");
1926 UserHandle.formatUid(pw, ent.uid);
1927 pw.print(":");
1928 pw.println(ent.pkg);
1929 if (ent.op != null) {
1930 pw.print(" ");
1931 pw.print(ent.op);
1932 pw.print(" / ");
1933 pw.print(ent.tag);
1934 if (ent.argRealtime != 0) {
1935 pw.print(" (");
1936 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
1937 pw.print(")");
1938 }
1939 pw.println();
1940 }
1941 }
1942 }
1943
Christopher Tate18a75f12013-07-01 18:18:59 -07001944 if (WAKEUP_STATS) {
1945 pw.println();
1946 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001947 long last = -1;
1948 for (WakeupEvent event : mRecentWakeups) {
1949 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1950 pw.print('|');
1951 if (last < 0) {
1952 pw.print('0');
1953 } else {
1954 pw.print(event.when - last);
1955 }
1956 last = event.when;
1957 pw.print('|'); pw.print(event.uid);
1958 pw.print('|'); pw.print(event.action);
1959 pw.println();
1960 }
1961 pw.println();
1962 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001963 }
1964 }
1965
Kweku Adams61e03292017-10-19 14:27:12 -07001966 void dumpProto(FileDescriptor fd) {
1967 final ProtoOutputStream proto = new ProtoOutputStream(fd);
1968
1969 synchronized (mLock) {
1970 final long nowRTC = System.currentTimeMillis();
1971 final long nowElapsed = SystemClock.elapsedRealtime();
1972 proto.write(AlarmManagerServiceProto.CURRENT_TIME, nowRTC);
1973 proto.write(AlarmManagerServiceProto.ELAPSED_REALTIME, nowElapsed);
1974 proto.write(AlarmManagerServiceProto.LAST_TIME_CHANGE_CLOCK_TIME,
1975 mLastTimeChangeClockTime);
1976 proto.write(AlarmManagerServiceProto.LAST_TIME_CHANGE_REALTIME,
1977 mLastTimeChangeRealtime);
1978
1979 mConstants.dumpProto(proto, AlarmManagerServiceProto.SETTINGS);
1980
Makoto Onuki2206af32017-11-21 16:25:35 -08001981 mForceAppStandbyTracker.dumpProto(proto,
1982 AlarmManagerServiceProto.FORCE_APP_STANDBY_TRACKER);
Kweku Adams61e03292017-10-19 14:27:12 -07001983
1984 proto.write(AlarmManagerServiceProto.IS_INTERACTIVE, mInteractive);
1985 if (!mInteractive) {
1986 // Durations
1987 proto.write(AlarmManagerServiceProto.TIME_SINCE_NON_INTERACTIVE_MS,
1988 nowElapsed - mNonInteractiveStartTime);
1989 proto.write(AlarmManagerServiceProto.MAX_WAKEUP_DELAY_MS,
1990 currentNonWakeupFuzzLocked(nowElapsed));
1991 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_DISPATCH_MS,
1992 nowElapsed - mLastAlarmDeliveryTime);
1993 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_NON_WAKEUP_DELIVERY_MS,
1994 nowElapsed - mNextNonWakeupDeliveryTime);
1995 }
1996
1997 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_NON_WAKEUP_ALARM_MS,
1998 mNextNonWakeup - nowElapsed);
1999 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_WAKEUP_MS,
2000 mNextWakeup - nowElapsed);
2001 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_WAKEUP_MS,
2002 nowElapsed - mLastWakeup);
2003 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_WAKEUP_SET_MS,
2004 nowElapsed - mLastWakeupSet);
2005 proto.write(AlarmManagerServiceProto.TIME_CHANGE_EVENT_COUNT, mNumTimeChanged);
Kweku Adams61e03292017-10-19 14:27:12 -07002006
2007 final TreeSet<Integer> users = new TreeSet<>();
2008 final int nextAlarmClockForUserSize = mNextAlarmClockForUser.size();
2009 for (int i = 0; i < nextAlarmClockForUserSize; i++) {
2010 users.add(mNextAlarmClockForUser.keyAt(i));
2011 }
2012 final int pendingSendNextAlarmClockChangedForUserSize =
2013 mPendingSendNextAlarmClockChangedForUser.size();
2014 for (int i = 0; i < pendingSendNextAlarmClockChangedForUserSize; i++) {
2015 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2016 }
2017 for (int user : users) {
2018 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2019 final long time = next != null ? next.getTriggerTime() : 0;
2020 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
2021 final long aToken = proto.start(AlarmManagerServiceProto.NEXT_ALARM_CLOCK_METADATA);
2022 proto.write(AlarmClockMetadataProto.USER, user);
2023 proto.write(AlarmClockMetadataProto.IS_PENDING_SEND, pendingSend);
2024 proto.write(AlarmClockMetadataProto.TRIGGER_TIME_MS, time);
2025 proto.end(aToken);
2026 }
2027 for (Batch b : mAlarmBatches) {
2028 b.writeToProto(proto, AlarmManagerServiceProto.PENDING_ALARM_BATCHES,
2029 nowElapsed, nowRTC);
2030 }
2031 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2032 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2033 if (blockedAlarms != null) {
2034 for (Alarm a : blockedAlarms) {
2035 a.writeToProto(proto,
2036 AlarmManagerServiceProto.PENDING_USER_BLOCKED_BACKGROUND_ALARMS,
2037 nowElapsed, nowRTC);
2038 }
2039 }
2040 }
2041 if (mPendingIdleUntil != null) {
2042 mPendingIdleUntil.writeToProto(
2043 proto, AlarmManagerServiceProto.PENDING_IDLE_UNTIL, nowElapsed, nowRTC);
2044 }
2045 for (Alarm a : mPendingWhileIdleAlarms) {
2046 a.writeToProto(proto, AlarmManagerServiceProto.PENDING_WHILE_IDLE_ALARMS,
2047 nowElapsed, nowRTC);
2048 }
2049 if (mNextWakeFromIdle != null) {
2050 mNextWakeFromIdle.writeToProto(proto, AlarmManagerServiceProto.NEXT_WAKE_FROM_IDLE,
2051 nowElapsed, nowRTC);
2052 }
2053
2054 for (Alarm a : mPendingNonWakeupAlarms) {
2055 a.writeToProto(proto, AlarmManagerServiceProto.PAST_DUE_NON_WAKEUP_ALARMS,
2056 nowElapsed, nowRTC);
2057 }
2058
2059 proto.write(AlarmManagerServiceProto.DELAYED_ALARM_COUNT, mNumDelayedAlarms);
2060 proto.write(AlarmManagerServiceProto.TOTAL_DELAY_TIME_MS, mTotalDelayTime);
2061 proto.write(AlarmManagerServiceProto.MAX_DELAY_DURATION_MS, mMaxDelayTime);
2062 proto.write(AlarmManagerServiceProto.MAX_NON_INTERACTIVE_DURATION_MS,
2063 mNonInteractiveTime);
2064
2065 proto.write(AlarmManagerServiceProto.BROADCAST_REF_COUNT, mBroadcastRefCount);
2066 proto.write(AlarmManagerServiceProto.PENDING_INTENT_SEND_COUNT, mSendCount);
2067 proto.write(AlarmManagerServiceProto.PENDING_INTENT_FINISH_COUNT, mSendFinishCount);
2068 proto.write(AlarmManagerServiceProto.LISTENER_SEND_COUNT, mListenerCount);
2069 proto.write(AlarmManagerServiceProto.LISTENER_FINISH_COUNT, mListenerFinishCount);
2070
2071 for (InFlight f : mInFlight) {
2072 f.writeToProto(proto, AlarmManagerServiceProto.OUTSTANDING_DELIVERIES);
2073 }
2074
2075 proto.write(AlarmManagerServiceProto.ALLOW_WHILE_IDLE_MIN_DURATION_MS,
2076 mAllowWhileIdleMinTime);
2077 for (int i = 0; i < mLastAllowWhileIdleDispatch.size(); ++i) {
2078 final long token = proto.start(
2079 AlarmManagerServiceProto.LAST_ALLOW_WHILE_IDLE_DISPATCH_TIMES);
2080 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.UID,
2081 mLastAllowWhileIdleDispatch.keyAt(i));
2082 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.TIME_MS,
2083 mLastAllowWhileIdleDispatch.valueAt(i));
2084 proto.end(token);
2085 }
2086
2087 mLog.writeToProto(proto, AlarmManagerServiceProto.RECENT_PROBLEMS);
2088
2089 final FilterStats[] topFilters = new FilterStats[10];
2090 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2091 @Override
2092 public int compare(FilterStats lhs, FilterStats rhs) {
2093 if (lhs.aggregateTime < rhs.aggregateTime) {
2094 return 1;
2095 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2096 return -1;
2097 }
2098 return 0;
2099 }
2100 };
2101 int len = 0;
2102 // Get the top 10 FilterStats, ordered by aggregateTime.
2103 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2104 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2105 for (int ip = 0; ip < uidStats.size(); ++ip) {
2106 BroadcastStats bs = uidStats.valueAt(ip);
2107 for (int is = 0; is < bs.filterStats.size(); ++is) {
2108 FilterStats fs = bs.filterStats.valueAt(is);
2109 int pos = len > 0
2110 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2111 if (pos < 0) {
2112 pos = -pos - 1;
2113 }
2114 if (pos < topFilters.length) {
2115 int copylen = topFilters.length - pos - 1;
2116 if (copylen > 0) {
2117 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2118 }
2119 topFilters[pos] = fs;
2120 if (len < topFilters.length) {
2121 len++;
2122 }
2123 }
2124 }
2125 }
2126 }
2127 for (int i = 0; i < len; ++i) {
2128 final long token = proto.start(AlarmManagerServiceProto.TOP_ALARMS);
2129 FilterStats fs = topFilters[i];
2130
2131 proto.write(AlarmManagerServiceProto.TopAlarm.UID, fs.mBroadcastStats.mUid);
2132 proto.write(AlarmManagerServiceProto.TopAlarm.PACKAGE_NAME,
2133 fs.mBroadcastStats.mPackageName);
2134 fs.writeToProto(proto, AlarmManagerServiceProto.TopAlarm.FILTER);
2135
2136 proto.end(token);
2137 }
2138
2139 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
2140 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2141 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2142 for (int ip = 0; ip < uidStats.size(); ++ip) {
2143 final long token = proto.start(AlarmManagerServiceProto.ALARM_STATS);
2144
2145 BroadcastStats bs = uidStats.valueAt(ip);
2146 bs.writeToProto(proto, AlarmManagerServiceProto.AlarmStat.BROADCAST);
2147
2148 // uidStats is an ArrayMap, which we can't sort.
2149 tmpFilters.clear();
2150 for (int is = 0; is < bs.filterStats.size(); ++is) {
2151 tmpFilters.add(bs.filterStats.valueAt(is));
2152 }
2153 Collections.sort(tmpFilters, comparator);
2154 for (FilterStats fs : tmpFilters) {
2155 fs.writeToProto(proto, AlarmManagerServiceProto.AlarmStat.FILTERS);
2156 }
2157
2158 proto.end(token);
2159 }
2160 }
2161
2162 if (RECORD_DEVICE_IDLE_ALARMS) {
2163 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2164 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2165 final long token = proto.start(
2166 AlarmManagerServiceProto.ALLOW_WHILE_IDLE_DISPATCHES);
2167
2168 proto.write(IdleDispatchEntryProto.UID, ent.uid);
2169 proto.write(IdleDispatchEntryProto.PKG, ent.pkg);
2170 proto.write(IdleDispatchEntryProto.TAG, ent.tag);
2171 proto.write(IdleDispatchEntryProto.OP, ent.op);
2172 proto.write(IdleDispatchEntryProto.ENTRY_CREATION_REALTIME,
2173 ent.elapsedRealtime);
2174 proto.write(IdleDispatchEntryProto.ARG_REALTIME, ent.argRealtime);
2175
2176 proto.end(token);
2177 }
2178 }
2179
2180 if (WAKEUP_STATS) {
2181 for (WakeupEvent event : mRecentWakeups) {
2182 final long token = proto.start(AlarmManagerServiceProto.RECENT_WAKEUP_HISTORY);
2183 proto.write(WakeupEventProto.UID, event.uid);
2184 proto.write(WakeupEventProto.ACTION, event.action);
2185 proto.write(WakeupEventProto.WHEN, event.when);
2186 proto.end(token);
2187 }
2188 }
2189 }
2190
2191 proto.flush();
2192 }
2193
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002194 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002195 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
2196 PrintWriter pw = new PrintWriter(bs);
2197 final long nowRTC = System.currentTimeMillis();
2198 final long nowELAPSED = SystemClock.elapsedRealtime();
2199 final int NZ = mAlarmBatches.size();
2200 for (int iz = 0; iz < NZ; iz++) {
2201 Batch bz = mAlarmBatches.get(iz);
2202 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002203 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002204 pw.flush();
2205 Slog.v(TAG, bs.toString());
2206 bs.reset();
2207 }
2208 }
2209
2210 private boolean validateConsistencyLocked() {
2211 if (DEBUG_VALIDATE) {
2212 long lastTime = Long.MIN_VALUE;
2213 final int N = mAlarmBatches.size();
2214 for (int i = 0; i < N; i++) {
2215 Batch b = mAlarmBatches.get(i);
2216 if (b.start >= lastTime) {
2217 // duplicate start times are okay because of standalone batches
2218 lastTime = b.start;
2219 } else {
2220 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002221 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2222 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002223 return false;
2224 }
2225 }
2226 }
2227 return true;
2228 }
2229
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002230 private Batch findFirstWakeupBatchLocked() {
2231 final int N = mAlarmBatches.size();
2232 for (int i = 0; i < N; i++) {
2233 Batch b = mAlarmBatches.get(i);
2234 if (b.hasWakeups()) {
2235 return b;
2236 }
2237 }
2238 return null;
2239 }
2240
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002241 long getNextWakeFromIdleTimeImpl() {
2242 synchronized (mLock) {
2243 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
2244 }
2245 }
2246
2247 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002248 synchronized (mLock) {
2249 return mNextAlarmClockForUser.get(userId);
2250 }
2251 }
2252
2253 /**
2254 * Recomputes the next alarm clock for all users.
2255 */
2256 private void updateNextAlarmClockLocked() {
2257 if (!mNextAlarmClockMayChange) {
2258 return;
2259 }
2260 mNextAlarmClockMayChange = false;
2261
Jose Lima235510e2014-08-13 12:50:01 -07002262 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002263 nextForUser.clear();
2264
2265 final int N = mAlarmBatches.size();
2266 for (int i = 0; i < N; i++) {
2267 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
2268 final int M = alarms.size();
2269
2270 for (int j = 0; j < M; j++) {
2271 Alarm a = alarms.get(j);
2272 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002273 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07002274 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002275
2276 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07002277 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002278 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02002279 " for user " + userId);
2280 }
2281
2282 // Alarms and batches are sorted by time, no need to compare times here.
2283 if (nextForUser.get(userId) == null) {
2284 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07002285 } else if (a.alarmClock.equals(current)
2286 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
2287 // same/earlier time and it's the one we cited before, so stick with it
2288 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002289 }
2290 }
2291 }
2292 }
2293
2294 // Update mNextAlarmForUser with new values.
2295 final int NN = nextForUser.size();
2296 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07002297 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002298 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002299 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002300 if (!newAlarm.equals(currentAlarm)) {
2301 updateNextAlarmInfoForUserLocked(userId, newAlarm);
2302 }
2303 }
2304
2305 // Remove users without any alarm clocks scheduled.
2306 final int NNN = mNextAlarmClockForUser.size();
2307 for (int i = NNN - 1; i >= 0; i--) {
2308 int userId = mNextAlarmClockForUser.keyAt(i);
2309 if (nextForUser.get(userId) == null) {
2310 updateNextAlarmInfoForUserLocked(userId, null);
2311 }
2312 }
2313 }
2314
Jose Lima235510e2014-08-13 12:50:01 -07002315 private void updateNextAlarmInfoForUserLocked(int userId,
2316 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002317 if (alarmClock != null) {
2318 if (DEBUG_ALARM_CLOCK) {
2319 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002320 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02002321 }
2322 mNextAlarmClockForUser.put(userId, alarmClock);
2323 } else {
2324 if (DEBUG_ALARM_CLOCK) {
2325 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
2326 }
2327 mNextAlarmClockForUser.remove(userId);
2328 }
2329
2330 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
2331 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2332 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2333 }
2334
2335 /**
2336 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
2337 * for which alarm clocks have changed since the last call to this.
2338 *
2339 * Do not call with a lock held. Only call from mHandler's thread.
2340 *
2341 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
2342 */
2343 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07002344 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002345 pendingUsers.clear();
2346
2347 synchronized (mLock) {
2348 final int N = mPendingSendNextAlarmClockChangedForUser.size();
2349 for (int i = 0; i < N; i++) {
2350 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
2351 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
2352 }
2353 mPendingSendNextAlarmClockChangedForUser.clear();
2354 }
2355
2356 final int N = pendingUsers.size();
2357 for (int i = 0; i < N; i++) {
2358 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002359 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002360 Settings.System.putStringForUser(getContext().getContentResolver(),
2361 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01002362 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02002363 userId);
2364
2365 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
2366 new UserHandle(userId));
2367 }
2368 }
2369
2370 /**
2371 * Formats an alarm like platform/packages/apps/DeskClock used to.
2372 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01002373 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
2374 int userId) {
2375 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02002376 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
2377 return (info == null) ? "" :
2378 DateFormat.format(pattern, info.getTriggerTime()).toString();
2379 }
2380
Adam Lesinski182f73f2013-12-05 16:48:06 -08002381 void rescheduleKernelAlarmsLocked() {
2382 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
2383 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002384 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002385 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002386 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002387 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07002388 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002389 mNextWakeup = firstWakeup.start;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002390 mLastWakeupSet = SystemClock.elapsedRealtime();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002391 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002392 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002393 if (firstBatch != firstWakeup) {
2394 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002395 }
2396 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002397 if (mPendingNonWakeupAlarms.size() > 0) {
2398 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
2399 nextNonWakeup = mNextNonWakeupDeliveryTime;
2400 }
2401 }
Prashant Malani753e9e02015-06-10 17:43:49 -07002402 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002403 mNextNonWakeup = nextNonWakeup;
2404 setLocked(ELAPSED_REALTIME, nextNonWakeup);
2405 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002406 }
2407
Christopher Tate14a7bb02015-10-01 10:24:31 -07002408 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Christopher Tate1d99c392017-12-07 16:54:04 -08002409 if (operation == null && directReceiver == null) {
2410 if (localLOGV) {
2411 Slog.w(TAG, "requested remove() of null operation",
2412 new RuntimeException("here"));
2413 }
2414 return;
2415 }
2416
Adam Lesinski182f73f2013-12-05 16:48:06 -08002417 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002418 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002419 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2420 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002421 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002422 if (b.size() == 0) {
2423 mAlarmBatches.remove(i);
2424 }
2425 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002426 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002427 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002428 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2429 mPendingWhileIdleAlarms.remove(i);
2430 }
2431 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002432 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2433 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2434 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2435 if (alarmsForUid.get(j).matches(operation, directReceiver)) {
2436 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2437 alarmsForUid.remove(j);
2438 }
2439 }
2440 if (alarmsForUid.size() == 0) {
2441 mPendingBackgroundAlarms.removeAt(i);
2442 }
2443 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002444 if (didRemove) {
2445 if (DEBUG_BATCH) {
2446 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
2447 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002448 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002449 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002450 mPendingIdleUntil = null;
2451 restorePending = true;
2452 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002453 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002454 mNextWakeFromIdle = null;
2455 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002456 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002457 if (restorePending) {
2458 restorePendingWhileIdleAlarmsLocked();
2459 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002460 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002461 }
2462 }
2463
Christopher Tate1d99c392017-12-07 16:54:04 -08002464 void removeLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002465 if (uid == Process.SYSTEM_UID) {
2466 Slog.wtf(TAG, "removeLocked: Shouldn't for UID=" + uid);
2467 return;
2468 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002469 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002470 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.uid == uid;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002471 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2472 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002473 didRemove |= b.remove(whichAlarms);
2474 if (b.size() == 0) {
2475 mAlarmBatches.remove(i);
2476 }
2477 }
2478 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2479 final Alarm a = mPendingWhileIdleAlarms.get(i);
2480 if (a.uid == uid) {
2481 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2482 mPendingWhileIdleAlarms.remove(i);
2483 }
2484 }
2485 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2486 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2487 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2488 if (alarmsForUid.get(j).uid == uid) {
2489 alarmsForUid.remove(j);
2490 }
2491 }
2492 if (alarmsForUid.size() == 0) {
2493 mPendingBackgroundAlarms.removeAt(i);
2494 }
2495 }
2496 if (didRemove) {
2497 if (DEBUG_BATCH) {
2498 Slog.v(TAG, "remove(uid) changed bounds; rebatching");
2499 }
2500 rebatchAllAlarmsLocked(true);
2501 rescheduleKernelAlarmsLocked();
2502 updateNextAlarmClockLocked();
2503 }
2504 }
2505
2506 void removeLocked(final String packageName) {
2507 if (packageName == null) {
2508 if (localLOGV) {
2509 Slog.w(TAG, "requested remove() of null packageName",
2510 new RuntimeException("here"));
2511 }
2512 return;
2513 }
2514
2515 boolean didRemove = false;
2516 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(packageName);
Makoto Onuki5d93b832018-01-10 16:12:39 -08002517 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
Christopher Tate1d99c392017-12-07 16:54:04 -08002518 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2519 Batch b = mAlarmBatches.get(i);
2520 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002521 if (b.size() == 0) {
2522 mAlarmBatches.remove(i);
2523 }
2524 }
Makoto Onuki5d93b832018-01-10 16:12:39 -08002525 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
2526 if (oldHasTick != newHasTick) {
2527 Slog.wtf(TAG, "removeLocked: hasTick changed from " + oldHasTick + " to " + newHasTick);
2528 }
2529
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002530 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002531 final Alarm a = mPendingWhileIdleAlarms.get(i);
2532 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002533 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2534 mPendingWhileIdleAlarms.remove(i);
2535 }
2536 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002537 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2538 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2539 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2540 if (alarmsForUid.get(j).matches(packageName)) {
2541 alarmsForUid.remove(j);
2542 }
2543 }
2544 if (alarmsForUid.size() == 0) {
2545 mPendingBackgroundAlarms.removeAt(i);
2546 }
2547 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002548 if (didRemove) {
2549 if (DEBUG_BATCH) {
2550 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2551 }
2552 rebatchAllAlarmsLocked(true);
2553 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002554 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002555 }
2556 }
2557
Christopher Tate1d99c392017-12-07 16:54:04 -08002558 void removeForStoppedLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002559 if (uid == Process.SYSTEM_UID) {
2560 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for UID=" + uid);
2561 return;
2562 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002563 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002564 final Predicate<Alarm> whichAlarms = (Alarm a) -> {
2565 try {
2566 if (a.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
2567 uid, a.packageName)) {
2568 return true;
2569 }
2570 } catch (RemoteException e) { /* fall through */}
2571 return false;
2572 };
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002573 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2574 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002575 didRemove |= b.remove(whichAlarms);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002576 if (b.size() == 0) {
2577 mAlarmBatches.remove(i);
2578 }
2579 }
2580 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2581 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08002582 if (a.uid == uid) {
2583 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2584 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002585 }
2586 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002587 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2588 if (mPendingBackgroundAlarms.keyAt(i) == uid) {
2589 mPendingBackgroundAlarms.removeAt(i);
2590 }
2591 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002592 if (didRemove) {
2593 if (DEBUG_BATCH) {
2594 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2595 }
2596 rebatchAllAlarmsLocked(true);
2597 rescheduleKernelAlarmsLocked();
2598 updateNextAlarmClockLocked();
2599 }
2600 }
2601
Adam Lesinski182f73f2013-12-05 16:48:06 -08002602 void removeUserLocked(int userHandle) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002603 if (userHandle == UserHandle.USER_SYSTEM) {
2604 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for user=" + userHandle);
2605 return;
2606 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002607 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002608 final Predicate<Alarm> whichAlarms =
2609 (Alarm a) -> UserHandle.getUserId(a.creatorUid) == userHandle;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002610 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2611 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002612 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002613 if (b.size() == 0) {
2614 mAlarmBatches.remove(i);
2615 }
2616 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002617 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002618 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002619 == userHandle) {
2620 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2621 mPendingWhileIdleAlarms.remove(i);
2622 }
2623 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002624 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2625 if (UserHandle.getUserId(mPendingBackgroundAlarms.keyAt(i)) == userHandle) {
2626 mPendingBackgroundAlarms.removeAt(i);
2627 }
2628 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002629 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
2630 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
2631 mLastAllowWhileIdleDispatch.removeAt(i);
2632 }
2633 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002634
2635 if (didRemove) {
2636 if (DEBUG_BATCH) {
2637 Slog.v(TAG, "remove(user) changed bounds; rebatching");
2638 }
2639 rebatchAllAlarmsLocked(true);
2640 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002641 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002642 }
2643 }
2644
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002645 void interactiveStateChangedLocked(boolean interactive) {
2646 if (mInteractive != interactive) {
2647 mInteractive = interactive;
2648 final long nowELAPSED = SystemClock.elapsedRealtime();
2649 if (interactive) {
2650 if (mPendingNonWakeupAlarms.size() > 0) {
2651 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2652 mTotalDelayTime += thisDelayTime;
2653 if (mMaxDelayTime < thisDelayTime) {
2654 mMaxDelayTime = thisDelayTime;
2655 }
2656 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2657 mPendingNonWakeupAlarms.clear();
2658 }
2659 if (mNonInteractiveStartTime > 0) {
2660 long dur = nowELAPSED - mNonInteractiveStartTime;
2661 if (dur > mNonInteractiveTime) {
2662 mNonInteractiveTime = dur;
2663 }
2664 }
2665 } else {
2666 mNonInteractiveStartTime = nowELAPSED;
2667 }
2668 }
2669 }
2670
Adam Lesinski182f73f2013-12-05 16:48:06 -08002671 boolean lookForPackageLocked(String packageName) {
2672 for (int i = 0; i < mAlarmBatches.size(); i++) {
2673 Batch b = mAlarmBatches.get(i);
2674 if (b.hasPackage(packageName)) {
2675 return true;
2676 }
2677 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002678 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002679 final Alarm a = mPendingWhileIdleAlarms.get(i);
2680 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002681 return true;
2682 }
2683 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002684 return false;
2685 }
2686
2687 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002688 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002689 // The kernel never triggers alarms with negative wakeup times
2690 // so we ensure they are positive.
2691 long alarmSeconds, alarmNanoseconds;
2692 if (when < 0) {
2693 alarmSeconds = 0;
2694 alarmNanoseconds = 0;
2695 } else {
2696 alarmSeconds = when / 1000;
2697 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2698 }
Kweku Adams61e03292017-10-19 14:27:12 -07002699
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002700 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002701 } else {
2702 Message msg = Message.obtain();
2703 msg.what = ALARM_EVENT;
Kweku Adams61e03292017-10-19 14:27:12 -07002704
Adam Lesinski182f73f2013-12-05 16:48:06 -08002705 mHandler.removeMessages(ALARM_EVENT);
2706 mHandler.sendMessageAtTime(msg, when);
2707 }
2708 }
2709
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002710 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Kweku Adams61e03292017-10-19 14:27:12 -07002711 String prefix, String label, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002712 for (int i=list.size()-1; i>=0; i--) {
2713 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002714 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2715 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002716 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002717 }
2718 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002719
2720 private static final String labelForType(int type) {
2721 switch (type) {
2722 case RTC: return "RTC";
2723 case RTC_WAKEUP : return "RTC_WAKEUP";
2724 case ELAPSED_REALTIME : return "ELAPSED";
2725 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
Christopher Tatee0a22b32013-07-11 14:43:13 -07002726 }
2727 return "--unknown--";
2728 }
2729
2730 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002731 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002732 for (int i=list.size()-1; i>=0; i--) {
2733 Alarm a = list.get(i);
2734 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002735 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2736 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002737 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002738 }
2739 }
2740
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002741 private boolean isBackgroundRestricted(Alarm alarm) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002742 if (alarm.alarmClock != null) {
2743 // Don't block alarm clocks
2744 return false;
2745 }
2746 if (alarm.operation != null
2747 && (alarm.operation.isActivity() || alarm.operation.isForegroundService())) {
2748 // Don't block starting foreground components
2749 return false;
2750 }
2751 final String sourcePackage =
2752 (alarm.operation != null) ? alarm.operation.getCreatorPackage() : alarm.packageName;
2753 final int sourceUid = alarm.creatorUid;
Makoto Onuki2206af32017-11-21 16:25:35 -08002754 return mForceAppStandbyTracker.areAlarmsRestricted(sourceUid, sourcePackage);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002755 }
2756
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002757 private native long init();
2758 private native void close(long nativeData);
2759 private native void set(long nativeData, int type, long seconds, long nanoseconds);
2760 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08002761 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002762 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002763
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002764 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002765 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002766 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002767 // batches are temporally sorted, so we need only pull from the
2768 // start of the list until we either empty it or hit a batch
2769 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07002770 while (mAlarmBatches.size() > 0) {
2771 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002772 if (batch.start > nowELAPSED) {
2773 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002774 break;
2775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002776
Christopher Tatee0a22b32013-07-11 14:43:13 -07002777 // We will (re)schedule some alarms now; don't let that interfere
2778 // with delivery of this current batch
2779 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002780
Christopher Tatee0a22b32013-07-11 14:43:13 -07002781 final int N = batch.size();
2782 for (int i = 0; i < N; i++) {
2783 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002784
2785 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
2786 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
2787 // schedule such alarms.
2788 long lastTime = mLastAllowWhileIdleDispatch.get(alarm.uid, 0);
2789 long minTime = lastTime + mAllowWhileIdleMinTime;
2790 if (nowELAPSED < minTime) {
2791 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
2792 // alarm went off for this app. Reschedule the alarm to be in the
2793 // correct time period.
2794 alarm.whenElapsed = minTime;
2795 if (alarm.maxWhenElapsed < minTime) {
2796 alarm.maxWhenElapsed = minTime;
2797 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002798 if (RECORD_DEVICE_IDLE_ALARMS) {
2799 IdleDispatchEntry ent = new IdleDispatchEntry();
2800 ent.uid = alarm.uid;
2801 ent.pkg = alarm.operation.getCreatorPackage();
2802 ent.tag = alarm.operation.getTag("");
2803 ent.op = "RESCHEDULE";
2804 ent.elapsedRealtime = nowELAPSED;
2805 ent.argRealtime = lastTime;
2806 mAllowWhileIdleDispatches.add(ent);
2807 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002808 setImplLocked(alarm, true, false);
2809 continue;
2810 }
2811 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002812 if (isBackgroundRestricted(alarm)) {
2813 // Alarms with FLAG_WAKE_FROM_IDLE or mPendingIdleUntil alarm are not deferred
2814 if (DEBUG_BG_LIMIT) {
2815 Slog.d(TAG, "Deferring alarm " + alarm + " due to user forced app standby");
2816 }
2817 ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(alarm.creatorUid);
2818 if (alarmsForUid == null) {
2819 alarmsForUid = new ArrayList<>();
2820 mPendingBackgroundAlarms.put(alarm.creatorUid, alarmsForUid);
2821 }
2822 alarmsForUid.add(alarm);
2823 continue;
2824 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002825
Christopher Tatee0a22b32013-07-11 14:43:13 -07002826 alarm.count = 1;
2827 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002828 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
2829 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002830 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002831 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002832 if (mPendingIdleUntil == alarm) {
2833 mPendingIdleUntil = null;
2834 rebatchAllAlarmsLocked(false);
2835 restorePendingWhileIdleAlarmsLocked();
2836 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002837 if (mNextWakeFromIdle == alarm) {
2838 mNextWakeFromIdle = null;
2839 rebatchAllAlarmsLocked(false);
2840 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002841
2842 // Recurring alarms may have passed several alarm intervals while the
2843 // phone was asleep or off, so pass a trigger count when sending them.
2844 if (alarm.repeatInterval > 0) {
2845 // this adjustment will be zero if we're late by
2846 // less than one full repeat interval
2847 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
2848
2849 // Also schedule its next recurrence
2850 final long delta = alarm.count * alarm.repeatInterval;
2851 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07002852 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07002853 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07002854 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
2855 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08002856 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002857
Christopher Tate864d42e2014-12-02 11:48:53 -08002858 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002859 hasWakeup = true;
2860 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002861
2862 // We removed an alarm clock. Let the caller recompute the next alarm clock.
2863 if (alarm.alarmClock != null) {
2864 mNextAlarmClockMayChange = true;
2865 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07002866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002867 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002868
Christopher Tate1590f1e2014-10-02 17:27:57 -07002869 // This is a new alarm delivery set; bump the sequence number to indicate that
2870 // all apps' alarm delivery classes should be recalculated.
2871 mCurrentSeq++;
2872 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002873 Collections.sort(triggerList, mAlarmDispatchComparator);
2874
2875 if (localLOGV) {
2876 for (int i=0; i<triggerList.size(); i++) {
2877 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
2878 }
2879 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002880
2881 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002882 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002884 /**
2885 * This Comparator sorts Alarms into increasing time order.
2886 */
2887 public static class IncreasingTimeOrder implements Comparator<Alarm> {
2888 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09002889 long when1 = a1.whenElapsed;
2890 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002891 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002892 return 1;
2893 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002894 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002895 return -1;
2896 }
2897 return 0;
2898 }
2899 }
Kweku Adams61e03292017-10-19 14:27:12 -07002900
Makoto Onuki2206af32017-11-21 16:25:35 -08002901 @VisibleForTesting
2902 static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002903 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002904 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002905 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002906 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002907 public final IAlarmListener listener;
2908 public final String listenerTag;
2909 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002910 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002911 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002912 public final AlarmManager.AlarmClockInfo alarmClock;
2913 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002914 public final int creatorUid;
2915 public final String packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002916 public int count;
2917 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07002918 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002919 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002920 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002921 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07002922 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002923
Christopher Tate3e04b472013-10-21 17:51:31 -07002924 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002925 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
2926 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
2927 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002928 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002929 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002930 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
2931 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002932 when = _when;
2933 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07002934 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002935 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002936 repeatInterval = _interval;
2937 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002938 listener = _rec;
2939 listenerTag = _listenerTag;
2940 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07002941 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002942 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002943 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002944 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002945 packageName = _pkgName;
2946
2947 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002948 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002949
Christopher Tate14a7bb02015-10-01 10:24:31 -07002950 public static String makeTag(PendingIntent pi, String tag, int type) {
2951 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
2952 ? "*walarm*:" : "*alarm*:";
2953 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
2954 }
2955
2956 public WakeupEvent makeWakeupEvent(long nowRTC) {
2957 return new WakeupEvent(nowRTC, creatorUid,
2958 (operation != null)
2959 ? operation.getIntent().getAction()
2960 : ("<listener>:" + listenerTag));
2961 }
2962
2963 // Returns true if either matches
2964 public boolean matches(PendingIntent pi, IAlarmListener rec) {
2965 return (operation != null)
2966 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09002967 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07002968 }
2969
2970 public boolean matches(String packageName) {
2971 return (operation != null)
2972 ? packageName.equals(operation.getTargetPackage())
2973 : packageName.equals(this.packageName);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002974 }
2975
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002976 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002977 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002978 StringBuilder sb = new StringBuilder(128);
2979 sb.append("Alarm{");
2980 sb.append(Integer.toHexString(System.identityHashCode(this)));
2981 sb.append(" type ");
2982 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002983 sb.append(" when ");
2984 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002985 sb.append(" ");
Christopher Tate14a7bb02015-10-01 10:24:31 -07002986 if (operation != null) {
2987 sb.append(operation.getTargetPackage());
2988 } else {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002989 sb.append(packageName);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002990 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002991 sb.append('}');
2992 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002993 }
2994
Kweku Adams61e03292017-10-19 14:27:12 -07002995 public void dump(PrintWriter pw, String prefix, long nowELAPSED, long nowRTC,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002996 SimpleDateFormat sdf) {
2997 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002998 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002999 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003000 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
3001 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003002 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003003 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003004 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003005 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003006 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003007 }
3008 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003009 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003010 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003011 pw.print(" count="); pw.print(count);
3012 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003013 if (alarmClock != null) {
3014 pw.print(prefix); pw.println("Alarm clock:");
3015 pw.print(prefix); pw.print(" triggerTime=");
3016 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
3017 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
3018 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003019 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003020 if (listener != null) {
3021 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
3022 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003023 }
Kweku Adams61e03292017-10-19 14:27:12 -07003024
3025 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
3026 long nowRTC) {
3027 final long token = proto.start(fieldId);
3028
3029 proto.write(AlarmProto.TAG, statsTag);
3030 proto.write(AlarmProto.TYPE, type);
Kweku Adams923ec432017-12-11 18:05:38 -08003031 proto.write(AlarmProto.TIME_UNTIL_WHEN_ELAPSED_MS, whenElapsed - nowElapsed);
Kweku Adams61e03292017-10-19 14:27:12 -07003032 proto.write(AlarmProto.WINDOW_LENGTH_MS, windowLength);
3033 proto.write(AlarmProto.REPEAT_INTERVAL_MS, repeatInterval);
3034 proto.write(AlarmProto.COUNT, count);
3035 proto.write(AlarmProto.FLAGS, flags);
3036 if (alarmClock != null) {
3037 alarmClock.writeToProto(proto, AlarmProto.ALARM_CLOCK);
3038 }
3039 if (operation != null) {
3040 operation.writeToProto(proto, AlarmProto.OPERATION);
3041 }
3042 if (listener != null) {
3043 proto.write(AlarmProto.LISTENER, listener.asBinder().toString());
3044 }
3045
3046 proto.end(token);
3047 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003048 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003049
Christopher Tatee0a22b32013-07-11 14:43:13 -07003050 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
3051 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003052 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
3053 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003054 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07003055 break;
3056 }
3057
Christopher Tatee0a22b32013-07-11 14:43:13 -07003058 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003059 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
3060 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003061 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07003062 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003063 }
3064 }
3065
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003066 long currentNonWakeupFuzzLocked(long nowELAPSED) {
3067 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
3068 if (timeSinceOn < 5*60*1000) {
3069 // If the screen has been off for 5 minutes, only delay by at most two minutes.
3070 return 2*60*1000;
3071 } else if (timeSinceOn < 30*60*1000) {
3072 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
3073 return 15*60*1000;
3074 } else {
3075 // Otherwise, we will delay by at most an hour.
3076 return 60*60*1000;
3077 }
3078 }
3079
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003080 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003081 if (duration < 15*60*1000) {
3082 // If the duration until the time is less than 15 minutes, the maximum fuzz
3083 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003084 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003085 } else if (duration < 90*60*1000) {
3086 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
3087 return 15*60*1000;
3088 } else {
3089 // Otherwise, we will fuzz by at most half an hour.
3090 return 30*60*1000;
3091 }
3092 }
3093
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003094 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
3095 if (mInteractive) {
3096 return false;
3097 }
3098 if (mLastAlarmDeliveryTime <= 0) {
3099 return false;
3100 }
minho.choo649acab2014-12-12 16:13:55 +09003101 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003102 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
3103 // and the next delivery time is in the past, then just deliver them all. This
3104 // avoids bugs where we get stuck in a loop trying to poll for alarms.
3105 return false;
3106 }
3107 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
3108 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
3109 }
3110
3111 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
3112 mLastAlarmDeliveryTime = nowELAPSED;
3113 for (int i=0; i<triggerList.size(); i++) {
3114 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07003115 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Tim Murray175c0f92017-11-28 15:01:04 -08003116 if (alarm.wakeup) {
3117 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch wakeup alarm to " + alarm.packageName);
3118 } else {
3119 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch non-wakeup alarm to " + alarm.packageName);
3120 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003121 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07003122 if (localLOGV) {
3123 Slog.v(TAG, "sending alarm " + alarm);
3124 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07003125 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003126 ActivityManager.noteAlarmStart(alarm.operation, alarm.workSource, alarm.uid,
3127 alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003128 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003129 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003130 } catch (RuntimeException e) {
3131 Slog.w(TAG, "Failure sending alarm.", e);
3132 }
Tim Murray175c0f92017-11-28 15:01:04 -08003133 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003134 }
3135 }
3136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003137 private class AlarmThread extends Thread
3138 {
3139 public AlarmThread()
3140 {
3141 super("AlarmManager");
3142 }
Kweku Adams61e03292017-10-19 14:27:12 -07003143
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003144 public void run()
3145 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003146 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3147
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003148 while (true)
3149 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003150 int result = waitForAlarm(mNativeData);
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003151 mLastWakeup = SystemClock.elapsedRealtime();
Dianne Hackborn390517b2013-05-30 15:03:32 -07003152
3153 triggerList.clear();
3154
Dianne Hackbornc3527222015-05-13 14:03:20 -07003155 final long nowRTC = System.currentTimeMillis();
3156 final long nowELAPSED = SystemClock.elapsedRealtime();
3157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003158 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003159 // The kernel can give us spurious time change notifications due to
3160 // small adjustments it makes internally; we want to filter those out.
3161 final long lastTimeChangeClockTime;
3162 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07003163 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003164 lastTimeChangeClockTime = mLastTimeChangeClockTime;
3165 expectedClockTime = lastTimeChangeClockTime
3166 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07003167 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003168 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
3169 || nowRTC > (expectedClockTime+1000)) {
3170 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07003171 // let's do it!
3172 if (DEBUG_BATCH) {
3173 Slog.v(TAG, "Time changed notification from kernel; rebatching");
3174 }
3175 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07003176 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003177 rebatchAllAlarms();
3178 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07003179 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003180 synchronized (mLock) {
3181 mNumTimeChanged++;
3182 mLastTimeChangeClockTime = nowRTC;
3183 mLastTimeChangeRealtime = nowELAPSED;
3184 }
3185 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
3186 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003187 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07003188 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
3189 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003190 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
3191
3192 // The world has changed on us, so we need to re-evaluate alarms
3193 // regardless of whether the kernel has told us one went off.
3194 result |= IS_WAKEUP_MASK;
3195 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003197
Dianne Hackbornc3527222015-05-13 14:03:20 -07003198 if (result != TIME_CHANGED_MASK) {
3199 // If this was anything besides just a time change, then figure what if
3200 // anything to do about alarms.
3201 synchronized (mLock) {
3202 if (localLOGV) Slog.v(
3203 TAG, "Checking for alarms... rtc=" + nowRTC
3204 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07003205
Dianne Hackbornc3527222015-05-13 14:03:20 -07003206 if (WAKEUP_STATS) {
3207 if ((result & IS_WAKEUP_MASK) != 0) {
3208 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
3209 int n = 0;
3210 for (WakeupEvent event : mRecentWakeups) {
3211 if (event.when > newEarliest) break;
3212 n++; // number of now-stale entries at the list head
3213 }
3214 for (int i = 0; i < n; i++) {
3215 mRecentWakeups.remove();
3216 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003217
Dianne Hackbornc3527222015-05-13 14:03:20 -07003218 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003219 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003220 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003221
3222 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3223 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
3224 // if there are no wakeup alarms and the screen is off, we can
3225 // delay what we have so far until the future.
3226 if (mPendingNonWakeupAlarms.size() == 0) {
3227 mStartCurrentDelayTime = nowELAPSED;
3228 mNextNonWakeupDeliveryTime = nowELAPSED
3229 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
3230 }
3231 mPendingNonWakeupAlarms.addAll(triggerList);
3232 mNumDelayedAlarms += triggerList.size();
3233 rescheduleKernelAlarmsLocked();
3234 updateNextAlarmClockLocked();
3235 } else {
3236 // now deliver the alarm intents; if there are pending non-wakeup
3237 // alarms, we need to merge them in to the list. note we don't
3238 // just deliver them first because we generally want non-wakeup
3239 // alarms delivered after wakeup alarms.
3240 rescheduleKernelAlarmsLocked();
3241 updateNextAlarmClockLocked();
3242 if (mPendingNonWakeupAlarms.size() > 0) {
3243 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
3244 triggerList.addAll(mPendingNonWakeupAlarms);
3245 Collections.sort(triggerList, mAlarmDispatchComparator);
3246 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3247 mTotalDelayTime += thisDelayTime;
3248 if (mMaxDelayTime < thisDelayTime) {
3249 mMaxDelayTime = thisDelayTime;
3250 }
3251 mPendingNonWakeupAlarms.clear();
3252 }
3253 deliverAlarmsLocked(triggerList, nowELAPSED);
3254 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003255 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003256
3257 } else {
3258 // Just in case -- even though no wakeup flag was set, make sure
3259 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07003260 synchronized (mLock) {
3261 rescheduleKernelAlarmsLocked();
3262 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003263 }
3264 }
3265 }
3266 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003267
David Christieebe51fc2013-07-26 13:23:29 -07003268 /**
3269 * Attribute blame for a WakeLock.
3270 * @param pi PendingIntent to attribute blame to if ws is null.
3271 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003272 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07003273 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003274 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003275 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07003276 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003277 final boolean unimportant = pi == mTimeTickSender;
3278 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003279 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003280 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003281 } else {
3282 mWakeLock.setHistoryTag(null);
3283 }
3284 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07003285 if (ws != null) {
3286 mWakeLock.setWorkSource(ws);
3287 return;
3288 }
3289
Christopher Tate14a7bb02015-10-01 10:24:31 -07003290 final int uid = (knownUid >= 0)
3291 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003292 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07003293 if (uid >= 0) {
3294 mWakeLock.setWorkSource(new WorkSource(uid));
3295 return;
3296 }
3297 } catch (Exception e) {
3298 }
3299
3300 // Something went wrong; fall back to attributing the lock to the OS
3301 mWakeLock.setWorkSource(null);
3302 }
3303
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003304 private class AlarmHandler extends Handler {
3305 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003306 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
3307 public static final int LISTENER_TIMEOUT = 3;
3308 public static final int REPORT_ALARMS_ACTIVE = 4;
Kweku Adams61e03292017-10-19 14:27:12 -07003309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003310 public AlarmHandler() {
3311 }
Kweku Adams61e03292017-10-19 14:27:12 -07003312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003313 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003314 switch (msg.what) {
3315 case ALARM_EVENT: {
3316 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3317 synchronized (mLock) {
3318 final long nowRTC = System.currentTimeMillis();
3319 final long nowELAPSED = SystemClock.elapsedRealtime();
3320 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3321 updateNextAlarmClockLocked();
3322 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003323
Christopher Tate14a7bb02015-10-01 10:24:31 -07003324 // now trigger the alarms without the lock held
3325 for (int i=0; i<triggerList.size(); i++) {
3326 Alarm alarm = triggerList.get(i);
3327 try {
3328 alarm.operation.send();
3329 } catch (PendingIntent.CanceledException e) {
3330 if (alarm.repeatInterval > 0) {
3331 // This IntentSender is no longer valid, but this
3332 // is a repeating alarm, so toss the hoser.
3333 removeImpl(alarm.operation);
3334 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003335 }
3336 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003337 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003338 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003339
3340 case SEND_NEXT_ALARM_CLOCK_CHANGED:
3341 sendNextAlarmClockChanged();
3342 break;
3343
3344 case LISTENER_TIMEOUT:
3345 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
3346 break;
3347
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003348 case REPORT_ALARMS_ACTIVE:
3349 if (mLocalDeviceIdleController != null) {
3350 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
3351 }
3352 break;
3353
Christopher Tate14a7bb02015-10-01 10:24:31 -07003354 default:
3355 // nope, just ignore it
3356 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003357 }
3358 }
3359 }
Kweku Adams61e03292017-10-19 14:27:12 -07003360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003361 class ClockReceiver extends BroadcastReceiver {
3362 public ClockReceiver() {
3363 IntentFilter filter = new IntentFilter();
3364 filter.addAction(Intent.ACTION_TIME_TICK);
3365 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003366 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003367 }
Kweku Adams61e03292017-10-19 14:27:12 -07003368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003369 @Override
3370 public void onReceive(Context context, Intent intent) {
3371 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07003372 if (DEBUG_BATCH) {
3373 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
3374 }
Christopher Tate12cf0b62018-01-05 18:40:14 -08003375 synchronized (mLock) {
3376 mLastTickReceived = System.currentTimeMillis();
3377 }
Christopher Tate385e4982013-07-23 18:22:29 -07003378 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003379 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
3380 // Since the kernel does not keep track of DST, we need to
3381 // reset the TZ information at the beginning of each day
3382 // based off of the current Zone gmt offset + userspace tracked
3383 // daylight savings information.
3384 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02003385 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003386 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07003387 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003388 }
3389 }
Kweku Adams61e03292017-10-19 14:27:12 -07003390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003391 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07003392 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09003393 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07003394
3395 // Schedule this event for the amount of time that it would take to get to
3396 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09003397 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07003398
David Christieebe51fc2013-07-26 13:23:29 -07003399 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08003400 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003401 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
3402 null, Process.myUid(), "android");
Christopher Tate12cf0b62018-01-05 18:40:14 -08003403
3404 // Finally, remember when we set the tick alarm
3405 synchronized (mLock) {
3406 mLastTickSet = currentTime;
3407 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003408 }
Christopher Tate385e4982013-07-23 18:22:29 -07003409
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003410 public void scheduleDateChangedEvent() {
3411 Calendar calendar = Calendar.getInstance();
3412 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07003413 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003414 calendar.set(Calendar.MINUTE, 0);
3415 calendar.set(Calendar.SECOND, 0);
3416 calendar.set(Calendar.MILLISECOND, 0);
3417 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07003418
3419 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003420 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
3421 AlarmManager.FLAG_STANDALONE, workSource, null,
3422 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003423 }
3424 }
Kweku Adams61e03292017-10-19 14:27:12 -07003425
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003426 class InteractiveStateReceiver extends BroadcastReceiver {
3427 public InteractiveStateReceiver() {
3428 IntentFilter filter = new IntentFilter();
3429 filter.addAction(Intent.ACTION_SCREEN_OFF);
3430 filter.addAction(Intent.ACTION_SCREEN_ON);
3431 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
3432 getContext().registerReceiver(this, filter);
3433 }
3434
3435 @Override
3436 public void onReceive(Context context, Intent intent) {
3437 synchronized (mLock) {
3438 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
3439 }
3440 }
3441 }
3442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003443 class UninstallReceiver extends BroadcastReceiver {
3444 public UninstallReceiver() {
3445 IntentFilter filter = new IntentFilter();
3446 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
3447 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003448 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003449 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08003450 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003451 // Register for events related to sdcard installation.
3452 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08003453 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003454 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003455 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003456 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003457 }
Kweku Adams61e03292017-10-19 14:27:12 -07003458
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003459 @Override
3460 public void onReceive(Context context, Intent intent) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003461 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003462 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003463 String action = intent.getAction();
3464 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003465 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
3466 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
3467 for (String packageName : pkgList) {
3468 if (lookForPackageLocked(packageName)) {
3469 setResultCode(Activity.RESULT_OK);
3470 return;
3471 }
3472 }
3473 return;
3474 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003475 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003476 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
3477 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
3478 if (userHandle >= 0) {
3479 removeUserLocked(userHandle);
3480 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003481 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003482 if (uid >= 0) {
3483 mLastAllowWhileIdleDispatch.delete(uid);
3484 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003485 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08003486 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
3487 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
3488 // This package is being updated; don't kill its alarms.
3489 return;
3490 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003491 Uri data = intent.getData();
3492 if (data != null) {
3493 String pkg = data.getSchemeSpecificPart();
3494 if (pkg != null) {
3495 pkgList = new String[]{pkg};
3496 }
3497 }
3498 }
3499 if (pkgList != null && (pkgList.length > 0)) {
3500 for (String pkg : pkgList) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003501 if (uid >= 0) {
3502 // package-removed case
3503 removeLocked(uid);
3504 } else {
3505 // external-applications-unavailable etc case
3506 removeLocked(pkg);
3507 }
Christopher Tate1590f1e2014-10-02 17:27:57 -07003508 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003509 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
3510 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
3511 if (uidStats.remove(pkg) != null) {
3512 if (uidStats.size() <= 0) {
3513 mBroadcastStats.removeAt(i);
3514 }
3515 }
3516 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003517 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003518 }
3519 }
3520 }
3521 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003522
3523 final class UidObserver extends IUidObserver.Stub {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003524 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003525 }
3526
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003527 @Override public void onUidGone(int uid, boolean disabled) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003528 synchronized (mLock) {
3529 if (disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -08003530 removeForStoppedLocked(uid);
3531 }
3532 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003533 }
3534
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003535 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003536 }
3537
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003538 @Override public void onUidIdle(int uid, boolean disabled) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003539 synchronized (mLock) {
3540 if (disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -08003541 removeForStoppedLocked(uid);
3542 }
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08003543 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003544 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003545
3546 @Override public void onUidCachedChanged(int uid, boolean cached) {
3547 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003548 };
3549
Makoto Onuki2206af32017-11-21 16:25:35 -08003550
3551 private final Listener mForceAppStandbyListener = new Listener() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003552 @Override
Makoto Onuki2206af32017-11-21 16:25:35 -08003553 public void unblockAllUnrestrictedAlarms() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003554 synchronized (mLock) {
Makoto Onuki2206af32017-11-21 16:25:35 -08003555 sendAllUnrestrictedPendingBackgroundAlarmsLocked();
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003556 }
3557 }
Makoto Onuki2206af32017-11-21 16:25:35 -08003558
3559 @Override
3560 public void unblockAlarmsForUid(int uid) {
3561 synchronized (mLock) {
3562 sendPendingBackgroundAlarmsLocked(uid, null);
3563 }
3564 }
3565
3566 @Override
3567 public void unblockAlarmsForUidPackage(int uid, String packageName) {
3568 synchronized (mLock) {
3569 sendPendingBackgroundAlarmsLocked(uid, packageName);
3570 }
3571 }
3572 };
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003574 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003575 String pkg = pi.getCreatorPackage();
3576 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003577 return getStatsLocked(uid, pkg);
3578 }
3579
3580 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003581 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
3582 if (uidStats == null) {
3583 uidStats = new ArrayMap<String, BroadcastStats>();
3584 mBroadcastStats.put(uid, uidStats);
3585 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003586 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003587 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003588 bs = new BroadcastStats(uid, pkgName);
3589 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003590 }
3591 return bs;
3592 }
Dianne Hackborn81038902012-11-26 17:04:09 -08003593
Christopher Tate21e9f192017-08-08 13:49:11 -07003594 /**
3595 * Canonical count of (operation.send() - onSendFinished()) and
3596 * listener send/complete/timeout invocations.
3597 * Guarded by the usual lock.
3598 */
3599 @GuardedBy("mLock")
3600 private int mSendCount = 0;
3601 @GuardedBy("mLock")
Christopher Tateeabba732017-08-17 17:12:52 -07003602 private int mSendFinishCount = 0;
3603 @GuardedBy("mLock")
Christopher Tate21e9f192017-08-08 13:49:11 -07003604 private int mListenerCount = 0;
Christopher Tateeabba732017-08-17 17:12:52 -07003605 @GuardedBy("mLock")
3606 private int mListenerFinishCount = 0;
Christopher Tate21e9f192017-08-08 13:49:11 -07003607
Christopher Tate14a7bb02015-10-01 10:24:31 -07003608 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
Christopher Tate21e9f192017-08-08 13:49:11 -07003609
Christopher Tate14a7bb02015-10-01 10:24:31 -07003610 private InFlight removeLocked(PendingIntent pi, Intent intent) {
3611 for (int i = 0; i < mInFlight.size(); i++) {
Christopher Tatedb9ae422017-08-21 11:24:30 -07003612 if (mInFlight.get(i).mPendingIntent == pi) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003613 return mInFlight.remove(i);
3614 }
3615 }
3616 mLog.w("No in-flight alarm for " + pi + " " + intent);
3617 return null;
3618 }
3619
3620 private InFlight removeLocked(IBinder listener) {
3621 for (int i = 0; i < mInFlight.size(); i++) {
3622 if (mInFlight.get(i).mListener == listener) {
3623 return mInFlight.remove(i);
3624 }
3625 }
3626 mLog.w("No in-flight alarm for listener " + listener);
3627 return null;
3628 }
3629
3630 private void updateStatsLocked(InFlight inflight) {
3631 final long nowELAPSED = SystemClock.elapsedRealtime();
3632 BroadcastStats bs = inflight.mBroadcastStats;
3633 bs.nesting--;
3634 if (bs.nesting <= 0) {
3635 bs.nesting = 0;
3636 bs.aggregateTime += nowELAPSED - bs.startTime;
3637 }
3638 FilterStats fs = inflight.mFilterStats;
3639 fs.nesting--;
3640 if (fs.nesting <= 0) {
3641 fs.nesting = 0;
3642 fs.aggregateTime += nowELAPSED - fs.startTime;
3643 }
3644 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003645 ActivityManager.noteAlarmFinish(inflight.mPendingIntent, inflight.mWorkSource,
3646 inflight.mUid, inflight.mTag);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003647 }
3648 }
3649
3650 private void updateTrackingLocked(InFlight inflight) {
3651 if (inflight != null) {
3652 updateStatsLocked(inflight);
3653 }
3654 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08003655 if (DEBUG_WAKELOCK) {
3656 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
3657 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003658 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003659 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003660 mWakeLock.release();
3661 if (mInFlight.size() > 0) {
3662 mLog.w("Finished all dispatches with " + mInFlight.size()
3663 + " remaining inflights");
3664 for (int i=0; i<mInFlight.size(); i++) {
3665 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
3666 }
3667 mInFlight.clear();
3668 }
3669 } else {
3670 // the next of our alarms is now in flight. reattribute the wakelock.
3671 if (mInFlight.size() > 0) {
3672 InFlight inFlight = mInFlight.get(0);
3673 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
3674 inFlight.mAlarmType, inFlight.mTag, -1, false);
3675 } else {
3676 // should never happen
3677 mLog.w("Alarm wakelock still held but sent queue empty");
3678 mWakeLock.setWorkSource(null);
3679 }
3680 }
3681 }
3682
3683 /**
3684 * Callback that arrives when a direct-call alarm reports that delivery has finished
3685 */
3686 @Override
3687 public void alarmComplete(IBinder who) {
3688 if (who == null) {
Christopher Tate21e9f192017-08-08 13:49:11 -07003689 mLog.w("Invalid alarmComplete: uid=" + Binder.getCallingUid()
Christopher Tate14a7bb02015-10-01 10:24:31 -07003690 + " pid=" + Binder.getCallingPid());
3691 return;
3692 }
3693
3694 final long ident = Binder.clearCallingIdentity();
3695 try {
3696 synchronized (mLock) {
3697 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
3698 InFlight inflight = removeLocked(who);
3699 if (inflight != null) {
3700 if (DEBUG_LISTENER_CALLBACK) {
3701 Slog.i(TAG, "alarmComplete() from " + who);
3702 }
3703 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07003704 mListenerFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003705 } else {
3706 // Delivery timed out, and the timeout handling already took care of
3707 // updating our tracking here, so we needn't do anything further.
3708 if (DEBUG_LISTENER_CALLBACK) {
3709 Slog.i(TAG, "Late alarmComplete() from " + who);
3710 }
3711 }
3712 }
3713 } finally {
3714 Binder.restoreCallingIdentity(ident);
3715 }
3716 }
3717
3718 /**
3719 * Callback that arrives when a PendingIntent alarm has finished delivery
3720 */
3721 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003722 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
3723 String resultData, Bundle resultExtras) {
3724 synchronized (mLock) {
Christopher Tateeabba732017-08-17 17:12:52 -07003725 mSendFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003726 updateTrackingLocked(removeLocked(pi, intent));
3727 }
3728 }
3729
3730 /**
3731 * Timeout of a direct-call alarm delivery
3732 */
3733 public void alarmTimedOut(IBinder who) {
3734 synchronized (mLock) {
3735 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08003736 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003737 // TODO: implement ANR policy for the target
3738 if (DEBUG_LISTENER_CALLBACK) {
3739 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003740 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003741 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07003742 mListenerFinishCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08003743 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003744 if (DEBUG_LISTENER_CALLBACK) {
3745 Slog.i(TAG, "Spurious timeout of listener " + who);
3746 }
Christopher Tate21e9f192017-08-08 13:49:11 -07003747 mLog.w("Spurious timeout of listener " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003748 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003749 }
3750 }
3751
3752 /**
3753 * Deliver an alarm and set up the post-delivery handling appropriately
3754 */
3755 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
3756 if (alarm.operation != null) {
3757 // PendingIntent alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07003758 mSendCount++;
Christopher Tate12cf0b62018-01-05 18:40:14 -08003759
3760 if (alarm.priorityClass.priority == PRIO_TICK) {
3761 mLastTickIssued = nowELAPSED;
3762 }
3763
Christopher Tate14a7bb02015-10-01 10:24:31 -07003764 try {
3765 alarm.operation.send(getContext(), 0,
3766 mBackgroundIntent.putExtra(
3767 Intent.EXTRA_ALARM_COUNT, alarm.count),
3768 mDeliveryTracker, mHandler, null,
3769 allowWhileIdle ? mIdleOptions : null);
3770 } catch (PendingIntent.CanceledException e) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08003771 if (alarm.operation == mTimeTickSender) {
3772 Slog.wtf(TAG, "mTimeTickSender canceled");
3773 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003774 if (alarm.repeatInterval > 0) {
3775 // This IntentSender is no longer valid, but this
3776 // is a repeating alarm, so toss it
3777 removeImpl(alarm.operation);
3778 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003779 // No actual delivery was possible, so the delivery tracker's
3780 // 'finished' callback won't be invoked. We also don't need
3781 // to do any wakelock or stats tracking, so we have nothing
3782 // left to do here but go on to the next thing.
Christopher Tateeabba732017-08-17 17:12:52 -07003783 mSendFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08003784 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003785 }
3786 } else {
3787 // Direct listener callback alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07003788 mListenerCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003789 try {
3790 if (DEBUG_LISTENER_CALLBACK) {
3791 Slog.v(TAG, "Alarm to uid=" + alarm.uid
3792 + " listener=" + alarm.listener.asBinder());
3793 }
3794 alarm.listener.doAlarm(this);
3795 mHandler.sendMessageDelayed(
3796 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
3797 alarm.listener.asBinder()),
3798 mConstants.LISTENER_TIMEOUT);
3799 } catch (Exception e) {
3800 if (DEBUG_LISTENER_CALLBACK) {
3801 Slog.i(TAG, "Alarm undeliverable to listener "
3802 + alarm.listener.asBinder(), e);
3803 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003804 // As in the PendingIntent.CanceledException case, delivery of the
3805 // alarm was not possible, so we have no wakelock or timeout or
3806 // stats management to do. It threw before we posted the delayed
3807 // timeout message, so we're done here.
Christopher Tateeabba732017-08-17 17:12:52 -07003808 mListenerFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08003809 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003810 }
3811 }
3812
3813 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08003814 if (DEBUG_WAKELOCK) {
3815 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
3816 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003817 if (mBroadcastRefCount == 0) {
3818 setWakelockWorkSource(alarm.operation, alarm.workSource,
3819 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
3820 true);
3821 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003822 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003823 }
3824 final InFlight inflight = new InFlight(AlarmManagerService.this,
3825 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
3826 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
3827 mInFlight.add(inflight);
3828 mBroadcastRefCount++;
3829
3830 if (allowWhileIdle) {
3831 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
3832 mLastAllowWhileIdleDispatch.put(alarm.uid, nowELAPSED);
3833 if (RECORD_DEVICE_IDLE_ALARMS) {
3834 IdleDispatchEntry ent = new IdleDispatchEntry();
3835 ent.uid = alarm.uid;
3836 ent.pkg = alarm.packageName;
3837 ent.tag = alarm.statsTag;
3838 ent.op = "DELIVER";
3839 ent.elapsedRealtime = nowELAPSED;
3840 mAllowWhileIdleDispatches.add(ent);
3841 }
3842 }
3843
3844 final BroadcastStats bs = inflight.mBroadcastStats;
3845 bs.count++;
3846 if (bs.nesting == 0) {
3847 bs.nesting = 1;
3848 bs.startTime = nowELAPSED;
3849 } else {
3850 bs.nesting++;
3851 }
3852 final FilterStats fs = inflight.mFilterStats;
3853 fs.count++;
3854 if (fs.nesting == 0) {
3855 fs.nesting = 1;
3856 fs.startTime = nowELAPSED;
3857 } else {
3858 fs.nesting++;
3859 }
3860 if (alarm.type == ELAPSED_REALTIME_WAKEUP
3861 || alarm.type == RTC_WAKEUP) {
3862 bs.numWakeup++;
3863 fs.numWakeup++;
Narayan Kamath695cf722017-12-21 18:32:47 +00003864 ActivityManager.noteWakeupAlarm(
3865 alarm.operation, alarm.workSource, alarm.uid, alarm.packageName,
3866 alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003867 }
3868 }
3869 }
3870}