blob: 94f6109fe20a5b39e4994de339759c8de960a908 [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;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060092import com.android.internal.util.DumpUtils;
Dianne Hackborn81038902012-11-26 17:04:09 -080093import com.android.internal.util.LocalLog;
Makoto Onuki2206af32017-11-21 16:25:35 -080094import com.android.server.ForceAppStandbyTracker.Listener;
Dianne Hackborn81038902012-11-26 17:04:09 -080095
Makoto Onuki2206af32017-11-21 16:25:35 -080096/**
97 * Alarm manager implementaion.
98 *
99 * Unit test:
100 atest $ANDROID_BUILD_TOP/frameworks/base/services/tests/servicestests/src/com/android/server/AlarmManagerServiceTest.java
101 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800102class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700103 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
104 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800105 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700106 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800107 static final int TIME_CHANGED_MASK = 1 << 16;
108 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -0800109
Christopher Tatee0a22b32013-07-11 14:43:13 -0700110 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -0800111 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -0800112
Adam Lesinski182f73f2013-12-05 16:48:06 -0800113 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -0800114 static final boolean localLOGV = false;
115 static final boolean DEBUG_BATCH = localLOGV || false;
116 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200117 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700118 static final boolean DEBUG_LISTENER_CALLBACK = localLOGV || false;
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800119 static final boolean DEBUG_WAKELOCK = localLOGV || false;
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700120 static final boolean DEBUG_BG_LIMIT = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700121 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700122 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800123 static final int ALARM_EVENT = 1;
124 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200125
Christopher Tate14a7bb02015-10-01 10:24:31 -0700126 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800128 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700129
Adam Lesinski182f73f2013-12-05 16:48:06 -0800130 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700131
Christopher Tate24cd46f2016-02-02 14:28:01 -0800132 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT =
133 new Intent(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED)
Christopher Tate50191db2017-05-09 16:02:25 -0700134 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
135 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Adrian Roosc42a1e12014-07-07 23:35:53 +0200136
Adam Lesinski182f73f2013-12-05 16:48:06 -0800137 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800138
Christopher Tate14a7bb02015-10-01 10:24:31 -0700139 AppOpsManager mAppOps;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800140 DeviceIdleController.LocalService mLocalDeviceIdleController;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700141
Adam Lesinski182f73f2013-12-05 16:48:06 -0800142 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800143
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700144 // List of alarms per uid deferred due to user applied background restrictions on the source app
145 SparseArray<ArrayList<Alarm>> mPendingBackgroundAlarms = new SparseArray<>();
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800146 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800147 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700148 private long mNextNonWakeup;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -0700149 private long mLastWakeupSet;
150 private long mLastWakeup;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800151 int mBroadcastRefCount = 0;
152 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700153 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700154 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
155 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800156 final AlarmHandler mHandler = new AlarmHandler();
157 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700158 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700160 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800161 PendingIntent mTimeTickSender;
162 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700163 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700164 boolean mInteractive = true;
165 long mNonInteractiveStartTime;
166 long mNonInteractiveTime;
167 long mLastAlarmDeliveryTime;
168 long mStartCurrentDelayTime;
169 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700170 long mLastTimeChangeClockTime;
171 long mLastTimeChangeRealtime;
Dianne Hackborna750a632015-06-16 17:18:23 -0700172 long mAllowWhileIdleMinTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700173 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800174
Christopher Tatebb9cce52017-04-18 14:19:43 -0700175 // Bookkeeping about the identity of the "System UI" package, determined at runtime.
176
177 /**
178 * This permission must be defined by the canonical System UI package,
179 * with protection level "signature".
180 */
181 private static final String SYSTEM_UI_SELF_PERMISSION =
182 "android.permission.systemui.IDENTITY";
183
184 /**
185 * At boot we use SYSTEM_UI_SELF_PERMISSION to look up the definer's uid.
186 */
187 int mSystemUiUid;
188
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700189 /**
190 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
Kweku Adams61e03292017-10-19 14:27:12 -0700191 * used to determine the earliest we can dispatch the next such alarm. Times are in the
192 * 'elapsed' timebase.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700193 */
194 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
195
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700196 final static class IdleDispatchEntry {
197 int uid;
198 String pkg;
199 String tag;
200 String op;
201 long elapsedRealtime;
202 long argRealtime;
203 }
204 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
205
Dianne Hackborna750a632015-06-16 17:18:23 -0700206 /**
207 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
208 */
209 Bundle mIdleOptions;
210
Jose Lima235510e2014-08-13 12:50:01 -0700211 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
212 new SparseArray<>();
213 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
214 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200215 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
216 new SparseBooleanArray();
217 private boolean mNextAlarmClockMayChange;
218
219 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700220 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
221 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200222
Makoto Onuki2206af32017-11-21 16:25:35 -0800223 private final ForceAppStandbyTracker mForceAppStandbyTracker;
224
Dianne Hackborna750a632015-06-16 17:18:23 -0700225 /**
226 * All times are in milliseconds. These constants are kept synchronized with the system
227 * global Settings. Any access to this class or its fields should be done while
228 * holding the AlarmManagerService.mLock lock.
229 */
230 private final class Constants extends ContentObserver {
231 // Key names stored in the settings value.
232 private static final String KEY_MIN_FUTURITY = "min_futurity";
233 private static final String KEY_MIN_INTERVAL = "min_interval";
234 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
235 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
236 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
237 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700238 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700239 private static final String KEY_BG_RESTRICTIONS_ENABLED = "limit_bg_alarms_enabled";
Dianne Hackborna750a632015-06-16 17:18:23 -0700240
241 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
242 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tateaa244da2015-08-27 15:57:57 -0700243 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700244 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700245 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
246
Christopher Tate14a7bb02015-10-01 10:24:31 -0700247 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
248
Dianne Hackborna750a632015-06-16 17:18:23 -0700249 // Minimum futurity of a new alarm
250 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
251
252 // Minimum alarm recurrence interval
253 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
254
255 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
256 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
257
258 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
259 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
260
261 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
262 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
263 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
264
Christopher Tate14a7bb02015-10-01 10:24:31 -0700265 // Direct alarm listener callback timeout
266 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
267
Dianne Hackborna750a632015-06-16 17:18:23 -0700268 private ContentResolver mResolver;
269 private final KeyValueListParser mParser = new KeyValueListParser(',');
270 private long mLastAllowWhileIdleWhitelistDuration = -1;
271
272 public Constants(Handler handler) {
273 super(handler);
274 updateAllowWhileIdleMinTimeLocked();
275 updateAllowWhileIdleWhitelistDurationLocked();
276 }
277
278 public void start(ContentResolver resolver) {
279 mResolver = resolver;
280 mResolver.registerContentObserver(Settings.Global.getUriFor(
281 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
282 updateConstants();
283 }
284
285 public void updateAllowWhileIdleMinTimeLocked() {
286 mAllowWhileIdleMinTime = mPendingIdleUntil != null
287 ? ALLOW_WHILE_IDLE_LONG_TIME : ALLOW_WHILE_IDLE_SHORT_TIME;
288 }
289
290 public void updateAllowWhileIdleWhitelistDurationLocked() {
291 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
292 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
293 BroadcastOptions opts = BroadcastOptions.makeBasic();
294 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
295 mIdleOptions = opts.toBundle();
296 }
297 }
298
299 @Override
300 public void onChange(boolean selfChange, Uri uri) {
301 updateConstants();
302 }
303
304 private void updateConstants() {
305 synchronized (mLock) {
306 try {
307 mParser.setString(Settings.Global.getString(mResolver,
308 Settings.Global.ALARM_MANAGER_CONSTANTS));
309 } catch (IllegalArgumentException e) {
310 // Failed to parse the settings string, log this and move on
311 // with defaults.
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800312 Slog.e(TAG, "Bad alarm manager settings", e);
Dianne Hackborna750a632015-06-16 17:18:23 -0700313 }
314
315 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
316 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
317 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
318 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
319 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
320 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
321 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
322 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
323 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700324 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
325 DEFAULT_LISTENER_TIMEOUT);
Dianne Hackborna750a632015-06-16 17:18:23 -0700326
327 updateAllowWhileIdleMinTimeLocked();
328 updateAllowWhileIdleWhitelistDurationLocked();
329 }
330 }
331
332 void dump(PrintWriter pw) {
333 pw.println(" Settings:");
334
335 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
336 TimeUtils.formatDuration(MIN_FUTURITY, pw);
337 pw.println();
338
339 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
340 TimeUtils.formatDuration(MIN_INTERVAL, pw);
341 pw.println();
342
Christopher Tate14a7bb02015-10-01 10:24:31 -0700343 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
344 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
345 pw.println();
346
Dianne Hackborna750a632015-06-16 17:18:23 -0700347 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
348 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
349 pw.println();
350
351 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
352 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
353 pw.println();
354
355 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
356 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
357 pw.println();
358 }
Kweku Adams61e03292017-10-19 14:27:12 -0700359
360 void dumpProto(ProtoOutputStream proto, long fieldId) {
361 final long token = proto.start(fieldId);
362
363 proto.write(ConstantsProto.MIN_FUTURITY_DURATION_MS, MIN_FUTURITY);
364 proto.write(ConstantsProto.MIN_INTERVAL_DURATION_MS, MIN_INTERVAL);
365 proto.write(ConstantsProto.LISTENER_TIMEOUT_DURATION_MS, LISTENER_TIMEOUT);
366 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_SHORT_DURATION_MS,
367 ALLOW_WHILE_IDLE_SHORT_TIME);
368 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_LONG_DURATION_MS,
369 ALLOW_WHILE_IDLE_LONG_TIME);
370 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_WHITELIST_DURATION_MS,
371 ALLOW_WHILE_IDLE_WHITELIST_DURATION);
372
373 proto.end(token);
374 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700375 }
376
377 final Constants mConstants;
378
Christopher Tate1590f1e2014-10-02 17:27:57 -0700379 // Alarm delivery ordering bookkeeping
380 static final int PRIO_TICK = 0;
381 static final int PRIO_WAKEUP = 1;
382 static final int PRIO_NORMAL = 2;
383
Dianne Hackborna750a632015-06-16 17:18:23 -0700384 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700385 int seq;
386 int priority;
387
388 PriorityClass() {
389 seq = mCurrentSeq - 1;
390 priority = PRIO_NORMAL;
391 }
392 }
393
Dianne Hackborna750a632015-06-16 17:18:23 -0700394 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700395 int mCurrentSeq = 0;
396
Dianne Hackborna750a632015-06-16 17:18:23 -0700397 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700398 public long when;
399 public int uid;
400 public String action;
401
402 public WakeupEvent(long theTime, int theUid, String theAction) {
403 when = theTime;
404 uid = theUid;
405 action = theAction;
406 }
407 }
408
Adam Lesinski182f73f2013-12-05 16:48:06 -0800409 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
410 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700411
Adrian Roosc42a1e12014-07-07 23:35:53 +0200412 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700413 long start; // These endpoints are always in ELAPSED
414 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700415 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700416
417 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
418
419 Batch() {
420 start = 0;
421 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700422 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700423 }
424
425 Batch(Alarm seed) {
426 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700427 end = seed.maxWhenElapsed;
428 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700429 alarms.add(seed);
430 }
431
432 int size() {
433 return alarms.size();
434 }
435
436 Alarm get(int index) {
437 return alarms.get(index);
438 }
439
440 boolean canHold(long whenElapsed, long maxWhen) {
441 return (end >= whenElapsed) && (start <= maxWhen);
442 }
443
444 boolean add(Alarm alarm) {
445 boolean newStart = false;
446 // narrows the batch if necessary; presumes that canHold(alarm) is true
447 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
448 if (index < 0) {
449 index = 0 - index - 1;
450 }
451 alarms.add(index, alarm);
452 if (DEBUG_BATCH) {
453 Slog.v(TAG, "Adding " + alarm + " to " + this);
454 }
455 if (alarm.whenElapsed > start) {
456 start = alarm.whenElapsed;
457 newStart = true;
458 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700459 if (alarm.maxWhenElapsed < end) {
460 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700461 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700462 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700463
464 if (DEBUG_BATCH) {
465 Slog.v(TAG, " => now " + this);
466 }
467 return newStart;
468 }
469
Christopher Tate14a7bb02015-10-01 10:24:31 -0700470 boolean remove(final PendingIntent operation, final IAlarmListener listener) {
471 if (operation == null && listener == null) {
472 if (localLOGV) {
473 Slog.w(TAG, "requested remove() of null operation",
474 new RuntimeException("here"));
475 }
476 return false;
477 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700478 boolean didRemove = false;
479 long newStart = 0; // recalculate endpoints as we go
480 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700481 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700482 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700483 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700484 if (alarm.matches(operation, listener)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700485 alarms.remove(i);
486 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200487 if (alarm.alarmClock != null) {
488 mNextAlarmClockMayChange = true;
489 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700490 } else {
491 if (alarm.whenElapsed > newStart) {
492 newStart = alarm.whenElapsed;
493 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700494 if (alarm.maxWhenElapsed < newEnd) {
495 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700496 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700497 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700498 i++;
499 }
500 }
501 if (didRemove) {
502 // commit the new batch bounds
503 start = newStart;
504 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700505 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700506 }
507 return didRemove;
508 }
509
510 boolean remove(final String packageName) {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700511 if (packageName == null) {
512 if (localLOGV) {
513 Slog.w(TAG, "requested remove() of null packageName",
514 new RuntimeException("here"));
515 }
516 return false;
517 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700518 boolean didRemove = false;
519 long newStart = 0; // recalculate endpoints as we go
520 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700521 int newFlags = 0;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700522 for (int i = alarms.size()-1; i >= 0; i--) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700523 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700524 if (alarm.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700525 alarms.remove(i);
526 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200527 if (alarm.alarmClock != null) {
528 mNextAlarmClockMayChange = true;
529 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700530 } else {
531 if (alarm.whenElapsed > newStart) {
532 newStart = alarm.whenElapsed;
533 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700534 if (alarm.maxWhenElapsed < newEnd) {
535 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700536 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700537 newFlags |= alarm.flags;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700538 }
539 }
540 if (didRemove) {
541 // commit the new batch bounds
542 start = newStart;
543 end = newEnd;
544 flags = newFlags;
545 }
546 return didRemove;
547 }
548
549 boolean removeForStopped(final int uid) {
550 boolean didRemove = false;
551 long newStart = 0; // recalculate endpoints as we go
552 long newEnd = Long.MAX_VALUE;
553 int newFlags = 0;
554 for (int i = alarms.size()-1; i >= 0; i--) {
555 Alarm alarm = alarms.get(i);
556 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800557 if (alarm.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
558 uid, alarm.packageName)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700559 alarms.remove(i);
560 didRemove = true;
561 if (alarm.alarmClock != null) {
562 mNextAlarmClockMayChange = true;
563 }
564 } else {
565 if (alarm.whenElapsed > newStart) {
566 newStart = alarm.whenElapsed;
567 }
568 if (alarm.maxWhenElapsed < newEnd) {
569 newEnd = alarm.maxWhenElapsed;
570 }
571 newFlags |= alarm.flags;
572 }
573 } catch (RemoteException e) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700574 }
575 }
576 if (didRemove) {
577 // commit the new batch bounds
578 start = newStart;
579 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700580 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700581 }
582 return didRemove;
583 }
584
585 boolean remove(final int userHandle) {
586 boolean didRemove = false;
587 long newStart = 0; // recalculate endpoints as we go
588 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700589 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700590 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700591 if (UserHandle.getUserId(alarm.creatorUid) == userHandle) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700592 alarms.remove(i);
593 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200594 if (alarm.alarmClock != null) {
595 mNextAlarmClockMayChange = true;
596 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700597 } else {
598 if (alarm.whenElapsed > newStart) {
599 newStart = alarm.whenElapsed;
600 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700601 if (alarm.maxWhenElapsed < newEnd) {
602 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700603 }
604 i++;
605 }
606 }
607 if (didRemove) {
608 // commit the new batch bounds
609 start = newStart;
610 end = newEnd;
611 }
612 return didRemove;
613 }
614
615 boolean hasPackage(final String packageName) {
616 final int N = alarms.size();
617 for (int i = 0; i < N; i++) {
618 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700619 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700620 return true;
621 }
622 }
623 return false;
624 }
625
626 boolean hasWakeups() {
627 final int N = alarms.size();
628 for (int i = 0; i < N; i++) {
629 Alarm a = alarms.get(i);
630 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
631 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
632 return true;
633 }
634 }
635 return false;
636 }
637
638 @Override
639 public String toString() {
640 StringBuilder b = new StringBuilder(40);
641 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
642 b.append(" num="); b.append(size());
643 b.append(" start="); b.append(start);
644 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700645 if (flags != 0) {
646 b.append(" flgs=0x");
647 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700648 }
649 b.append('}');
650 return b.toString();
651 }
Kweku Adams61e03292017-10-19 14:27:12 -0700652
653 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
654 long nowRTC) {
655 final long token = proto.start(fieldId);
656
657 proto.write(BatchProto.START_REALTIME, start);
658 proto.write(BatchProto.END_REALTIME, end);
659 proto.write(BatchProto.FLAGS, flags);
660 for (Alarm a : alarms) {
661 a.writeToProto(proto, BatchProto.ALARMS, nowElapsed, nowRTC);
662 }
663
664 proto.end(token);
665 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700666 }
667
668 static class BatchTimeOrder implements Comparator<Batch> {
669 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800670 long when1 = b1.start;
671 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800672 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700673 return 1;
674 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800675 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700676 return -1;
677 }
678 return 0;
679 }
680 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800681
682 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
683 @Override
684 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700685 // priority class trumps everything. TICK < WAKEUP < NORMAL
686 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
687 return -1;
688 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
689 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800690 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700691
692 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800693 if (lhs.whenElapsed < rhs.whenElapsed) {
694 return -1;
695 } else if (lhs.whenElapsed > rhs.whenElapsed) {
696 return 1;
697 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700698
699 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800700 return 0;
701 }
702 };
703
Christopher Tate1590f1e2014-10-02 17:27:57 -0700704 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
705 final int N = alarms.size();
706 for (int i = 0; i < N; i++) {
707 Alarm a = alarms.get(i);
708
709 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700710 if (a.operation != null
711 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700712 alarmPrio = PRIO_TICK;
713 } else if (a.wakeup) {
714 alarmPrio = PRIO_WAKEUP;
715 } else {
716 alarmPrio = PRIO_NORMAL;
717 }
718
719 PriorityClass packagePrio = a.priorityClass;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700720 String alarmPackage = (a.operation != null)
721 ? a.operation.getCreatorPackage()
722 : a.packageName;
723 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700724 if (packagePrio == null) {
725 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700726 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700727 }
728 a.priorityClass = packagePrio;
729
730 if (packagePrio.seq != mCurrentSeq) {
731 // first alarm we've seen in the current delivery generation from this package
732 packagePrio.priority = alarmPrio;
733 packagePrio.seq = mCurrentSeq;
734 } else {
735 // Multiple alarms from this package being delivered in this generation;
736 // bump the package's delivery class if it's warranted.
737 // TICK < WAKEUP < NORMAL
738 if (alarmPrio < packagePrio.priority) {
739 packagePrio.priority = alarmPrio;
740 }
741 }
742 }
743 }
744
Christopher Tatee0a22b32013-07-11 14:43:13 -0700745 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800746 static final long MIN_FUZZABLE_INTERVAL = 10000;
747 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700748 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
749
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700750 // 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 -0700751 // to run during this time are placed in mPendingWhileIdleAlarms
752 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700753 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700754 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700755
Jeff Brownb880d882014-02-10 19:47:07 -0800756 public AlarmManagerService(Context context) {
757 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700758 mConstants = new Constants(mHandler);
Makoto Onuki2206af32017-11-21 16:25:35 -0800759
760 mForceAppStandbyTracker = ForceAppStandbyTracker.getInstance(context);
761 mForceAppStandbyTracker.addListener(mForceAppStandbyListener);
Jeff Brownb880d882014-02-10 19:47:07 -0800762 }
763
Christopher Tatee0a22b32013-07-11 14:43:13 -0700764 static long convertToElapsed(long when, int type) {
765 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
766 if (isRtc) {
767 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
768 }
769 return when;
770 }
771
772 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
773 // calculate the end of our nominal delivery window for the alarm.
774 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
775 // Current heuristic: batchable window is 75% of either the recurrence interval
776 // [for a periodic alarm] or of the time from now to the desired delivery time,
777 // with a minimum delay/interval of 10 seconds, under which we will simply not
778 // defer the alarm.
779 long futurity = (interval == 0)
780 ? (triggerAtTime - now)
781 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700782 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700783 futurity = 0;
784 }
785 return triggerAtTime + (long)(.75 * futurity);
786 }
787
788 // returns true if the batch was added at the head
789 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
790 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
791 if (index < 0) {
792 index = 0 - index - 1;
793 }
794 list.add(index, newBatch);
795 return (index == 0);
796 }
797
Christopher Tate385e4982013-07-23 18:22:29 -0700798 // Return the index of the matching batch, or -1 if none found.
799 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700800 final int N = mAlarmBatches.size();
801 for (int i = 0; i < N; i++) {
802 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700803 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700804 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700805 }
806 }
Christopher Tate385e4982013-07-23 18:22:29 -0700807 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700808 }
809
810 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
811 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700812 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700813 rebatchAllAlarmsLocked(true);
814 }
815 }
816
817 void rebatchAllAlarmsLocked(boolean doValidate) {
818 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
819 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700820 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700821 final long nowElapsed = SystemClock.elapsedRealtime();
822 final int oldBatches = oldSet.size();
823 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
824 Batch batch = oldSet.get(batchNum);
825 final int N = batch.size();
826 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700827 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700828 }
829 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700830 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
831 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
832 + " to " + mPendingIdleUntil);
833 if (mPendingIdleUntil == null) {
834 // Somehow we lost this... we need to restore all of the pending alarms.
835 restorePendingWhileIdleAlarmsLocked();
836 }
837 }
838 rescheduleKernelAlarmsLocked();
839 updateNextAlarmClockLocked();
840 }
841
842 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
843 a.when = a.origWhen;
844 long whenElapsed = convertToElapsed(a.when, a.type);
845 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700846 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700847 // Exact
848 maxElapsed = whenElapsed;
849 } else {
850 // Not exact. Preserve any explicit window, otherwise recalculate
851 // the window based on the alarm's new futurity. Note that this
852 // reflects a policy of preferring timely to deferred delivery.
853 maxElapsed = (a.windowLength > 0)
854 ? (whenElapsed + a.windowLength)
855 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
856 }
857 a.whenElapsed = whenElapsed;
858 a.maxWhenElapsed = maxElapsed;
859 setImplLocked(a, true, doValidate);
860 }
861
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700862 /**
863 * Sends alarms that were blocked due to user applied background restrictions - either because
864 * the user lifted those or the uid came to foreground.
865 *
866 * @param uid uid to filter on
867 * @param packageName package to filter on, or null for all packages in uid
868 */
869 void sendPendingBackgroundAlarmsLocked(int uid, String packageName) {
870 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(uid);
871 if (alarmsForUid == null || alarmsForUid.size() == 0) {
872 return;
873 }
874 final ArrayList<Alarm> alarmsToDeliver;
875 if (packageName != null) {
876 if (DEBUG_BG_LIMIT) {
877 Slog.d(TAG, "Sending blocked alarms for uid " + uid + ", package " + packageName);
878 }
879 alarmsToDeliver = new ArrayList<>();
880 for (int i = alarmsForUid.size() - 1; i >= 0; i--) {
881 final Alarm a = alarmsForUid.get(i);
882 if (a.matches(packageName)) {
883 alarmsToDeliver.add(alarmsForUid.remove(i));
884 }
885 }
886 if (alarmsForUid.size() == 0) {
887 mPendingBackgroundAlarms.remove(uid);
888 }
889 } else {
890 if (DEBUG_BG_LIMIT) {
891 Slog.d(TAG, "Sending blocked alarms for uid " + uid);
892 }
893 alarmsToDeliver = alarmsForUid;
894 mPendingBackgroundAlarms.remove(uid);
895 }
896 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
897 }
898
Makoto Onuki2206af32017-11-21 16:25:35 -0800899 /**
900 * Check all alarms in {@link #mPendingBackgroundAlarms} and send the ones that are not
901 * restricted.
902 *
903 * This is only called when the global "force all apps-standby" flag changes or when the
904 * power save whitelist changes, so it's okay to be slow.
905 */
906 void sendAllUnrestrictedPendingBackgroundAlarmsLocked() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700907 final ArrayList<Alarm> alarmsToDeliver = new ArrayList<>();
Makoto Onuki2206af32017-11-21 16:25:35 -0800908
909 findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
910 mPendingBackgroundAlarms, alarmsToDeliver, this::isBackgroundRestricted);
911
912 if (alarmsToDeliver.size() > 0) {
913 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
914 }
915 }
916
917 @VisibleForTesting
918 static void findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
919 SparseArray<ArrayList<Alarm>> pendingAlarms, ArrayList<Alarm> unrestrictedAlarms,
920 Predicate<Alarm> isBackgroundRestricted) {
921
922 for (int uidIndex = pendingAlarms.size() - 1; uidIndex >= 0; uidIndex--) {
923 final int uid = pendingAlarms.keyAt(uidIndex);
924 final ArrayList<Alarm> alarmsForUid = pendingAlarms.valueAt(uidIndex);
925
926 for (int alarmIndex = alarmsForUid.size() - 1; alarmIndex >= 0; alarmIndex--) {
927 final Alarm alarm = alarmsForUid.get(alarmIndex);
928
929 if (isBackgroundRestricted.test(alarm)) {
930 continue;
931 }
932
933 unrestrictedAlarms.add(alarm);
934 alarmsForUid.remove(alarmIndex);
935 }
936
937 if (alarmsForUid.size() == 0) {
938 pendingAlarms.removeAt(uidIndex);
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700939 }
940 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700941 }
942
943 private void deliverPendingBackgroundAlarmsLocked(ArrayList<Alarm> alarms, long nowELAPSED) {
944 final int N = alarms.size();
945 boolean hasWakeup = false;
946 for (int i = 0; i < N; i++) {
947 final Alarm alarm = alarms.get(i);
948 if (alarm.wakeup) {
949 hasWakeup = true;
950 }
951 alarm.count = 1;
952 // Recurring alarms may have passed several alarm intervals while the
953 // alarm was kept pending. Send the appropriate trigger count.
954 if (alarm.repeatInterval > 0) {
955 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
956 // Also schedule its next recurrence
957 final long delta = alarm.count * alarm.repeatInterval;
958 final long nextElapsed = alarm.whenElapsed + delta;
959 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
960 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
961 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
962 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
963 // Kernel alarms will be rescheduled as needed in setImplLocked
964 }
965 }
966 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
967 // No need to wakeup for non wakeup alarms
968 if (mPendingNonWakeupAlarms.size() == 0) {
969 mStartCurrentDelayTime = nowELAPSED;
970 mNextNonWakeupDeliveryTime = nowELAPSED
971 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
972 }
973 mPendingNonWakeupAlarms.addAll(alarms);
974 mNumDelayedAlarms += alarms.size();
975 } else {
976 if (DEBUG_BG_LIMIT) {
977 Slog.d(TAG, "Waking up to deliver pending blocked alarms");
978 }
979 // Since we are waking up, also deliver any pending non wakeup alarms we have.
980 if (mPendingNonWakeupAlarms.size() > 0) {
981 alarms.addAll(mPendingNonWakeupAlarms);
982 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
983 mTotalDelayTime += thisDelayTime;
984 if (mMaxDelayTime < thisDelayTime) {
985 mMaxDelayTime = thisDelayTime;
986 }
987 mPendingNonWakeupAlarms.clear();
988 }
989 calculateDeliveryPriorities(alarms);
990 Collections.sort(alarms, mAlarmDispatchComparator);
991 deliverAlarmsLocked(alarms, nowELAPSED);
992 }
993 }
994
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700995 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700996 if (RECORD_DEVICE_IDLE_ALARMS) {
997 IdleDispatchEntry ent = new IdleDispatchEntry();
998 ent.uid = 0;
999 ent.pkg = "FINISH IDLE";
1000 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1001 mAllowWhileIdleDispatches.add(ent);
1002 }
1003
Dianne Hackborn35d54032015-04-23 10:30:43 -07001004 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001005 if (mPendingWhileIdleAlarms.size() > 0) {
1006 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
1007 mPendingWhileIdleAlarms = new ArrayList<>();
1008 final long nowElapsed = SystemClock.elapsedRealtime();
1009 for (int i=alarms.size() - 1; i >= 0; i--) {
1010 Alarm a = alarms.get(i);
1011 reAddAlarmLocked(a, nowElapsed, false);
1012 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001013 }
Dianne Hackborn35d54032015-04-23 10:30:43 -07001014
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001015 // Make sure we are using the correct ALLOW_WHILE_IDLE min time.
Dianne Hackborna750a632015-06-16 17:18:23 -07001016 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001017
Dianne Hackborn35d54032015-04-23 10:30:43 -07001018 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001019 rescheduleKernelAlarmsLocked();
1020 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -07001021
1022 // And send a TIME_TICK right now, since it is important to get the UI updated.
1023 try {
1024 mTimeTickSender.send();
1025 } catch (PendingIntent.CanceledException e) {
1026 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001027 }
1028
Christopher Tate14a7bb02015-10-01 10:24:31 -07001029 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -08001030 final PendingIntent mPendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001031 final long mWhenElapsed;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001032 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -07001033 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001034 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001035 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001036 final BroadcastStats mBroadcastStats;
1037 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001038 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001039
Christopher Tate14a7bb02015-10-01 10:24:31 -07001040 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
1041 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
1042 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001043 mPendingIntent = pendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001044 mWhenElapsed = nowELAPSED;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001045 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -07001046 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001047 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001048 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001049 mBroadcastStats = (pendingIntent != null)
1050 ? service.getStatsLocked(pendingIntent)
1051 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001052 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001053 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001054 fs = new FilterStats(mBroadcastStats, mTag);
1055 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -08001056 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001057 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -08001058 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001059 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001060 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001061
1062 @Override
1063 public String toString() {
1064 return "InFlight{"
1065 + "pendingIntent=" + mPendingIntent
Christopher Tateeabba732017-08-17 17:12:52 -07001066 + ", when=" + mWhenElapsed
Makoto Onuki33955e12017-03-01 18:11:00 -08001067 + ", workSource=" + mWorkSource
1068 + ", uid=" + mUid
1069 + ", tag=" + mTag
1070 + ", broadcastStats=" + mBroadcastStats
1071 + ", filterStats=" + mFilterStats
1072 + ", alarmType=" + mAlarmType
1073 + "}";
1074 }
Kweku Adams61e03292017-10-19 14:27:12 -07001075
1076 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1077 final long token = proto.start(fieldId);
1078
1079 proto.write(InFlightProto.UID, mUid);
1080 proto.write(InFlightProto.TAG, mTag);
1081 proto.write(InFlightProto.WHEN_ELAPSED_MS, mWhenElapsed);
1082 proto.write(InFlightProto.ALARM_TYPE, mAlarmType);
1083 if (mPendingIntent != null) {
1084 mPendingIntent.writeToProto(proto, InFlightProto.PENDING_INTENT);
1085 }
1086 if (mBroadcastStats != null) {
1087 mBroadcastStats.writeToProto(proto, InFlightProto.BROADCAST_STATS);
1088 }
1089 if (mFilterStats != null) {
1090 mFilterStats.writeToProto(proto, InFlightProto.FILTER_STATS);
1091 }
1092 if (mWorkSource != null) {
1093 mWorkSource.writeToProto(proto, InFlightProto.WORK_SOURCE);
1094 }
1095
1096 proto.end(token);
1097 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001099
Adam Lesinski182f73f2013-12-05 16:48:06 -08001100 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -08001101 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001102 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001103
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001104 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -08001106 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 int numWakeup;
1108 long startTime;
1109 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -08001110
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001111 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001112 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001113 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001114 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001115
1116 @Override
1117 public String toString() {
1118 return "FilterStats{"
1119 + "tag=" + mTag
1120 + ", lastTime=" + lastTime
1121 + ", aggregateTime=" + aggregateTime
1122 + ", count=" + count
1123 + ", numWakeup=" + numWakeup
1124 + ", startTime=" + startTime
1125 + ", nesting=" + nesting
1126 + "}";
1127 }
Kweku Adams61e03292017-10-19 14:27:12 -07001128
1129 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1130 final long token = proto.start(fieldId);
1131
1132 proto.write(FilterStatsProto.TAG, mTag);
1133 proto.write(FilterStatsProto.LAST_FLIGHT_TIME_REALTIME, lastTime);
1134 proto.write(FilterStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1135 proto.write(FilterStatsProto.COUNT, count);
1136 proto.write(FilterStatsProto.WAKEUP_COUNT, numWakeup);
1137 proto.write(FilterStatsProto.START_TIME_REALTIME, startTime);
1138 proto.write(FilterStatsProto.NESTING, nesting);
1139
1140 proto.end(token);
1141 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001142 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001143
Adam Lesinski182f73f2013-12-05 16:48:06 -08001144 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001145 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001146 final String mPackageName;
1147
1148 long aggregateTime;
1149 int count;
1150 int numWakeup;
1151 long startTime;
1152 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001153 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -08001154
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001155 BroadcastStats(int uid, String packageName) {
1156 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001157 mPackageName = packageName;
1158 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001159
1160 @Override
1161 public String toString() {
1162 return "BroadcastStats{"
1163 + "uid=" + mUid
1164 + ", packageName=" + mPackageName
1165 + ", aggregateTime=" + aggregateTime
1166 + ", count=" + count
1167 + ", numWakeup=" + numWakeup
1168 + ", startTime=" + startTime
1169 + ", nesting=" + nesting
1170 + "}";
1171 }
Kweku Adams61e03292017-10-19 14:27:12 -07001172
1173 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1174 final long token = proto.start(fieldId);
1175
1176 proto.write(BroadcastStatsProto.UID, mUid);
1177 proto.write(BroadcastStatsProto.PACKAGE_NAME, mPackageName);
1178 proto.write(BroadcastStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1179 proto.write(BroadcastStatsProto.COUNT, count);
1180 proto.write(BroadcastStatsProto.WAKEUP_COUNT, numWakeup);
1181 proto.write(BroadcastStatsProto.START_TIME_REALTIME, startTime);
1182 proto.write(BroadcastStatsProto.NESTING, nesting);
1183
1184 proto.end(token);
1185 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001187
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001188 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
1189 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001190
1191 int mNumDelayedAlarms = 0;
1192 long mTotalDelayTime = 0;
1193 long mMaxDelayTime = 0;
1194
Adam Lesinski182f73f2013-12-05 16:48:06 -08001195 @Override
1196 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001197 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001198 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001199
1200 // We have to set current TimeZone info to kernel
1201 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -08001202 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001203
Christopher Tate247571462017-04-10 11:45:05 -07001204 // Also sure that we're booting with a halfway sensible current time
1205 if (mNativeData != 0) {
1206 final long systemBuildTime = Environment.getRootDirectory().lastModified();
1207 if (System.currentTimeMillis() < systemBuildTime) {
1208 Slog.i(TAG, "Current time only " + System.currentTimeMillis()
1209 + ", advancing to build time " + systemBuildTime);
1210 setKernelTime(mNativeData, systemBuildTime);
1211 }
1212 }
1213
Christopher Tatebb9cce52017-04-18 14:19:43 -07001214 // Determine SysUI's uid
1215 final PackageManager packMan = getContext().getPackageManager();
1216 try {
1217 PermissionInfo sysUiPerm = packMan.getPermissionInfo(SYSTEM_UI_SELF_PERMISSION, 0);
1218 ApplicationInfo sysUi = packMan.getApplicationInfo(sysUiPerm.packageName, 0);
1219 if ((sysUi.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1220 mSystemUiUid = sysUi.uid;
1221 } else {
1222 Slog.e(TAG, "SysUI permission " + SYSTEM_UI_SELF_PERMISSION
1223 + " defined by non-privileged app " + sysUi.packageName
1224 + " - ignoring");
1225 }
1226 } catch (NameNotFoundException e) {
1227 }
1228
1229 if (mSystemUiUid <= 0) {
1230 Slog.wtf(TAG, "SysUI package not found!");
1231 }
1232
Adam Lesinski182f73f2013-12-05 16:48:06 -08001233 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001234 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001235
Adam Lesinski182f73f2013-12-05 16:48:06 -08001236 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001238 Intent.FLAG_RECEIVER_REGISTERED_ONLY
Chad Brubaker291df4f2017-03-14 10:23:02 -07001239 | Intent.FLAG_RECEIVER_FOREGROUND
1240 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001241 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001242 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001243 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1244 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001245 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001246 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
Kweku Adams61e03292017-10-19 14:27:12 -07001247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -08001249 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001250 mClockReceiver.scheduleTimeTickEvent();
1251 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001252 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 mUninstallReceiver = new UninstallReceiver();
Kweku Adams61e03292017-10-19 14:27:12 -07001254
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001255 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001256 AlarmThread waitThread = new AlarmThread();
1257 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001258 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001259 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001260 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001261
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001262 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001263 ActivityManager.getService().registerUidObserver(new UidObserver(),
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001264 ActivityManager.UID_OBSERVER_GONE | ActivityManager.UID_OBSERVER_IDLE
1265 | ActivityManager.UID_OBSERVER_ACTIVE,
1266 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001267 } catch (RemoteException e) {
1268 // ignored; both services live in system_server
1269 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001270 publishBinderService(Context.ALARM_SERVICE, mService);
Makoto Onuki2206af32017-11-21 16:25:35 -08001271 mForceAppStandbyTracker.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001272 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001273
1274 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001275 public void onBootPhase(int phase) {
1276 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1277 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -07001278 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001279 mLocalDeviceIdleController
1280 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackborna750a632015-06-16 17:18:23 -07001281 }
1282 }
1283
1284 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 protected void finalize() throws Throwable {
1286 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001287 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 } finally {
1289 super.finalize();
1290 }
1291 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001292
Adam Lesinski182f73f2013-12-05 16:48:06 -08001293 void setTimeZoneImpl(String tz) {
1294 if (TextUtils.isEmpty(tz)) {
1295 return;
David Christieebe51fc2013-07-26 13:23:29 -07001296 }
1297
Adam Lesinski182f73f2013-12-05 16:48:06 -08001298 TimeZone zone = TimeZone.getTimeZone(tz);
1299 // Prevent reentrant calls from stepping on each other when writing
1300 // the time zone property
1301 boolean timeZoneWasChanged = false;
1302 synchronized (this) {
1303 String current = SystemProperties.get(TIMEZONE_PROPERTY);
1304 if (current == null || !current.equals(zone.getID())) {
1305 if (localLOGV) {
1306 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
1307 }
1308 timeZoneWasChanged = true;
1309 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
1310 }
1311
1312 // Update the kernel timezone information
1313 // Kernel tracks time offsets as 'minutes west of GMT'
1314 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001315 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001316 }
1317
1318 TimeZone.setDefault(null);
1319
1320 if (timeZoneWasChanged) {
1321 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001322 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate5cdf9f82017-05-03 18:10:39 -07001323 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
Chad Brubaker291df4f2017-03-14 10:23:02 -07001324 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001325 intent.putExtra("time-zone", zone.getID());
1326 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1327 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001329
Adam Lesinski182f73f2013-12-05 16:48:06 -08001330 void removeImpl(PendingIntent operation) {
1331 if (operation == null) {
1332 return;
1333 }
1334 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001335 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001336 }
1337 }
1338
1339 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001340 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1341 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1342 int callingUid, String callingPackage) {
1343 // must be *either* PendingIntent or AlarmReceiver, but not both
1344 if ((operation == null && directReceiver == null)
1345 || (operation != null && directReceiver != null)) {
1346 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1347 // NB: previous releases failed silently here, so we are continuing to do the same
1348 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001349 return;
1350 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001351
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001352 // Sanity check the window length. This will catch people mistakenly
1353 // trying to pass an end-of-window timestamp rather than a duration.
1354 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1355 Slog.w(TAG, "Window length " + windowLength
1356 + "ms suspiciously long; limiting to 1 hour");
1357 windowLength = AlarmManager.INTERVAL_HOUR;
1358 }
1359
Christopher Tate498c6cb2014-11-17 16:09:27 -08001360 // Sanity check the recurrence interval. This will catch people who supply
1361 // seconds when the API expects milliseconds.
Dianne Hackborna750a632015-06-16 17:18:23 -07001362 final long minInterval = mConstants.MIN_INTERVAL;
1363 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001364 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001365 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001366 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001367 interval = minInterval;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001368 }
1369
Christopher Tatee0a22b32013-07-11 14:43:13 -07001370 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1371 throw new IllegalArgumentException("Invalid alarm type " + type);
1372 }
1373
Christopher Tate5f221e82013-07-30 17:13:15 -07001374 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001375 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001376 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001377 + " pid=" + what);
1378 triggerAtTime = 0;
1379 }
1380
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001381 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001382 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1383 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001384 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001385 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1386
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001387 final long maxElapsed;
1388 if (windowLength == AlarmManager.WINDOW_EXACT) {
1389 maxElapsed = triggerElapsed;
1390 } else if (windowLength < 0) {
1391 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001392 // Fix this window in place, so that as time approaches we don't collapse it.
1393 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001394 } else {
1395 maxElapsed = triggerElapsed + windowLength;
1396 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001397
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001399 if (DEBUG_BATCH) {
1400 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001401 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001402 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001403 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001405 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001406 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1407 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 }
1409 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410
Christopher Tate3e04b472013-10-21 17:51:31 -07001411 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001412 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1413 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1414 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001415 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001416 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1417 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001418 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001419 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001420 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1421 + " -- package not allowed to start");
1422 return;
1423 }
1424 } catch (RemoteException e) {
1425 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001426 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001427 setImplLocked(a, false, doValidate);
1428 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001429
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001430 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1431 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001432 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001433 // The caller has given the time they want this to happen at, however we need
1434 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001435 // bring us out of idle at an earlier time.
1436 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001437 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001438 }
1439 // Add fuzz to make the alarm go off some time before the actual desired time.
1440 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001441 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001442 if (fuzz > 0) {
1443 if (mRandom == null) {
1444 mRandom = new Random();
1445 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001446 final int delta = mRandom.nextInt(fuzz);
1447 a.whenElapsed -= delta;
1448 if (false) {
1449 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1450 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1451 Slog.d(TAG, "Applied fuzz: " + fuzz);
1452 Slog.d(TAG, "Final delta: " + delta);
1453 Slog.d(TAG, "Final when: " + a.whenElapsed);
1454 }
1455 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001456 }
1457
1458 } else if (mPendingIdleUntil != null) {
1459 // We currently have an idle until alarm scheduled; if the new alarm has
1460 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001461 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1462 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1463 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001464 == 0) {
1465 mPendingWhileIdleAlarms.add(a);
1466 return;
1467 }
1468 }
1469
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001470 if (RECORD_DEVICE_IDLE_ALARMS) {
1471 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1472 IdleDispatchEntry ent = new IdleDispatchEntry();
1473 ent.uid = a.uid;
1474 ent.pkg = a.operation.getCreatorPackage();
1475 ent.tag = a.operation.getTag("");
1476 ent.op = "SET";
1477 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1478 ent.argRealtime = a.whenElapsed;
1479 mAllowWhileIdleDispatches.add(ent);
1480 }
1481 }
1482
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001483 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
1484 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -07001485 if (whichBatch < 0) {
1486 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001487 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 } else {
Christopher Tate385e4982013-07-23 18:22:29 -07001489 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001490 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001491 // The start time of this batch advanced, so batch ordering may
1492 // have just been broken. Move it to where it now belongs.
1493 mAlarmBatches.remove(whichBatch);
1494 addBatchLocked(mAlarmBatches, batch);
1495 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 }
1497
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001498 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001499 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001500 }
1501
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001502 boolean needRebatch = false;
1503
1504 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001505 if (RECORD_DEVICE_IDLE_ALARMS) {
1506 if (mPendingIdleUntil == null) {
1507 IdleDispatchEntry ent = new IdleDispatchEntry();
1508 ent.uid = 0;
1509 ent.pkg = "START IDLE";
1510 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1511 mAllowWhileIdleDispatches.add(ent);
1512 }
1513 }
Makoto Onuki4274a6d2017-04-21 12:21:25 -07001514 if ((mPendingIdleUntil != a) && (mPendingIdleUntil != null)) {
1515 Slog.wtfStack(TAG, "setImplLocked: idle until changed from " + mPendingIdleUntil
1516 + " to " + a);
1517 }
1518
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001519 mPendingIdleUntil = a;
Dianne Hackborna750a632015-06-16 17:18:23 -07001520 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001521 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001522 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1523 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1524 mNextWakeFromIdle = a;
1525 // If this wake from idle is earlier than whatever was previously scheduled,
1526 // and we are currently idling, then we need to rebatch alarms in case the idle
1527 // until time needs to be updated.
1528 if (mPendingIdleUntil != null) {
1529 needRebatch = true;
1530 }
1531 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001532 }
1533
1534 if (!rebatching) {
1535 if (DEBUG_VALIDATE) {
1536 if (doValidate && !validateConsistencyLocked()) {
1537 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1538 + " when(hex)=" + Long.toHexString(a.when)
1539 + " whenElapsed=" + a.whenElapsed
1540 + " maxWhenElapsed=" + a.maxWhenElapsed
1541 + " interval=" + a.repeatInterval + " op=" + a.operation
1542 + " flags=0x" + Integer.toHexString(a.flags));
1543 rebatchAllAlarmsLocked(false);
1544 needRebatch = false;
1545 }
1546 }
1547
1548 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001549 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001550 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001551
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001552 rescheduleKernelAlarmsLocked();
1553 updateNextAlarmClockLocked();
1554 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001555 }
1556
Adam Lesinski182f73f2013-12-05 16:48:06 -08001557 private final IBinder mService = new IAlarmManager.Stub() {
1558 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001559 public void set(String callingPackage,
1560 int type, long triggerAtTime, long windowLength, long interval, int flags,
1561 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1562 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001563 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001564
1565 // make sure the caller is not lying about which package should be blamed for
1566 // wakelock time spent in alarm delivery
1567 mAppOps.checkPackage(callingUid, callingPackage);
1568
1569 // Repeating alarms must use PendingIntent, not direct listener
1570 if (interval != 0) {
1571 if (directReceiver != null) {
1572 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1573 }
1574 }
1575
Adam Lesinski182f73f2013-12-05 16:48:06 -08001576 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001577 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001578 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001579 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001580 }
1581
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001582 // No incoming callers can request either WAKE_FROM_IDLE or
1583 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1584 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1585 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1586
1587 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1588 // manager when to come out of idle mode, which is only for DeviceIdleController.
1589 if (callingUid != Process.SYSTEM_UID) {
1590 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1591 }
1592
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001593 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001594 if (windowLength == AlarmManager.WINDOW_EXACT) {
1595 flags |= AlarmManager.FLAG_STANDALONE;
1596 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001597
1598 // If this alarm is for an alarm clock, then it must be standalone and we will
1599 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001600 if (alarmClock != null) {
1601 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001602
1603 // If the caller is a core system component or on the user's whitelist, and not calling
1604 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1605 // This means we will allow these alarms to go off as normal even while idle, with no
1606 // timing restrictions.
1607 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
Christopher Tatebb9cce52017-04-18 14:19:43 -07001608 || callingUid == mSystemUiUid
Makoto Onuki2206af32017-11-21 16:25:35 -08001609 || mForceAppStandbyTracker.isUidPowerSaveWhitelisted(callingUid))) {
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001610 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1611 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001612 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001613
Christopher Tate14a7bb02015-10-01 10:24:31 -07001614 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1615 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001616 }
Christopher Tate89779822012-08-31 14:40:03 -07001617
Adam Lesinski182f73f2013-12-05 16:48:06 -08001618 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001619 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001620 getContext().enforceCallingOrSelfPermission(
1621 "android.permission.SET_TIME",
1622 "setTime");
1623
Greg Hackmann0cab8962014-02-21 16:35:52 -08001624 if (mNativeData == 0) {
1625 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1626 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001627 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001628
1629 synchronized (mLock) {
1630 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001633
1634 @Override
1635 public void setTimeZone(String tz) {
1636 getContext().enforceCallingOrSelfPermission(
1637 "android.permission.SET_TIME_ZONE",
1638 "setTimeZone");
1639
1640 final long oldId = Binder.clearCallingIdentity();
1641 try {
1642 setTimeZoneImpl(tz);
1643 } finally {
1644 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 }
1646 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001647
Adam Lesinski182f73f2013-12-05 16:48:06 -08001648 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001649 public void remove(PendingIntent operation, IAlarmListener listener) {
1650 if (operation == null && listener == null) {
1651 Slog.w(TAG, "remove() with no intent or listener");
1652 return;
1653 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001654
Christopher Tate14a7bb02015-10-01 10:24:31 -07001655 synchronized (mLock) {
1656 removeLocked(operation, listener);
1657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001659
Adam Lesinski182f73f2013-12-05 16:48:06 -08001660 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001661 public long getNextWakeFromIdleTime() {
1662 return getNextWakeFromIdleTimeImpl();
1663 }
1664
1665 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001666 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001667 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1668 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1669 "getNextAlarmClock", null);
1670
1671 return getNextAlarmClockImpl(userId);
1672 }
1673
1674 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001675 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06001676 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Kweku Adams61e03292017-10-19 14:27:12 -07001677
1678 if (args.length > 0 && "--proto".equals(args[0])) {
1679 dumpProto(fd);
1680 } else {
1681 dumpImpl(pw);
1682 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001683 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001684 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001685
Adam Lesinski182f73f2013-12-05 16:48:06 -08001686 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 synchronized (mLock) {
1688 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001689 mConstants.dump(pw);
1690 pw.println();
1691
Makoto Onuki2206af32017-11-21 16:25:35 -08001692 mForceAppStandbyTracker.dump(pw, " ");
1693
Christopher Tatee0a22b32013-07-11 14:43:13 -07001694 final long nowRTC = System.currentTimeMillis();
1695 final long nowELAPSED = SystemClock.elapsedRealtime();
1696 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1697
Dianne Hackborna750a632015-06-16 17:18:23 -07001698 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001699 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001700 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001701 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001702 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001703 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001704 pw.print(" mLastTimeChangeRealtime=");
Dianne Hackbornc3527222015-05-13 14:03:20 -07001705 TimeUtils.formatDuration(mLastTimeChangeRealtime, pw);
1706 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001707 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001708 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001709 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1710 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001711 pw.print(" Max wakeup delay: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001712 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1713 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001714 pw.print(" Time since last dispatch: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001715 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1716 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001717 pw.print(" Next non-wakeup delivery time: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001718 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1719 pw.println();
1720 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001721
1722 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1723 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001724 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001725 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001726 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001727 pw.print(" Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001728 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001729 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
1730 pw.print(" set at "); TimeUtils.formatDuration(mLastWakeupSet, nowELAPSED, pw);
1731 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001732 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001733
John Spurlock604a5ee2015-06-01 12:27:22 -04001734 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001735 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001736 final TreeSet<Integer> users = new TreeSet<>();
1737 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1738 users.add(mNextAlarmClockForUser.keyAt(i));
1739 }
1740 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1741 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1742 }
1743 for (int user : users) {
1744 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1745 final long time = next != null ? next.getTriggerTime() : 0;
1746 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001747 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001748 pw.print(" pendingSend:"); pw.print(pendingSend);
1749 pw.print(" time:"); pw.print(time);
1750 if (time > 0) {
1751 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1752 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1753 }
1754 pw.println();
1755 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001756 if (mAlarmBatches.size() > 0) {
1757 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001758 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001759 pw.println(mAlarmBatches.size());
1760 for (Batch b : mAlarmBatches) {
1761 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001762 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001763 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001765 pw.println();
1766 pw.println(" Pending user blocked background alarms: ");
1767 boolean blocked = false;
1768 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
1769 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
1770 if (blockedAlarms != null && blockedAlarms.size() > 0) {
1771 blocked = true;
1772 dumpAlarmList(pw, blockedAlarms, " ", nowELAPSED, nowRTC, sdf);
1773 }
1774 }
1775 if (!blocked) {
1776 pw.println(" none");
1777 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001778 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001779 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001780 pw.println(" Idle mode state:");
1781 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001782 if (mPendingIdleUntil != null) {
1783 pw.println(mPendingIdleUntil);
Kweku Adams61e03292017-10-19 14:27:12 -07001784 mPendingIdleUntil.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001785 } else {
1786 pw.println("null");
1787 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001788 pw.println(" Pending alarms:");
1789 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001790 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001791 if (mNextWakeFromIdle != null) {
1792 pw.println();
1793 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
Kweku Adams61e03292017-10-19 14:27:12 -07001794 mNextWakeFromIdle.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001795 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001796
1797 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001798 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001799 if (mPendingNonWakeupAlarms.size() > 0) {
1800 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001801 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001802 } else {
1803 pw.println("(none)");
1804 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001805 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001806 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1807 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001808 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001809 pw.print(", max non-interactive time: ");
1810 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1811 pw.println();
1812
1813 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001814 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Christopher Tateeabba732017-08-17 17:12:52 -07001815 pw.print(" PendingIntent send count: "); pw.println(mSendCount);
1816 pw.print(" PendingIntent finish count: "); pw.println(mSendFinishCount);
1817 pw.print(" Listener send count: "); pw.println(mListenerCount);
1818 pw.print(" Listener finish count: "); pw.println(mListenerFinishCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001819 pw.println();
1820
Christopher Tate7f2a0352015-12-08 10:24:33 -08001821 if (mInFlight.size() > 0) {
1822 pw.println("Outstanding deliveries:");
1823 for (int i = 0; i < mInFlight.size(); i++) {
1824 pw.print(" #"); pw.print(i); pw.print(": ");
1825 pw.println(mInFlight.get(i));
1826 }
1827 pw.println();
1828 }
1829
Dianne Hackborna750a632015-06-16 17:18:23 -07001830 pw.print(" mAllowWhileIdleMinTime=");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001831 TimeUtils.formatDuration(mAllowWhileIdleMinTime, pw);
1832 pw.println();
1833 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001834 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001835 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
1836 pw.print(" UID ");
1837 UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
1838 pw.print(": ");
1839 TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i),
1840 nowELAPSED, pw);
1841 pw.println();
1842 }
1843 }
1844 pw.println();
1845
Dianne Hackborn81038902012-11-26 17:04:09 -08001846 if (mLog.dump(pw, " Recent problems", " ")) {
1847 pw.println();
1848 }
1849
1850 final FilterStats[] topFilters = new FilterStats[10];
1851 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1852 @Override
1853 public int compare(FilterStats lhs, FilterStats rhs) {
1854 if (lhs.aggregateTime < rhs.aggregateTime) {
1855 return 1;
1856 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1857 return -1;
1858 }
1859 return 0;
1860 }
1861 };
1862 int len = 0;
Kweku Adams61e03292017-10-19 14:27:12 -07001863 // Get the top 10 FilterStats, ordered by aggregateTime.
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001864 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1865 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1866 for (int ip=0; ip<uidStats.size(); ip++) {
1867 BroadcastStats bs = uidStats.valueAt(ip);
1868 for (int is=0; is<bs.filterStats.size(); is++) {
1869 FilterStats fs = bs.filterStats.valueAt(is);
1870 int pos = len > 0
1871 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1872 if (pos < 0) {
1873 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001874 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001875 if (pos < topFilters.length) {
1876 int copylen = topFilters.length - pos - 1;
1877 if (copylen > 0) {
1878 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1879 }
1880 topFilters[pos] = fs;
1881 if (len < topFilters.length) {
1882 len++;
1883 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001884 }
1885 }
1886 }
1887 }
1888 if (len > 0) {
1889 pw.println(" Top Alarms:");
1890 for (int i=0; i<len; i++) {
1891 FilterStats fs = topFilters[i];
1892 pw.print(" ");
1893 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1894 TimeUtils.formatDuration(fs.aggregateTime, pw);
1895 pw.print(" running, "); pw.print(fs.numWakeup);
1896 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001897 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1898 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001899 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001900 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001901 pw.println();
1902 }
1903 }
1904
1905 pw.println(" ");
1906 pw.println(" Alarm Stats:");
1907 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001908 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1909 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1910 for (int ip=0; ip<uidStats.size(); ip++) {
1911 BroadcastStats bs = uidStats.valueAt(ip);
1912 pw.print(" ");
1913 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1914 UserHandle.formatUid(pw, bs.mUid);
1915 pw.print(":");
1916 pw.print(bs.mPackageName);
1917 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1918 pw.print(" running, "); pw.print(bs.numWakeup);
1919 pw.println(" wakeups:");
1920 tmpFilters.clear();
1921 for (int is=0; is<bs.filterStats.size(); is++) {
1922 tmpFilters.add(bs.filterStats.valueAt(is));
1923 }
1924 Collections.sort(tmpFilters, comparator);
1925 for (int i=0; i<tmpFilters.size(); i++) {
1926 FilterStats fs = tmpFilters.get(i);
1927 pw.print(" ");
1928 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1929 TimeUtils.formatDuration(fs.aggregateTime, pw);
1930 pw.print(" "); pw.print(fs.numWakeup);
1931 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001932 pw.print(" alarms, last ");
1933 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1934 pw.println(":");
1935 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001936 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001937 pw.println();
1938 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 }
1940 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001941
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001942 if (RECORD_DEVICE_IDLE_ALARMS) {
1943 pw.println();
1944 pw.println(" Allow while idle dispatches:");
1945 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
1946 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
1947 pw.print(" ");
1948 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
1949 pw.print(": ");
1950 UserHandle.formatUid(pw, ent.uid);
1951 pw.print(":");
1952 pw.println(ent.pkg);
1953 if (ent.op != null) {
1954 pw.print(" ");
1955 pw.print(ent.op);
1956 pw.print(" / ");
1957 pw.print(ent.tag);
1958 if (ent.argRealtime != 0) {
1959 pw.print(" (");
1960 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
1961 pw.print(")");
1962 }
1963 pw.println();
1964 }
1965 }
1966 }
1967
Christopher Tate18a75f12013-07-01 18:18:59 -07001968 if (WAKEUP_STATS) {
1969 pw.println();
1970 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001971 long last = -1;
1972 for (WakeupEvent event : mRecentWakeups) {
1973 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1974 pw.print('|');
1975 if (last < 0) {
1976 pw.print('0');
1977 } else {
1978 pw.print(event.when - last);
1979 }
1980 last = event.when;
1981 pw.print('|'); pw.print(event.uid);
1982 pw.print('|'); pw.print(event.action);
1983 pw.println();
1984 }
1985 pw.println();
1986 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 }
1988 }
1989
Kweku Adams61e03292017-10-19 14:27:12 -07001990 void dumpProto(FileDescriptor fd) {
1991 final ProtoOutputStream proto = new ProtoOutputStream(fd);
1992
1993 synchronized (mLock) {
1994 final long nowRTC = System.currentTimeMillis();
1995 final long nowElapsed = SystemClock.elapsedRealtime();
1996 proto.write(AlarmManagerServiceProto.CURRENT_TIME, nowRTC);
1997 proto.write(AlarmManagerServiceProto.ELAPSED_REALTIME, nowElapsed);
1998 proto.write(AlarmManagerServiceProto.LAST_TIME_CHANGE_CLOCK_TIME,
1999 mLastTimeChangeClockTime);
2000 proto.write(AlarmManagerServiceProto.LAST_TIME_CHANGE_REALTIME,
2001 mLastTimeChangeRealtime);
2002
2003 mConstants.dumpProto(proto, AlarmManagerServiceProto.SETTINGS);
2004
Makoto Onuki2206af32017-11-21 16:25:35 -08002005 mForceAppStandbyTracker.dumpProto(proto,
2006 AlarmManagerServiceProto.FORCE_APP_STANDBY_TRACKER);
Kweku Adams61e03292017-10-19 14:27:12 -07002007
2008 proto.write(AlarmManagerServiceProto.IS_INTERACTIVE, mInteractive);
2009 if (!mInteractive) {
2010 // Durations
2011 proto.write(AlarmManagerServiceProto.TIME_SINCE_NON_INTERACTIVE_MS,
2012 nowElapsed - mNonInteractiveStartTime);
2013 proto.write(AlarmManagerServiceProto.MAX_WAKEUP_DELAY_MS,
2014 currentNonWakeupFuzzLocked(nowElapsed));
2015 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_DISPATCH_MS,
2016 nowElapsed - mLastAlarmDeliveryTime);
2017 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_NON_WAKEUP_DELIVERY_MS,
2018 nowElapsed - mNextNonWakeupDeliveryTime);
2019 }
2020
2021 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_NON_WAKEUP_ALARM_MS,
2022 mNextNonWakeup - nowElapsed);
2023 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_WAKEUP_MS,
2024 mNextWakeup - nowElapsed);
2025 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_WAKEUP_MS,
2026 nowElapsed - mLastWakeup);
2027 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_WAKEUP_SET_MS,
2028 nowElapsed - mLastWakeupSet);
2029 proto.write(AlarmManagerServiceProto.TIME_CHANGE_EVENT_COUNT, mNumTimeChanged);
Kweku Adams61e03292017-10-19 14:27:12 -07002030
2031 final TreeSet<Integer> users = new TreeSet<>();
2032 final int nextAlarmClockForUserSize = mNextAlarmClockForUser.size();
2033 for (int i = 0; i < nextAlarmClockForUserSize; i++) {
2034 users.add(mNextAlarmClockForUser.keyAt(i));
2035 }
2036 final int pendingSendNextAlarmClockChangedForUserSize =
2037 mPendingSendNextAlarmClockChangedForUser.size();
2038 for (int i = 0; i < pendingSendNextAlarmClockChangedForUserSize; i++) {
2039 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2040 }
2041 for (int user : users) {
2042 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2043 final long time = next != null ? next.getTriggerTime() : 0;
2044 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
2045 final long aToken = proto.start(AlarmManagerServiceProto.NEXT_ALARM_CLOCK_METADATA);
2046 proto.write(AlarmClockMetadataProto.USER, user);
2047 proto.write(AlarmClockMetadataProto.IS_PENDING_SEND, pendingSend);
2048 proto.write(AlarmClockMetadataProto.TRIGGER_TIME_MS, time);
2049 proto.end(aToken);
2050 }
2051 for (Batch b : mAlarmBatches) {
2052 b.writeToProto(proto, AlarmManagerServiceProto.PENDING_ALARM_BATCHES,
2053 nowElapsed, nowRTC);
2054 }
2055 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2056 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2057 if (blockedAlarms != null) {
2058 for (Alarm a : blockedAlarms) {
2059 a.writeToProto(proto,
2060 AlarmManagerServiceProto.PENDING_USER_BLOCKED_BACKGROUND_ALARMS,
2061 nowElapsed, nowRTC);
2062 }
2063 }
2064 }
2065 if (mPendingIdleUntil != null) {
2066 mPendingIdleUntil.writeToProto(
2067 proto, AlarmManagerServiceProto.PENDING_IDLE_UNTIL, nowElapsed, nowRTC);
2068 }
2069 for (Alarm a : mPendingWhileIdleAlarms) {
2070 a.writeToProto(proto, AlarmManagerServiceProto.PENDING_WHILE_IDLE_ALARMS,
2071 nowElapsed, nowRTC);
2072 }
2073 if (mNextWakeFromIdle != null) {
2074 mNextWakeFromIdle.writeToProto(proto, AlarmManagerServiceProto.NEXT_WAKE_FROM_IDLE,
2075 nowElapsed, nowRTC);
2076 }
2077
2078 for (Alarm a : mPendingNonWakeupAlarms) {
2079 a.writeToProto(proto, AlarmManagerServiceProto.PAST_DUE_NON_WAKEUP_ALARMS,
2080 nowElapsed, nowRTC);
2081 }
2082
2083 proto.write(AlarmManagerServiceProto.DELAYED_ALARM_COUNT, mNumDelayedAlarms);
2084 proto.write(AlarmManagerServiceProto.TOTAL_DELAY_TIME_MS, mTotalDelayTime);
2085 proto.write(AlarmManagerServiceProto.MAX_DELAY_DURATION_MS, mMaxDelayTime);
2086 proto.write(AlarmManagerServiceProto.MAX_NON_INTERACTIVE_DURATION_MS,
2087 mNonInteractiveTime);
2088
2089 proto.write(AlarmManagerServiceProto.BROADCAST_REF_COUNT, mBroadcastRefCount);
2090 proto.write(AlarmManagerServiceProto.PENDING_INTENT_SEND_COUNT, mSendCount);
2091 proto.write(AlarmManagerServiceProto.PENDING_INTENT_FINISH_COUNT, mSendFinishCount);
2092 proto.write(AlarmManagerServiceProto.LISTENER_SEND_COUNT, mListenerCount);
2093 proto.write(AlarmManagerServiceProto.LISTENER_FINISH_COUNT, mListenerFinishCount);
2094
2095 for (InFlight f : mInFlight) {
2096 f.writeToProto(proto, AlarmManagerServiceProto.OUTSTANDING_DELIVERIES);
2097 }
2098
2099 proto.write(AlarmManagerServiceProto.ALLOW_WHILE_IDLE_MIN_DURATION_MS,
2100 mAllowWhileIdleMinTime);
2101 for (int i = 0; i < mLastAllowWhileIdleDispatch.size(); ++i) {
2102 final long token = proto.start(
2103 AlarmManagerServiceProto.LAST_ALLOW_WHILE_IDLE_DISPATCH_TIMES);
2104 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.UID,
2105 mLastAllowWhileIdleDispatch.keyAt(i));
2106 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.TIME_MS,
2107 mLastAllowWhileIdleDispatch.valueAt(i));
2108 proto.end(token);
2109 }
2110
2111 mLog.writeToProto(proto, AlarmManagerServiceProto.RECENT_PROBLEMS);
2112
2113 final FilterStats[] topFilters = new FilterStats[10];
2114 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2115 @Override
2116 public int compare(FilterStats lhs, FilterStats rhs) {
2117 if (lhs.aggregateTime < rhs.aggregateTime) {
2118 return 1;
2119 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2120 return -1;
2121 }
2122 return 0;
2123 }
2124 };
2125 int len = 0;
2126 // Get the top 10 FilterStats, ordered by aggregateTime.
2127 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2128 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2129 for (int ip = 0; ip < uidStats.size(); ++ip) {
2130 BroadcastStats bs = uidStats.valueAt(ip);
2131 for (int is = 0; is < bs.filterStats.size(); ++is) {
2132 FilterStats fs = bs.filterStats.valueAt(is);
2133 int pos = len > 0
2134 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2135 if (pos < 0) {
2136 pos = -pos - 1;
2137 }
2138 if (pos < topFilters.length) {
2139 int copylen = topFilters.length - pos - 1;
2140 if (copylen > 0) {
2141 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2142 }
2143 topFilters[pos] = fs;
2144 if (len < topFilters.length) {
2145 len++;
2146 }
2147 }
2148 }
2149 }
2150 }
2151 for (int i = 0; i < len; ++i) {
2152 final long token = proto.start(AlarmManagerServiceProto.TOP_ALARMS);
2153 FilterStats fs = topFilters[i];
2154
2155 proto.write(AlarmManagerServiceProto.TopAlarm.UID, fs.mBroadcastStats.mUid);
2156 proto.write(AlarmManagerServiceProto.TopAlarm.PACKAGE_NAME,
2157 fs.mBroadcastStats.mPackageName);
2158 fs.writeToProto(proto, AlarmManagerServiceProto.TopAlarm.FILTER);
2159
2160 proto.end(token);
2161 }
2162
2163 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
2164 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2165 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2166 for (int ip = 0; ip < uidStats.size(); ++ip) {
2167 final long token = proto.start(AlarmManagerServiceProto.ALARM_STATS);
2168
2169 BroadcastStats bs = uidStats.valueAt(ip);
2170 bs.writeToProto(proto, AlarmManagerServiceProto.AlarmStat.BROADCAST);
2171
2172 // uidStats is an ArrayMap, which we can't sort.
2173 tmpFilters.clear();
2174 for (int is = 0; is < bs.filterStats.size(); ++is) {
2175 tmpFilters.add(bs.filterStats.valueAt(is));
2176 }
2177 Collections.sort(tmpFilters, comparator);
2178 for (FilterStats fs : tmpFilters) {
2179 fs.writeToProto(proto, AlarmManagerServiceProto.AlarmStat.FILTERS);
2180 }
2181
2182 proto.end(token);
2183 }
2184 }
2185
2186 if (RECORD_DEVICE_IDLE_ALARMS) {
2187 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2188 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2189 final long token = proto.start(
2190 AlarmManagerServiceProto.ALLOW_WHILE_IDLE_DISPATCHES);
2191
2192 proto.write(IdleDispatchEntryProto.UID, ent.uid);
2193 proto.write(IdleDispatchEntryProto.PKG, ent.pkg);
2194 proto.write(IdleDispatchEntryProto.TAG, ent.tag);
2195 proto.write(IdleDispatchEntryProto.OP, ent.op);
2196 proto.write(IdleDispatchEntryProto.ENTRY_CREATION_REALTIME,
2197 ent.elapsedRealtime);
2198 proto.write(IdleDispatchEntryProto.ARG_REALTIME, ent.argRealtime);
2199
2200 proto.end(token);
2201 }
2202 }
2203
2204 if (WAKEUP_STATS) {
2205 for (WakeupEvent event : mRecentWakeups) {
2206 final long token = proto.start(AlarmManagerServiceProto.RECENT_WAKEUP_HISTORY);
2207 proto.write(WakeupEventProto.UID, event.uid);
2208 proto.write(WakeupEventProto.ACTION, event.action);
2209 proto.write(WakeupEventProto.WHEN, event.when);
2210 proto.end(token);
2211 }
2212 }
2213 }
2214
2215 proto.flush();
2216 }
2217
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002218 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002219 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
2220 PrintWriter pw = new PrintWriter(bs);
2221 final long nowRTC = System.currentTimeMillis();
2222 final long nowELAPSED = SystemClock.elapsedRealtime();
2223 final int NZ = mAlarmBatches.size();
2224 for (int iz = 0; iz < NZ; iz++) {
2225 Batch bz = mAlarmBatches.get(iz);
2226 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002227 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002228 pw.flush();
2229 Slog.v(TAG, bs.toString());
2230 bs.reset();
2231 }
2232 }
2233
2234 private boolean validateConsistencyLocked() {
2235 if (DEBUG_VALIDATE) {
2236 long lastTime = Long.MIN_VALUE;
2237 final int N = mAlarmBatches.size();
2238 for (int i = 0; i < N; i++) {
2239 Batch b = mAlarmBatches.get(i);
2240 if (b.start >= lastTime) {
2241 // duplicate start times are okay because of standalone batches
2242 lastTime = b.start;
2243 } else {
2244 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002245 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2246 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002247 return false;
2248 }
2249 }
2250 }
2251 return true;
2252 }
2253
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002254 private Batch findFirstWakeupBatchLocked() {
2255 final int N = mAlarmBatches.size();
2256 for (int i = 0; i < N; i++) {
2257 Batch b = mAlarmBatches.get(i);
2258 if (b.hasWakeups()) {
2259 return b;
2260 }
2261 }
2262 return null;
2263 }
2264
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002265 long getNextWakeFromIdleTimeImpl() {
2266 synchronized (mLock) {
2267 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
2268 }
2269 }
2270
2271 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002272 synchronized (mLock) {
2273 return mNextAlarmClockForUser.get(userId);
2274 }
2275 }
2276
2277 /**
2278 * Recomputes the next alarm clock for all users.
2279 */
2280 private void updateNextAlarmClockLocked() {
2281 if (!mNextAlarmClockMayChange) {
2282 return;
2283 }
2284 mNextAlarmClockMayChange = false;
2285
Jose Lima235510e2014-08-13 12:50:01 -07002286 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002287 nextForUser.clear();
2288
2289 final int N = mAlarmBatches.size();
2290 for (int i = 0; i < N; i++) {
2291 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
2292 final int M = alarms.size();
2293
2294 for (int j = 0; j < M; j++) {
2295 Alarm a = alarms.get(j);
2296 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002297 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07002298 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002299
2300 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07002301 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002302 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02002303 " for user " + userId);
2304 }
2305
2306 // Alarms and batches are sorted by time, no need to compare times here.
2307 if (nextForUser.get(userId) == null) {
2308 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07002309 } else if (a.alarmClock.equals(current)
2310 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
2311 // same/earlier time and it's the one we cited before, so stick with it
2312 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002313 }
2314 }
2315 }
2316 }
2317
2318 // Update mNextAlarmForUser with new values.
2319 final int NN = nextForUser.size();
2320 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07002321 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002322 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002323 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002324 if (!newAlarm.equals(currentAlarm)) {
2325 updateNextAlarmInfoForUserLocked(userId, newAlarm);
2326 }
2327 }
2328
2329 // Remove users without any alarm clocks scheduled.
2330 final int NNN = mNextAlarmClockForUser.size();
2331 for (int i = NNN - 1; i >= 0; i--) {
2332 int userId = mNextAlarmClockForUser.keyAt(i);
2333 if (nextForUser.get(userId) == null) {
2334 updateNextAlarmInfoForUserLocked(userId, null);
2335 }
2336 }
2337 }
2338
Jose Lima235510e2014-08-13 12:50:01 -07002339 private void updateNextAlarmInfoForUserLocked(int userId,
2340 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002341 if (alarmClock != null) {
2342 if (DEBUG_ALARM_CLOCK) {
2343 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002344 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02002345 }
2346 mNextAlarmClockForUser.put(userId, alarmClock);
2347 } else {
2348 if (DEBUG_ALARM_CLOCK) {
2349 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
2350 }
2351 mNextAlarmClockForUser.remove(userId);
2352 }
2353
2354 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
2355 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2356 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2357 }
2358
2359 /**
2360 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
2361 * for which alarm clocks have changed since the last call to this.
2362 *
2363 * Do not call with a lock held. Only call from mHandler's thread.
2364 *
2365 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
2366 */
2367 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07002368 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002369 pendingUsers.clear();
2370
2371 synchronized (mLock) {
2372 final int N = mPendingSendNextAlarmClockChangedForUser.size();
2373 for (int i = 0; i < N; i++) {
2374 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
2375 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
2376 }
2377 mPendingSendNextAlarmClockChangedForUser.clear();
2378 }
2379
2380 final int N = pendingUsers.size();
2381 for (int i = 0; i < N; i++) {
2382 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002383 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002384 Settings.System.putStringForUser(getContext().getContentResolver(),
2385 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01002386 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02002387 userId);
2388
2389 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
2390 new UserHandle(userId));
2391 }
2392 }
2393
2394 /**
2395 * Formats an alarm like platform/packages/apps/DeskClock used to.
2396 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01002397 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
2398 int userId) {
2399 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02002400 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
2401 return (info == null) ? "" :
2402 DateFormat.format(pattern, info.getTriggerTime()).toString();
2403 }
2404
Adam Lesinski182f73f2013-12-05 16:48:06 -08002405 void rescheduleKernelAlarmsLocked() {
2406 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
2407 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002408 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002409 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002410 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002411 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07002412 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002413 mNextWakeup = firstWakeup.start;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002414 mLastWakeupSet = SystemClock.elapsedRealtime();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002415 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002416 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002417 if (firstBatch != firstWakeup) {
2418 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002419 }
2420 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002421 if (mPendingNonWakeupAlarms.size() > 0) {
2422 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
2423 nextNonWakeup = mNextNonWakeupDeliveryTime;
2424 }
2425 }
Prashant Malani753e9e02015-06-10 17:43:49 -07002426 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002427 mNextNonWakeup = nextNonWakeup;
2428 setLocked(ELAPSED_REALTIME, nextNonWakeup);
2429 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002430 }
2431
Christopher Tate14a7bb02015-10-01 10:24:31 -07002432 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002433 boolean didRemove = false;
2434 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2435 Batch b = mAlarmBatches.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002436 didRemove |= b.remove(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002437 if (b.size() == 0) {
2438 mAlarmBatches.remove(i);
2439 }
2440 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002441 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002442 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002443 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2444 mPendingWhileIdleAlarms.remove(i);
2445 }
2446 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002447 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2448 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2449 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2450 if (alarmsForUid.get(j).matches(operation, directReceiver)) {
2451 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2452 alarmsForUid.remove(j);
2453 }
2454 }
2455 if (alarmsForUid.size() == 0) {
2456 mPendingBackgroundAlarms.removeAt(i);
2457 }
2458 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002459 if (didRemove) {
2460 if (DEBUG_BATCH) {
2461 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
2462 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002463 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002464 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002465 mPendingIdleUntil = null;
2466 restorePending = true;
2467 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002468 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002469 mNextWakeFromIdle = null;
2470 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002471 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002472 if (restorePending) {
2473 restorePendingWhileIdleAlarmsLocked();
2474 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002475 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002476 }
2477 }
2478
2479 void removeLocked(String packageName) {
2480 boolean didRemove = false;
2481 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2482 Batch b = mAlarmBatches.get(i);
2483 didRemove |= b.remove(packageName);
2484 if (b.size() == 0) {
2485 mAlarmBatches.remove(i);
2486 }
2487 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002488 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002489 final Alarm a = mPendingWhileIdleAlarms.get(i);
2490 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002491 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2492 mPendingWhileIdleAlarms.remove(i);
2493 }
2494 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002495 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2496 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2497 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2498 if (alarmsForUid.get(j).matches(packageName)) {
2499 alarmsForUid.remove(j);
2500 }
2501 }
2502 if (alarmsForUid.size() == 0) {
2503 mPendingBackgroundAlarms.removeAt(i);
2504 }
2505 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002506 if (didRemove) {
2507 if (DEBUG_BATCH) {
2508 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2509 }
2510 rebatchAllAlarmsLocked(true);
2511 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002512 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002513 }
2514 }
2515
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002516 void removeForStoppedLocked(int uid) {
2517 boolean didRemove = false;
2518 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2519 Batch b = mAlarmBatches.get(i);
2520 didRemove |= b.removeForStopped(uid);
2521 if (b.size() == 0) {
2522 mAlarmBatches.remove(i);
2523 }
2524 }
2525 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2526 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08002527 if (a.uid == uid) {
2528 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2529 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002530 }
2531 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002532 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2533 if (mPendingBackgroundAlarms.keyAt(i) == uid) {
2534 mPendingBackgroundAlarms.removeAt(i);
2535 }
2536 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002537 if (didRemove) {
2538 if (DEBUG_BATCH) {
2539 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2540 }
2541 rebatchAllAlarmsLocked(true);
2542 rescheduleKernelAlarmsLocked();
2543 updateNextAlarmClockLocked();
2544 }
2545 }
2546
Adam Lesinski182f73f2013-12-05 16:48:06 -08002547 void removeUserLocked(int userHandle) {
2548 boolean didRemove = false;
2549 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2550 Batch b = mAlarmBatches.get(i);
2551 didRemove |= b.remove(userHandle);
2552 if (b.size() == 0) {
2553 mAlarmBatches.remove(i);
2554 }
2555 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002556 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002557 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002558 == userHandle) {
2559 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2560 mPendingWhileIdleAlarms.remove(i);
2561 }
2562 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002563 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2564 if (UserHandle.getUserId(mPendingBackgroundAlarms.keyAt(i)) == userHandle) {
2565 mPendingBackgroundAlarms.removeAt(i);
2566 }
2567 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002568 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
2569 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
2570 mLastAllowWhileIdleDispatch.removeAt(i);
2571 }
2572 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002573
2574 if (didRemove) {
2575 if (DEBUG_BATCH) {
2576 Slog.v(TAG, "remove(user) changed bounds; rebatching");
2577 }
2578 rebatchAllAlarmsLocked(true);
2579 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002580 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002581 }
2582 }
2583
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002584 void interactiveStateChangedLocked(boolean interactive) {
2585 if (mInteractive != interactive) {
2586 mInteractive = interactive;
2587 final long nowELAPSED = SystemClock.elapsedRealtime();
2588 if (interactive) {
2589 if (mPendingNonWakeupAlarms.size() > 0) {
2590 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2591 mTotalDelayTime += thisDelayTime;
2592 if (mMaxDelayTime < thisDelayTime) {
2593 mMaxDelayTime = thisDelayTime;
2594 }
2595 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2596 mPendingNonWakeupAlarms.clear();
2597 }
2598 if (mNonInteractiveStartTime > 0) {
2599 long dur = nowELAPSED - mNonInteractiveStartTime;
2600 if (dur > mNonInteractiveTime) {
2601 mNonInteractiveTime = dur;
2602 }
2603 }
2604 } else {
2605 mNonInteractiveStartTime = nowELAPSED;
2606 }
2607 }
2608 }
2609
Adam Lesinski182f73f2013-12-05 16:48:06 -08002610 boolean lookForPackageLocked(String packageName) {
2611 for (int i = 0; i < mAlarmBatches.size(); i++) {
2612 Batch b = mAlarmBatches.get(i);
2613 if (b.hasPackage(packageName)) {
2614 return true;
2615 }
2616 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002617 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002618 final Alarm a = mPendingWhileIdleAlarms.get(i);
2619 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002620 return true;
2621 }
2622 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002623 return false;
2624 }
2625
2626 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002627 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002628 // The kernel never triggers alarms with negative wakeup times
2629 // so we ensure they are positive.
2630 long alarmSeconds, alarmNanoseconds;
2631 if (when < 0) {
2632 alarmSeconds = 0;
2633 alarmNanoseconds = 0;
2634 } else {
2635 alarmSeconds = when / 1000;
2636 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2637 }
Kweku Adams61e03292017-10-19 14:27:12 -07002638
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002639 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002640 } else {
2641 Message msg = Message.obtain();
2642 msg.what = ALARM_EVENT;
Kweku Adams61e03292017-10-19 14:27:12 -07002643
Adam Lesinski182f73f2013-12-05 16:48:06 -08002644 mHandler.removeMessages(ALARM_EVENT);
2645 mHandler.sendMessageAtTime(msg, when);
2646 }
2647 }
2648
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002649 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Kweku Adams61e03292017-10-19 14:27:12 -07002650 String prefix, String label, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002651 for (int i=list.size()-1; i>=0; i--) {
2652 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002653 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2654 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002655 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002656 }
2657 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002658
2659 private static final String labelForType(int type) {
2660 switch (type) {
2661 case RTC: return "RTC";
2662 case RTC_WAKEUP : return "RTC_WAKEUP";
2663 case ELAPSED_REALTIME : return "ELAPSED";
2664 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
Christopher Tatee0a22b32013-07-11 14:43:13 -07002665 }
2666 return "--unknown--";
2667 }
2668
2669 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002670 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002671 for (int i=list.size()-1; i>=0; i--) {
2672 Alarm a = list.get(i);
2673 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002674 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2675 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002676 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002677 }
2678 }
2679
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002680 private boolean isBackgroundRestricted(Alarm alarm) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002681 if (alarm.alarmClock != null) {
2682 // Don't block alarm clocks
2683 return false;
2684 }
2685 if (alarm.operation != null
2686 && (alarm.operation.isActivity() || alarm.operation.isForegroundService())) {
2687 // Don't block starting foreground components
2688 return false;
2689 }
2690 final String sourcePackage =
2691 (alarm.operation != null) ? alarm.operation.getCreatorPackage() : alarm.packageName;
2692 final int sourceUid = alarm.creatorUid;
Makoto Onuki2206af32017-11-21 16:25:35 -08002693 return mForceAppStandbyTracker.areAlarmsRestricted(sourceUid, sourcePackage);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002694 }
2695
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002696 private native long init();
2697 private native void close(long nativeData);
2698 private native void set(long nativeData, int type, long seconds, long nanoseconds);
2699 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08002700 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002701 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002702
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002703 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002704 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002705 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002706 // batches are temporally sorted, so we need only pull from the
2707 // start of the list until we either empty it or hit a batch
2708 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07002709 while (mAlarmBatches.size() > 0) {
2710 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002711 if (batch.start > nowELAPSED) {
2712 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002713 break;
2714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002715
Christopher Tatee0a22b32013-07-11 14:43:13 -07002716 // We will (re)schedule some alarms now; don't let that interfere
2717 // with delivery of this current batch
2718 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002719
Christopher Tatee0a22b32013-07-11 14:43:13 -07002720 final int N = batch.size();
2721 for (int i = 0; i < N; i++) {
2722 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002723
2724 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
2725 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
2726 // schedule such alarms.
2727 long lastTime = mLastAllowWhileIdleDispatch.get(alarm.uid, 0);
2728 long minTime = lastTime + mAllowWhileIdleMinTime;
2729 if (nowELAPSED < minTime) {
2730 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
2731 // alarm went off for this app. Reschedule the alarm to be in the
2732 // correct time period.
2733 alarm.whenElapsed = minTime;
2734 if (alarm.maxWhenElapsed < minTime) {
2735 alarm.maxWhenElapsed = minTime;
2736 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002737 if (RECORD_DEVICE_IDLE_ALARMS) {
2738 IdleDispatchEntry ent = new IdleDispatchEntry();
2739 ent.uid = alarm.uid;
2740 ent.pkg = alarm.operation.getCreatorPackage();
2741 ent.tag = alarm.operation.getTag("");
2742 ent.op = "RESCHEDULE";
2743 ent.elapsedRealtime = nowELAPSED;
2744 ent.argRealtime = lastTime;
2745 mAllowWhileIdleDispatches.add(ent);
2746 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002747 setImplLocked(alarm, true, false);
2748 continue;
2749 }
2750 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002751 if (isBackgroundRestricted(alarm)) {
2752 // Alarms with FLAG_WAKE_FROM_IDLE or mPendingIdleUntil alarm are not deferred
2753 if (DEBUG_BG_LIMIT) {
2754 Slog.d(TAG, "Deferring alarm " + alarm + " due to user forced app standby");
2755 }
2756 ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(alarm.creatorUid);
2757 if (alarmsForUid == null) {
2758 alarmsForUid = new ArrayList<>();
2759 mPendingBackgroundAlarms.put(alarm.creatorUid, alarmsForUid);
2760 }
2761 alarmsForUid.add(alarm);
2762 continue;
2763 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002764
Christopher Tatee0a22b32013-07-11 14:43:13 -07002765 alarm.count = 1;
2766 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002767 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
2768 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002769 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002770 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002771 if (mPendingIdleUntil == alarm) {
2772 mPendingIdleUntil = null;
2773 rebatchAllAlarmsLocked(false);
2774 restorePendingWhileIdleAlarmsLocked();
2775 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002776 if (mNextWakeFromIdle == alarm) {
2777 mNextWakeFromIdle = null;
2778 rebatchAllAlarmsLocked(false);
2779 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002780
2781 // Recurring alarms may have passed several alarm intervals while the
2782 // phone was asleep or off, so pass a trigger count when sending them.
2783 if (alarm.repeatInterval > 0) {
2784 // this adjustment will be zero if we're late by
2785 // less than one full repeat interval
2786 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
2787
2788 // Also schedule its next recurrence
2789 final long delta = alarm.count * alarm.repeatInterval;
2790 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07002791 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07002792 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07002793 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
2794 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08002795 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796
Christopher Tate864d42e2014-12-02 11:48:53 -08002797 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002798 hasWakeup = true;
2799 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002800
2801 // We removed an alarm clock. Let the caller recompute the next alarm clock.
2802 if (alarm.alarmClock != null) {
2803 mNextAlarmClockMayChange = true;
2804 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07002805 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002806 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002807
Christopher Tate1590f1e2014-10-02 17:27:57 -07002808 // This is a new alarm delivery set; bump the sequence number to indicate that
2809 // all apps' alarm delivery classes should be recalculated.
2810 mCurrentSeq++;
2811 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002812 Collections.sort(triggerList, mAlarmDispatchComparator);
2813
2814 if (localLOGV) {
2815 for (int i=0; i<triggerList.size(); i++) {
2816 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
2817 }
2818 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002819
2820 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002821 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002823 /**
2824 * This Comparator sorts Alarms into increasing time order.
2825 */
2826 public static class IncreasingTimeOrder implements Comparator<Alarm> {
2827 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09002828 long when1 = a1.whenElapsed;
2829 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002830 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831 return 1;
2832 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002833 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002834 return -1;
2835 }
2836 return 0;
2837 }
2838 }
Kweku Adams61e03292017-10-19 14:27:12 -07002839
Makoto Onuki2206af32017-11-21 16:25:35 -08002840 @VisibleForTesting
2841 static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002842 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002843 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002844 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002845 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002846 public final IAlarmListener listener;
2847 public final String listenerTag;
2848 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002849 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002850 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002851 public final AlarmManager.AlarmClockInfo alarmClock;
2852 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002853 public final int creatorUid;
2854 public final String packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002855 public int count;
2856 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07002857 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002858 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002859 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002860 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07002861 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002862
Christopher Tate3e04b472013-10-21 17:51:31 -07002863 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002864 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
2865 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
2866 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002867 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002868 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002869 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
2870 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002871 when = _when;
2872 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07002873 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002874 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002875 repeatInterval = _interval;
2876 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002877 listener = _rec;
2878 listenerTag = _listenerTag;
2879 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07002880 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002881 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002882 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002883 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002884 packageName = _pkgName;
2885
2886 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002887 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002888
Christopher Tate14a7bb02015-10-01 10:24:31 -07002889 public static String makeTag(PendingIntent pi, String tag, int type) {
2890 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
2891 ? "*walarm*:" : "*alarm*:";
2892 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
2893 }
2894
2895 public WakeupEvent makeWakeupEvent(long nowRTC) {
2896 return new WakeupEvent(nowRTC, creatorUid,
2897 (operation != null)
2898 ? operation.getIntent().getAction()
2899 : ("<listener>:" + listenerTag));
2900 }
2901
2902 // Returns true if either matches
2903 public boolean matches(PendingIntent pi, IAlarmListener rec) {
2904 return (operation != null)
2905 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09002906 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07002907 }
2908
2909 public boolean matches(String packageName) {
2910 return (operation != null)
2911 ? packageName.equals(operation.getTargetPackage())
2912 : packageName.equals(this.packageName);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002913 }
2914
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002915 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002916 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002917 StringBuilder sb = new StringBuilder(128);
2918 sb.append("Alarm{");
2919 sb.append(Integer.toHexString(System.identityHashCode(this)));
2920 sb.append(" type ");
2921 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002922 sb.append(" when ");
2923 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002924 sb.append(" ");
Christopher Tate14a7bb02015-10-01 10:24:31 -07002925 if (operation != null) {
2926 sb.append(operation.getTargetPackage());
2927 } else {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002928 sb.append(packageName);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002929 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002930 sb.append('}');
2931 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002932 }
2933
Kweku Adams61e03292017-10-19 14:27:12 -07002934 public void dump(PrintWriter pw, String prefix, long nowELAPSED, long nowRTC,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002935 SimpleDateFormat sdf) {
2936 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002937 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002938 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002939 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
2940 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002941 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002942 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002943 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002944 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002945 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002946 }
2947 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002948 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002949 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002950 pw.print(" count="); pw.print(count);
2951 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002952 if (alarmClock != null) {
2953 pw.print(prefix); pw.println("Alarm clock:");
2954 pw.print(prefix); pw.print(" triggerTime=");
2955 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
2956 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
2957 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002958 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002959 if (listener != null) {
2960 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
2961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002962 }
Kweku Adams61e03292017-10-19 14:27:12 -07002963
2964 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
2965 long nowRTC) {
2966 final long token = proto.start(fieldId);
2967
2968 proto.write(AlarmProto.TAG, statsTag);
2969 proto.write(AlarmProto.TYPE, type);
Kweku Adams923ec432017-12-11 18:05:38 -08002970 proto.write(AlarmProto.TIME_UNTIL_WHEN_ELAPSED_MS, whenElapsed - nowElapsed);
Kweku Adams61e03292017-10-19 14:27:12 -07002971 proto.write(AlarmProto.WINDOW_LENGTH_MS, windowLength);
2972 proto.write(AlarmProto.REPEAT_INTERVAL_MS, repeatInterval);
2973 proto.write(AlarmProto.COUNT, count);
2974 proto.write(AlarmProto.FLAGS, flags);
2975 if (alarmClock != null) {
2976 alarmClock.writeToProto(proto, AlarmProto.ALARM_CLOCK);
2977 }
2978 if (operation != null) {
2979 operation.writeToProto(proto, AlarmProto.OPERATION);
2980 }
2981 if (listener != null) {
2982 proto.write(AlarmProto.LISTENER, listener.asBinder().toString());
2983 }
2984
2985 proto.end(token);
2986 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002987 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002988
Christopher Tatee0a22b32013-07-11 14:43:13 -07002989 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
2990 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002991 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
2992 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002993 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07002994 break;
2995 }
2996
Christopher Tatee0a22b32013-07-11 14:43:13 -07002997 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002998 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
2999 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003000 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07003001 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003002 }
3003 }
3004
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003005 long currentNonWakeupFuzzLocked(long nowELAPSED) {
3006 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
3007 if (timeSinceOn < 5*60*1000) {
3008 // If the screen has been off for 5 minutes, only delay by at most two minutes.
3009 return 2*60*1000;
3010 } else if (timeSinceOn < 30*60*1000) {
3011 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
3012 return 15*60*1000;
3013 } else {
3014 // Otherwise, we will delay by at most an hour.
3015 return 60*60*1000;
3016 }
3017 }
3018
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003019 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003020 if (duration < 15*60*1000) {
3021 // If the duration until the time is less than 15 minutes, the maximum fuzz
3022 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003023 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003024 } else if (duration < 90*60*1000) {
3025 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
3026 return 15*60*1000;
3027 } else {
3028 // Otherwise, we will fuzz by at most half an hour.
3029 return 30*60*1000;
3030 }
3031 }
3032
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003033 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
3034 if (mInteractive) {
3035 return false;
3036 }
3037 if (mLastAlarmDeliveryTime <= 0) {
3038 return false;
3039 }
minho.choo649acab2014-12-12 16:13:55 +09003040 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003041 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
3042 // and the next delivery time is in the past, then just deliver them all. This
3043 // avoids bugs where we get stuck in a loop trying to poll for alarms.
3044 return false;
3045 }
3046 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
3047 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
3048 }
3049
3050 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
3051 mLastAlarmDeliveryTime = nowELAPSED;
3052 for (int i=0; i<triggerList.size(); i++) {
3053 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07003054 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Tim Murray175c0f92017-11-28 15:01:04 -08003055 if (alarm.wakeup) {
3056 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch wakeup alarm to " + alarm.packageName);
3057 } else {
3058 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch non-wakeup alarm to " + alarm.packageName);
3059 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003060 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07003061 if (localLOGV) {
3062 Slog.v(TAG, "sending alarm " + alarm);
3063 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07003064 if (RECORD_ALARMS_IN_HISTORY) {
3065 if (alarm.workSource != null && alarm.workSource.size() > 0) {
3066 for (int wi=0; wi<alarm.workSource.size(); wi++) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003067 ActivityManager.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003068 alarm.operation, alarm.workSource.get(wi), alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003069 }
3070 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003071 ActivityManager.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003072 alarm.operation, alarm.uid, alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003073 }
3074 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003075 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003076 } catch (RuntimeException e) {
3077 Slog.w(TAG, "Failure sending alarm.", e);
3078 }
Tim Murray175c0f92017-11-28 15:01:04 -08003079 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003080 }
3081 }
3082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003083 private class AlarmThread extends Thread
3084 {
3085 public AlarmThread()
3086 {
3087 super("AlarmManager");
3088 }
Kweku Adams61e03292017-10-19 14:27:12 -07003089
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003090 public void run()
3091 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003092 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3093
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003094 while (true)
3095 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003096 int result = waitForAlarm(mNativeData);
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003097 mLastWakeup = SystemClock.elapsedRealtime();
Dianne Hackborn390517b2013-05-30 15:03:32 -07003098
3099 triggerList.clear();
3100
Dianne Hackbornc3527222015-05-13 14:03:20 -07003101 final long nowRTC = System.currentTimeMillis();
3102 final long nowELAPSED = SystemClock.elapsedRealtime();
3103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003104 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003105 // The kernel can give us spurious time change notifications due to
3106 // small adjustments it makes internally; we want to filter those out.
3107 final long lastTimeChangeClockTime;
3108 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07003109 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003110 lastTimeChangeClockTime = mLastTimeChangeClockTime;
3111 expectedClockTime = lastTimeChangeClockTime
3112 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07003113 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003114 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
3115 || nowRTC > (expectedClockTime+1000)) {
3116 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07003117 // let's do it!
3118 if (DEBUG_BATCH) {
3119 Slog.v(TAG, "Time changed notification from kernel; rebatching");
3120 }
3121 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07003122 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003123 rebatchAllAlarms();
3124 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07003125 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003126 synchronized (mLock) {
3127 mNumTimeChanged++;
3128 mLastTimeChangeClockTime = nowRTC;
3129 mLastTimeChangeRealtime = nowELAPSED;
3130 }
3131 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
3132 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003133 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07003134 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
3135 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003136 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
3137
3138 // The world has changed on us, so we need to re-evaluate alarms
3139 // regardless of whether the kernel has told us one went off.
3140 result |= IS_WAKEUP_MASK;
3141 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003142 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003143
Dianne Hackbornc3527222015-05-13 14:03:20 -07003144 if (result != TIME_CHANGED_MASK) {
3145 // If this was anything besides just a time change, then figure what if
3146 // anything to do about alarms.
3147 synchronized (mLock) {
3148 if (localLOGV) Slog.v(
3149 TAG, "Checking for alarms... rtc=" + nowRTC
3150 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07003151
Dianne Hackbornc3527222015-05-13 14:03:20 -07003152 if (WAKEUP_STATS) {
3153 if ((result & IS_WAKEUP_MASK) != 0) {
3154 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
3155 int n = 0;
3156 for (WakeupEvent event : mRecentWakeups) {
3157 if (event.when > newEarliest) break;
3158 n++; // number of now-stale entries at the list head
3159 }
3160 for (int i = 0; i < n; i++) {
3161 mRecentWakeups.remove();
3162 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003163
Dianne Hackbornc3527222015-05-13 14:03:20 -07003164 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003165 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003166 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003167
3168 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3169 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
3170 // if there are no wakeup alarms and the screen is off, we can
3171 // delay what we have so far until the future.
3172 if (mPendingNonWakeupAlarms.size() == 0) {
3173 mStartCurrentDelayTime = nowELAPSED;
3174 mNextNonWakeupDeliveryTime = nowELAPSED
3175 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
3176 }
3177 mPendingNonWakeupAlarms.addAll(triggerList);
3178 mNumDelayedAlarms += triggerList.size();
3179 rescheduleKernelAlarmsLocked();
3180 updateNextAlarmClockLocked();
3181 } else {
3182 // now deliver the alarm intents; if there are pending non-wakeup
3183 // alarms, we need to merge them in to the list. note we don't
3184 // just deliver them first because we generally want non-wakeup
3185 // alarms delivered after wakeup alarms.
3186 rescheduleKernelAlarmsLocked();
3187 updateNextAlarmClockLocked();
3188 if (mPendingNonWakeupAlarms.size() > 0) {
3189 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
3190 triggerList.addAll(mPendingNonWakeupAlarms);
3191 Collections.sort(triggerList, mAlarmDispatchComparator);
3192 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3193 mTotalDelayTime += thisDelayTime;
3194 if (mMaxDelayTime < thisDelayTime) {
3195 mMaxDelayTime = thisDelayTime;
3196 }
3197 mPendingNonWakeupAlarms.clear();
3198 }
3199 deliverAlarmsLocked(triggerList, nowELAPSED);
3200 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003201 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003202
3203 } else {
3204 // Just in case -- even though no wakeup flag was set, make sure
3205 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07003206 synchronized (mLock) {
3207 rescheduleKernelAlarmsLocked();
3208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003209 }
3210 }
3211 }
3212 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003213
David Christieebe51fc2013-07-26 13:23:29 -07003214 /**
3215 * Attribute blame for a WakeLock.
3216 * @param pi PendingIntent to attribute blame to if ws is null.
3217 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003218 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07003219 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003220 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003221 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07003222 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003223 final boolean unimportant = pi == mTimeTickSender;
3224 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003225 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003226 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003227 } else {
3228 mWakeLock.setHistoryTag(null);
3229 }
3230 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07003231 if (ws != null) {
3232 mWakeLock.setWorkSource(ws);
3233 return;
3234 }
3235
Christopher Tate14a7bb02015-10-01 10:24:31 -07003236 final int uid = (knownUid >= 0)
3237 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003238 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07003239 if (uid >= 0) {
3240 mWakeLock.setWorkSource(new WorkSource(uid));
3241 return;
3242 }
3243 } catch (Exception e) {
3244 }
3245
3246 // Something went wrong; fall back to attributing the lock to the OS
3247 mWakeLock.setWorkSource(null);
3248 }
3249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003250 private class AlarmHandler extends Handler {
3251 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003252 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
3253 public static final int LISTENER_TIMEOUT = 3;
3254 public static final int REPORT_ALARMS_ACTIVE = 4;
Kweku Adams61e03292017-10-19 14:27:12 -07003255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003256 public AlarmHandler() {
3257 }
Kweku Adams61e03292017-10-19 14:27:12 -07003258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003259 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003260 switch (msg.what) {
3261 case ALARM_EVENT: {
3262 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3263 synchronized (mLock) {
3264 final long nowRTC = System.currentTimeMillis();
3265 final long nowELAPSED = SystemClock.elapsedRealtime();
3266 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3267 updateNextAlarmClockLocked();
3268 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003269
Christopher Tate14a7bb02015-10-01 10:24:31 -07003270 // now trigger the alarms without the lock held
3271 for (int i=0; i<triggerList.size(); i++) {
3272 Alarm alarm = triggerList.get(i);
3273 try {
3274 alarm.operation.send();
3275 } catch (PendingIntent.CanceledException e) {
3276 if (alarm.repeatInterval > 0) {
3277 // This IntentSender is no longer valid, but this
3278 // is a repeating alarm, so toss the hoser.
3279 removeImpl(alarm.operation);
3280 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003281 }
3282 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003283 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003284 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003285
3286 case SEND_NEXT_ALARM_CLOCK_CHANGED:
3287 sendNextAlarmClockChanged();
3288 break;
3289
3290 case LISTENER_TIMEOUT:
3291 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
3292 break;
3293
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003294 case REPORT_ALARMS_ACTIVE:
3295 if (mLocalDeviceIdleController != null) {
3296 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
3297 }
3298 break;
3299
Christopher Tate14a7bb02015-10-01 10:24:31 -07003300 default:
3301 // nope, just ignore it
3302 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003303 }
3304 }
3305 }
Kweku Adams61e03292017-10-19 14:27:12 -07003306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003307 class ClockReceiver extends BroadcastReceiver {
3308 public ClockReceiver() {
3309 IntentFilter filter = new IntentFilter();
3310 filter.addAction(Intent.ACTION_TIME_TICK);
3311 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003312 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003313 }
Kweku Adams61e03292017-10-19 14:27:12 -07003314
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003315 @Override
3316 public void onReceive(Context context, Intent intent) {
3317 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07003318 if (DEBUG_BATCH) {
3319 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
3320 }
3321 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003322 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
3323 // Since the kernel does not keep track of DST, we need to
3324 // reset the TZ information at the beginning of each day
3325 // based off of the current Zone gmt offset + userspace tracked
3326 // daylight savings information.
3327 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02003328 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003329 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07003330 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003331 }
3332 }
Kweku Adams61e03292017-10-19 14:27:12 -07003333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003334 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07003335 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09003336 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07003337
3338 // Schedule this event for the amount of time that it would take to get to
3339 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09003340 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07003341
David Christieebe51fc2013-07-26 13:23:29 -07003342 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08003343 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003344 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
3345 null, Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003346 }
Christopher Tate385e4982013-07-23 18:22:29 -07003347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003348 public void scheduleDateChangedEvent() {
3349 Calendar calendar = Calendar.getInstance();
3350 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07003351 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003352 calendar.set(Calendar.MINUTE, 0);
3353 calendar.set(Calendar.SECOND, 0);
3354 calendar.set(Calendar.MILLISECOND, 0);
3355 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07003356
3357 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003358 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
3359 AlarmManager.FLAG_STANDALONE, workSource, null,
3360 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003361 }
3362 }
Kweku Adams61e03292017-10-19 14:27:12 -07003363
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003364 class InteractiveStateReceiver extends BroadcastReceiver {
3365 public InteractiveStateReceiver() {
3366 IntentFilter filter = new IntentFilter();
3367 filter.addAction(Intent.ACTION_SCREEN_OFF);
3368 filter.addAction(Intent.ACTION_SCREEN_ON);
3369 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
3370 getContext().registerReceiver(this, filter);
3371 }
3372
3373 @Override
3374 public void onReceive(Context context, Intent intent) {
3375 synchronized (mLock) {
3376 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
3377 }
3378 }
3379 }
3380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003381 class UninstallReceiver extends BroadcastReceiver {
3382 public UninstallReceiver() {
3383 IntentFilter filter = new IntentFilter();
3384 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
3385 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003386 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003387 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08003388 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003389 // Register for events related to sdcard installation.
3390 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08003391 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003392 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003393 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003394 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003395 }
Kweku Adams61e03292017-10-19 14:27:12 -07003396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003397 @Override
3398 public void onReceive(Context context, Intent intent) {
3399 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003400 String action = intent.getAction();
3401 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003402 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
3403 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
3404 for (String packageName : pkgList) {
3405 if (lookForPackageLocked(packageName)) {
3406 setResultCode(Activity.RESULT_OK);
3407 return;
3408 }
3409 }
3410 return;
3411 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003412 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003413 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
3414 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
3415 if (userHandle >= 0) {
3416 removeUserLocked(userHandle);
3417 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003418 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
3419 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
3420 if (uid >= 0) {
3421 mLastAllowWhileIdleDispatch.delete(uid);
3422 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003423 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08003424 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
3425 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
3426 // This package is being updated; don't kill its alarms.
3427 return;
3428 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003429 Uri data = intent.getData();
3430 if (data != null) {
3431 String pkg = data.getSchemeSpecificPart();
3432 if (pkg != null) {
3433 pkgList = new String[]{pkg};
3434 }
3435 }
3436 }
3437 if (pkgList != null && (pkgList.length > 0)) {
3438 for (String pkg : pkgList) {
3439 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07003440 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003441 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
3442 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
3443 if (uidStats.remove(pkg) != null) {
3444 if (uidStats.size() <= 0) {
3445 mBroadcastStats.removeAt(i);
3446 }
3447 }
3448 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003449 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003450 }
3451 }
3452 }
3453 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003454
3455 final class UidObserver extends IUidObserver.Stub {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003456 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003457 }
3458
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003459 @Override public void onUidGone(int uid, boolean disabled) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003460 synchronized (mLock) {
3461 if (disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -08003462 removeForStoppedLocked(uid);
3463 }
3464 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003465 }
3466
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003467 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003468 }
3469
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003470 @Override public void onUidIdle(int uid, boolean disabled) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003471 synchronized (mLock) {
3472 if (disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -08003473 removeForStoppedLocked(uid);
3474 }
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08003475 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003476 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003477
3478 @Override public void onUidCachedChanged(int uid, boolean cached) {
3479 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003480 };
3481
Makoto Onuki2206af32017-11-21 16:25:35 -08003482
3483 private final Listener mForceAppStandbyListener = new Listener() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003484 @Override
Makoto Onuki2206af32017-11-21 16:25:35 -08003485 public void unblockAllUnrestrictedAlarms() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003486 synchronized (mLock) {
Makoto Onuki2206af32017-11-21 16:25:35 -08003487 sendAllUnrestrictedPendingBackgroundAlarmsLocked();
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003488 }
3489 }
Makoto Onuki2206af32017-11-21 16:25:35 -08003490
3491 @Override
3492 public void unblockAlarmsForUid(int uid) {
3493 synchronized (mLock) {
3494 sendPendingBackgroundAlarmsLocked(uid, null);
3495 }
3496 }
3497
3498 @Override
3499 public void unblockAlarmsForUidPackage(int uid, String packageName) {
3500 synchronized (mLock) {
3501 sendPendingBackgroundAlarmsLocked(uid, packageName);
3502 }
3503 }
3504 };
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003506 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003507 String pkg = pi.getCreatorPackage();
3508 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003509 return getStatsLocked(uid, pkg);
3510 }
3511
3512 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003513 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
3514 if (uidStats == null) {
3515 uidStats = new ArrayMap<String, BroadcastStats>();
3516 mBroadcastStats.put(uid, uidStats);
3517 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003518 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003519 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003520 bs = new BroadcastStats(uid, pkgName);
3521 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003522 }
3523 return bs;
3524 }
Dianne Hackborn81038902012-11-26 17:04:09 -08003525
Christopher Tate21e9f192017-08-08 13:49:11 -07003526 /**
3527 * Canonical count of (operation.send() - onSendFinished()) and
3528 * listener send/complete/timeout invocations.
3529 * Guarded by the usual lock.
3530 */
3531 @GuardedBy("mLock")
3532 private int mSendCount = 0;
3533 @GuardedBy("mLock")
Christopher Tateeabba732017-08-17 17:12:52 -07003534 private int mSendFinishCount = 0;
3535 @GuardedBy("mLock")
Christopher Tate21e9f192017-08-08 13:49:11 -07003536 private int mListenerCount = 0;
Christopher Tateeabba732017-08-17 17:12:52 -07003537 @GuardedBy("mLock")
3538 private int mListenerFinishCount = 0;
Christopher Tate21e9f192017-08-08 13:49:11 -07003539
Christopher Tate14a7bb02015-10-01 10:24:31 -07003540 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
Christopher Tate21e9f192017-08-08 13:49:11 -07003541
Christopher Tate14a7bb02015-10-01 10:24:31 -07003542 private InFlight removeLocked(PendingIntent pi, Intent intent) {
3543 for (int i = 0; i < mInFlight.size(); i++) {
Christopher Tatedb9ae422017-08-21 11:24:30 -07003544 if (mInFlight.get(i).mPendingIntent == pi) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003545 return mInFlight.remove(i);
3546 }
3547 }
3548 mLog.w("No in-flight alarm for " + pi + " " + intent);
3549 return null;
3550 }
3551
3552 private InFlight removeLocked(IBinder listener) {
3553 for (int i = 0; i < mInFlight.size(); i++) {
3554 if (mInFlight.get(i).mListener == listener) {
3555 return mInFlight.remove(i);
3556 }
3557 }
3558 mLog.w("No in-flight alarm for listener " + listener);
3559 return null;
3560 }
3561
3562 private void updateStatsLocked(InFlight inflight) {
3563 final long nowELAPSED = SystemClock.elapsedRealtime();
3564 BroadcastStats bs = inflight.mBroadcastStats;
3565 bs.nesting--;
3566 if (bs.nesting <= 0) {
3567 bs.nesting = 0;
3568 bs.aggregateTime += nowELAPSED - bs.startTime;
3569 }
3570 FilterStats fs = inflight.mFilterStats;
3571 fs.nesting--;
3572 if (fs.nesting <= 0) {
3573 fs.nesting = 0;
3574 fs.aggregateTime += nowELAPSED - fs.startTime;
3575 }
3576 if (RECORD_ALARMS_IN_HISTORY) {
3577 if (inflight.mWorkSource != null && inflight.mWorkSource.size() > 0) {
3578 for (int wi=0; wi<inflight.mWorkSource.size(); wi++) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003579 ActivityManager.noteAlarmFinish(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003580 inflight.mPendingIntent, inflight.mWorkSource.get(wi), inflight.mTag);
3581 }
3582 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003583 ActivityManager.noteAlarmFinish(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003584 inflight.mPendingIntent, inflight.mUid, inflight.mTag);
3585 }
3586 }
3587 }
3588
3589 private void updateTrackingLocked(InFlight inflight) {
3590 if (inflight != null) {
3591 updateStatsLocked(inflight);
3592 }
3593 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08003594 if (DEBUG_WAKELOCK) {
3595 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
3596 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003597 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003598 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003599 mWakeLock.release();
3600 if (mInFlight.size() > 0) {
3601 mLog.w("Finished all dispatches with " + mInFlight.size()
3602 + " remaining inflights");
3603 for (int i=0; i<mInFlight.size(); i++) {
3604 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
3605 }
3606 mInFlight.clear();
3607 }
3608 } else {
3609 // the next of our alarms is now in flight. reattribute the wakelock.
3610 if (mInFlight.size() > 0) {
3611 InFlight inFlight = mInFlight.get(0);
3612 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
3613 inFlight.mAlarmType, inFlight.mTag, -1, false);
3614 } else {
3615 // should never happen
3616 mLog.w("Alarm wakelock still held but sent queue empty");
3617 mWakeLock.setWorkSource(null);
3618 }
3619 }
3620 }
3621
3622 /**
3623 * Callback that arrives when a direct-call alarm reports that delivery has finished
3624 */
3625 @Override
3626 public void alarmComplete(IBinder who) {
3627 if (who == null) {
Christopher Tate21e9f192017-08-08 13:49:11 -07003628 mLog.w("Invalid alarmComplete: uid=" + Binder.getCallingUid()
Christopher Tate14a7bb02015-10-01 10:24:31 -07003629 + " pid=" + Binder.getCallingPid());
3630 return;
3631 }
3632
3633 final long ident = Binder.clearCallingIdentity();
3634 try {
3635 synchronized (mLock) {
3636 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
3637 InFlight inflight = removeLocked(who);
3638 if (inflight != null) {
3639 if (DEBUG_LISTENER_CALLBACK) {
3640 Slog.i(TAG, "alarmComplete() from " + who);
3641 }
3642 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07003643 mListenerFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003644 } else {
3645 // Delivery timed out, and the timeout handling already took care of
3646 // updating our tracking here, so we needn't do anything further.
3647 if (DEBUG_LISTENER_CALLBACK) {
3648 Slog.i(TAG, "Late alarmComplete() from " + who);
3649 }
3650 }
3651 }
3652 } finally {
3653 Binder.restoreCallingIdentity(ident);
3654 }
3655 }
3656
3657 /**
3658 * Callback that arrives when a PendingIntent alarm has finished delivery
3659 */
3660 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003661 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
3662 String resultData, Bundle resultExtras) {
3663 synchronized (mLock) {
Christopher Tateeabba732017-08-17 17:12:52 -07003664 mSendFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003665 updateTrackingLocked(removeLocked(pi, intent));
3666 }
3667 }
3668
3669 /**
3670 * Timeout of a direct-call alarm delivery
3671 */
3672 public void alarmTimedOut(IBinder who) {
3673 synchronized (mLock) {
3674 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08003675 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003676 // TODO: implement ANR policy for the target
3677 if (DEBUG_LISTENER_CALLBACK) {
3678 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003679 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003680 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07003681 mListenerFinishCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08003682 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003683 if (DEBUG_LISTENER_CALLBACK) {
3684 Slog.i(TAG, "Spurious timeout of listener " + who);
3685 }
Christopher Tate21e9f192017-08-08 13:49:11 -07003686 mLog.w("Spurious timeout of listener " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003687 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003688 }
3689 }
3690
3691 /**
3692 * Deliver an alarm and set up the post-delivery handling appropriately
3693 */
3694 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
3695 if (alarm.operation != null) {
3696 // PendingIntent alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07003697 mSendCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003698 try {
3699 alarm.operation.send(getContext(), 0,
3700 mBackgroundIntent.putExtra(
3701 Intent.EXTRA_ALARM_COUNT, alarm.count),
3702 mDeliveryTracker, mHandler, null,
3703 allowWhileIdle ? mIdleOptions : null);
3704 } catch (PendingIntent.CanceledException e) {
3705 if (alarm.repeatInterval > 0) {
3706 // This IntentSender is no longer valid, but this
3707 // is a repeating alarm, so toss it
3708 removeImpl(alarm.operation);
3709 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003710 // No actual delivery was possible, so the delivery tracker's
3711 // 'finished' callback won't be invoked. We also don't need
3712 // to do any wakelock or stats tracking, so we have nothing
3713 // left to do here but go on to the next thing.
Christopher Tateeabba732017-08-17 17:12:52 -07003714 mSendFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08003715 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003716 }
3717 } else {
3718 // Direct listener callback alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07003719 mListenerCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003720 try {
3721 if (DEBUG_LISTENER_CALLBACK) {
3722 Slog.v(TAG, "Alarm to uid=" + alarm.uid
3723 + " listener=" + alarm.listener.asBinder());
3724 }
3725 alarm.listener.doAlarm(this);
3726 mHandler.sendMessageDelayed(
3727 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
3728 alarm.listener.asBinder()),
3729 mConstants.LISTENER_TIMEOUT);
3730 } catch (Exception e) {
3731 if (DEBUG_LISTENER_CALLBACK) {
3732 Slog.i(TAG, "Alarm undeliverable to listener "
3733 + alarm.listener.asBinder(), e);
3734 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003735 // As in the PendingIntent.CanceledException case, delivery of the
3736 // alarm was not possible, so we have no wakelock or timeout or
3737 // stats management to do. It threw before we posted the delayed
3738 // timeout message, so we're done here.
Christopher Tateeabba732017-08-17 17:12:52 -07003739 mListenerFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08003740 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003741 }
3742 }
3743
3744 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08003745 if (DEBUG_WAKELOCK) {
3746 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
3747 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003748 if (mBroadcastRefCount == 0) {
3749 setWakelockWorkSource(alarm.operation, alarm.workSource,
3750 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
3751 true);
3752 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003753 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003754 }
3755 final InFlight inflight = new InFlight(AlarmManagerService.this,
3756 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
3757 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
3758 mInFlight.add(inflight);
3759 mBroadcastRefCount++;
3760
3761 if (allowWhileIdle) {
3762 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
3763 mLastAllowWhileIdleDispatch.put(alarm.uid, nowELAPSED);
3764 if (RECORD_DEVICE_IDLE_ALARMS) {
3765 IdleDispatchEntry ent = new IdleDispatchEntry();
3766 ent.uid = alarm.uid;
3767 ent.pkg = alarm.packageName;
3768 ent.tag = alarm.statsTag;
3769 ent.op = "DELIVER";
3770 ent.elapsedRealtime = nowELAPSED;
3771 mAllowWhileIdleDispatches.add(ent);
3772 }
3773 }
3774
3775 final BroadcastStats bs = inflight.mBroadcastStats;
3776 bs.count++;
3777 if (bs.nesting == 0) {
3778 bs.nesting = 1;
3779 bs.startTime = nowELAPSED;
3780 } else {
3781 bs.nesting++;
3782 }
3783 final FilterStats fs = inflight.mFilterStats;
3784 fs.count++;
3785 if (fs.nesting == 0) {
3786 fs.nesting = 1;
3787 fs.startTime = nowELAPSED;
3788 } else {
3789 fs.nesting++;
3790 }
3791 if (alarm.type == ELAPSED_REALTIME_WAKEUP
3792 || alarm.type == RTC_WAKEUP) {
3793 bs.numWakeup++;
3794 fs.numWakeup++;
3795 if (alarm.workSource != null && alarm.workSource.size() > 0) {
3796 for (int wi=0; wi<alarm.workSource.size(); wi++) {
Christopher Tate0029f572016-06-14 10:16:28 -07003797 final String wsName = alarm.workSource.getName(wi);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003798 ActivityManager.noteWakeupAlarm(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003799 alarm.operation, alarm.workSource.get(wi),
Christopher Tate0029f572016-06-14 10:16:28 -07003800 (wsName != null) ? wsName : alarm.packageName,
3801 alarm.statsTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08003802 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003803 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003804 ActivityManager.noteWakeupAlarm(
Joe Onorato78bcdf92016-05-09 10:10:29 -07003805 alarm.operation, alarm.uid, alarm.packageName, alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003806 }
3807 }
3808 }
3809 }
3810}