blob: 4330f5d892c70bb31f650a5b23ee06973683abc7 [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;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070051import android.os.UserHandle;
Christopher Tatec4a07d12012-04-06 14:19:13 -070052import android.os.WorkSource;
Adrian Roosc42a1e12014-07-07 23:35:53 +020053import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.text.TextUtils;
Adrian Roosc42a1e12014-07-07 23:35:53 +020055import android.text.format.DateFormat;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080056import android.util.ArrayMap;
Dianne Hackborna750a632015-06-16 17:18:23 -070057import android.util.KeyValueListParser;
Adrian Roosc42a1e12014-07-07 23:35:53 +020058import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080059import android.util.Slog;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080060import android.util.SparseArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +020061import android.util.SparseBooleanArray;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -070062import android.util.SparseLongArray;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070063import android.util.TimeUtils;
Kweku Adams61e03292017-10-19 14:27:12 -070064import android.util.proto.ProtoOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065
Christopher Tate4cb338d2013-07-26 13:11:31 -070066import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import java.io.FileDescriptor;
68import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070069import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -080071import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import java.util.Calendar;
73import java.util.Collections;
74import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -050075import java.util.Date;
Christopher Tate1590f1e2014-10-02 17:27:57 -070076import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -070077import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +020078import java.util.Locale;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070079import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import java.util.TimeZone;
John Spurlock604a5ee2015-06-01 12:27:22 -040081import java.util.TreeSet;
Makoto Onuki2206af32017-11-21 16:25:35 -080082import java.util.function.Predicate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083
Christopher Tatee0a22b32013-07-11 14:43:13 -070084import static android.app.AlarmManager.RTC_WAKEUP;
85import static android.app.AlarmManager.RTC;
86import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
87import static android.app.AlarmManager.ELAPSED_REALTIME;
88
Christopher Tate21e9f192017-08-08 13:49:11 -070089import com.android.internal.annotations.GuardedBy;
Makoto Onuki2206af32017-11-21 16:25:35 -080090import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060091import com.android.internal.util.DumpUtils;
Dianne Hackborn81038902012-11-26 17:04:09 -080092import com.android.internal.util.LocalLog;
Makoto Onuki2206af32017-11-21 16:25:35 -080093import com.android.server.ForceAppStandbyTracker.Listener;
Dianne Hackborn81038902012-11-26 17:04:09 -080094
Makoto Onuki2206af32017-11-21 16:25:35 -080095/**
96 * Alarm manager implementaion.
97 *
98 * Unit test:
99 atest $ANDROID_BUILD_TOP/frameworks/base/services/tests/servicestests/src/com/android/server/AlarmManagerServiceTest.java
100 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800101class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700102 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
103 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800104 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700105 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800106 static final int TIME_CHANGED_MASK = 1 << 16;
107 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -0800108
Christopher Tatee0a22b32013-07-11 14:43:13 -0700109 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -0800110 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -0800111
Adam Lesinski182f73f2013-12-05 16:48:06 -0800112 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -0800113 static final boolean localLOGV = false;
114 static final boolean DEBUG_BATCH = localLOGV || false;
115 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200116 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700117 static final boolean DEBUG_LISTENER_CALLBACK = localLOGV || false;
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800118 static final boolean DEBUG_WAKELOCK = localLOGV || false;
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700119 static final boolean DEBUG_BG_LIMIT = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700120 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700121 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800122 static final int ALARM_EVENT = 1;
123 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200124
Christopher Tate14a7bb02015-10-01 10:24:31 -0700125 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800127 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700128
Adam Lesinski182f73f2013-12-05 16:48:06 -0800129 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700130
Christopher Tate24cd46f2016-02-02 14:28:01 -0800131 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT =
132 new Intent(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED)
Christopher Tate50191db2017-05-09 16:02:25 -0700133 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
134 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Adrian Roosc42a1e12014-07-07 23:35:53 +0200135
Adam Lesinski182f73f2013-12-05 16:48:06 -0800136 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800137
Christopher Tate14a7bb02015-10-01 10:24:31 -0700138 AppOpsManager mAppOps;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800139 DeviceIdleController.LocalService mLocalDeviceIdleController;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700140
Adam Lesinski182f73f2013-12-05 16:48:06 -0800141 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800142
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700143 // List of alarms per uid deferred due to user applied background restrictions on the source app
144 SparseArray<ArrayList<Alarm>> mPendingBackgroundAlarms = new SparseArray<>();
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800145 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800146 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700147 private long mNextNonWakeup;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -0700148 private long mLastWakeupSet;
149 private long mLastWakeup;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800150 int mBroadcastRefCount = 0;
151 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700152 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700153 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
154 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800155 final AlarmHandler mHandler = new AlarmHandler();
156 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700157 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700159 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800160 PendingIntent mTimeTickSender;
161 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700162 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700163 boolean mInteractive = true;
164 long mNonInteractiveStartTime;
165 long mNonInteractiveTime;
166 long mLastAlarmDeliveryTime;
167 long mStartCurrentDelayTime;
168 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700169 long mLastTimeChangeClockTime;
170 long mLastTimeChangeRealtime;
Dianne Hackborna750a632015-06-16 17:18:23 -0700171 long mAllowWhileIdleMinTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700172 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800173
Christopher Tatebb9cce52017-04-18 14:19:43 -0700174 // Bookkeeping about the identity of the "System UI" package, determined at runtime.
175
176 /**
177 * This permission must be defined by the canonical System UI package,
178 * with protection level "signature".
179 */
180 private static final String SYSTEM_UI_SELF_PERMISSION =
181 "android.permission.systemui.IDENTITY";
182
183 /**
184 * At boot we use SYSTEM_UI_SELF_PERMISSION to look up the definer's uid.
185 */
186 int mSystemUiUid;
187
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700188 /**
189 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
Kweku Adams61e03292017-10-19 14:27:12 -0700190 * used to determine the earliest we can dispatch the next such alarm. Times are in the
191 * 'elapsed' timebase.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700192 */
193 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
194
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700195 final static class IdleDispatchEntry {
196 int uid;
197 String pkg;
198 String tag;
199 String op;
200 long elapsedRealtime;
201 long argRealtime;
202 }
203 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
204
Dianne Hackborna750a632015-06-16 17:18:23 -0700205 /**
206 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
207 */
208 Bundle mIdleOptions;
209
Jose Lima235510e2014-08-13 12:50:01 -0700210 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
211 new SparseArray<>();
212 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
213 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200214 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
215 new SparseBooleanArray();
216 private boolean mNextAlarmClockMayChange;
217
218 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700219 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
220 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200221
Makoto Onuki2206af32017-11-21 16:25:35 -0800222 private final ForceAppStandbyTracker mForceAppStandbyTracker;
223
Dianne Hackborna750a632015-06-16 17:18:23 -0700224 /**
225 * All times are in milliseconds. These constants are kept synchronized with the system
226 * global Settings. Any access to this class or its fields should be done while
227 * holding the AlarmManagerService.mLock lock.
228 */
229 private final class Constants extends ContentObserver {
230 // Key names stored in the settings value.
231 private static final String KEY_MIN_FUTURITY = "min_futurity";
232 private static final String KEY_MIN_INTERVAL = "min_interval";
233 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
234 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
235 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
236 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700237 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700238 private static final String KEY_BG_RESTRICTIONS_ENABLED = "limit_bg_alarms_enabled";
Dianne Hackborna750a632015-06-16 17:18:23 -0700239
240 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
241 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tateaa244da2015-08-27 15:57:57 -0700242 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700243 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700244 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
245
Christopher Tate14a7bb02015-10-01 10:24:31 -0700246 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
247
Dianne Hackborna750a632015-06-16 17:18:23 -0700248 // Minimum futurity of a new alarm
249 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
250
251 // Minimum alarm recurrence interval
252 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
253
254 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
255 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
256
257 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
258 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
259
260 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
261 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
262 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
263
Christopher Tate14a7bb02015-10-01 10:24:31 -0700264 // Direct alarm listener callback timeout
265 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
266
Dianne Hackborna750a632015-06-16 17:18:23 -0700267 private ContentResolver mResolver;
268 private final KeyValueListParser mParser = new KeyValueListParser(',');
269 private long mLastAllowWhileIdleWhitelistDuration = -1;
270
271 public Constants(Handler handler) {
272 super(handler);
273 updateAllowWhileIdleMinTimeLocked();
274 updateAllowWhileIdleWhitelistDurationLocked();
275 }
276
277 public void start(ContentResolver resolver) {
278 mResolver = resolver;
279 mResolver.registerContentObserver(Settings.Global.getUriFor(
280 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
281 updateConstants();
282 }
283
284 public void updateAllowWhileIdleMinTimeLocked() {
285 mAllowWhileIdleMinTime = mPendingIdleUntil != null
286 ? ALLOW_WHILE_IDLE_LONG_TIME : ALLOW_WHILE_IDLE_SHORT_TIME;
287 }
288
289 public void updateAllowWhileIdleWhitelistDurationLocked() {
290 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
291 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
292 BroadcastOptions opts = BroadcastOptions.makeBasic();
293 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
294 mIdleOptions = opts.toBundle();
295 }
296 }
297
298 @Override
299 public void onChange(boolean selfChange, Uri uri) {
300 updateConstants();
301 }
302
303 private void updateConstants() {
304 synchronized (mLock) {
305 try {
306 mParser.setString(Settings.Global.getString(mResolver,
307 Settings.Global.ALARM_MANAGER_CONSTANTS));
308 } catch (IllegalArgumentException e) {
309 // Failed to parse the settings string, log this and move on
310 // with defaults.
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800311 Slog.e(TAG, "Bad alarm manager settings", e);
Dianne Hackborna750a632015-06-16 17:18:23 -0700312 }
313
314 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
315 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
316 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
317 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
318 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
319 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
320 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
321 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
322 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700323 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
324 DEFAULT_LISTENER_TIMEOUT);
Dianne Hackborna750a632015-06-16 17:18:23 -0700325
326 updateAllowWhileIdleMinTimeLocked();
327 updateAllowWhileIdleWhitelistDurationLocked();
328 }
329 }
330
331 void dump(PrintWriter pw) {
332 pw.println(" Settings:");
333
334 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
335 TimeUtils.formatDuration(MIN_FUTURITY, pw);
336 pw.println();
337
338 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
339 TimeUtils.formatDuration(MIN_INTERVAL, pw);
340 pw.println();
341
Christopher Tate14a7bb02015-10-01 10:24:31 -0700342 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
343 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
344 pw.println();
345
Dianne Hackborna750a632015-06-16 17:18:23 -0700346 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
347 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
348 pw.println();
349
350 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
351 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
352 pw.println();
353
354 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
355 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
356 pw.println();
357 }
Kweku Adams61e03292017-10-19 14:27:12 -0700358
359 void dumpProto(ProtoOutputStream proto, long fieldId) {
360 final long token = proto.start(fieldId);
361
362 proto.write(ConstantsProto.MIN_FUTURITY_DURATION_MS, MIN_FUTURITY);
363 proto.write(ConstantsProto.MIN_INTERVAL_DURATION_MS, MIN_INTERVAL);
364 proto.write(ConstantsProto.LISTENER_TIMEOUT_DURATION_MS, LISTENER_TIMEOUT);
365 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_SHORT_DURATION_MS,
366 ALLOW_WHILE_IDLE_SHORT_TIME);
367 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_LONG_DURATION_MS,
368 ALLOW_WHILE_IDLE_LONG_TIME);
369 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_WHITELIST_DURATION_MS,
370 ALLOW_WHILE_IDLE_WHITELIST_DURATION);
371
372 proto.end(token);
373 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700374 }
375
376 final Constants mConstants;
377
Christopher Tate1590f1e2014-10-02 17:27:57 -0700378 // Alarm delivery ordering bookkeeping
379 static final int PRIO_TICK = 0;
380 static final int PRIO_WAKEUP = 1;
381 static final int PRIO_NORMAL = 2;
382
Dianne Hackborna750a632015-06-16 17:18:23 -0700383 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700384 int seq;
385 int priority;
386
387 PriorityClass() {
388 seq = mCurrentSeq - 1;
389 priority = PRIO_NORMAL;
390 }
391 }
392
Dianne Hackborna750a632015-06-16 17:18:23 -0700393 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700394 int mCurrentSeq = 0;
395
Dianne Hackborna750a632015-06-16 17:18:23 -0700396 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700397 public long when;
398 public int uid;
399 public String action;
400
401 public WakeupEvent(long theTime, int theUid, String theAction) {
402 when = theTime;
403 uid = theUid;
404 action = theAction;
405 }
406 }
407
Adam Lesinski182f73f2013-12-05 16:48:06 -0800408 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
409 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700410
Adrian Roosc42a1e12014-07-07 23:35:53 +0200411 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700412 long start; // These endpoints are always in ELAPSED
413 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700414 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700415
416 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
417
418 Batch() {
419 start = 0;
420 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700421 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700422 }
423
424 Batch(Alarm seed) {
425 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700426 end = seed.maxWhenElapsed;
427 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700428 alarms.add(seed);
429 }
430
431 int size() {
432 return alarms.size();
433 }
434
435 Alarm get(int index) {
436 return alarms.get(index);
437 }
438
439 boolean canHold(long whenElapsed, long maxWhen) {
440 return (end >= whenElapsed) && (start <= maxWhen);
441 }
442
443 boolean add(Alarm alarm) {
444 boolean newStart = false;
445 // narrows the batch if necessary; presumes that canHold(alarm) is true
446 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
447 if (index < 0) {
448 index = 0 - index - 1;
449 }
450 alarms.add(index, alarm);
451 if (DEBUG_BATCH) {
452 Slog.v(TAG, "Adding " + alarm + " to " + this);
453 }
454 if (alarm.whenElapsed > start) {
455 start = alarm.whenElapsed;
456 newStart = true;
457 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700458 if (alarm.maxWhenElapsed < end) {
459 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700460 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700461 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700462
463 if (DEBUG_BATCH) {
464 Slog.v(TAG, " => now " + this);
465 }
466 return newStart;
467 }
468
Christopher Tate14a7bb02015-10-01 10:24:31 -0700469 boolean remove(final PendingIntent operation, final IAlarmListener listener) {
470 if (operation == null && listener == null) {
471 if (localLOGV) {
472 Slog.w(TAG, "requested remove() of null operation",
473 new RuntimeException("here"));
474 }
475 return false;
476 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700477 boolean didRemove = false;
478 long newStart = 0; // recalculate endpoints as we go
479 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700480 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700481 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700482 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700483 if (alarm.matches(operation, listener)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700484 alarms.remove(i);
485 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200486 if (alarm.alarmClock != null) {
487 mNextAlarmClockMayChange = true;
488 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700489 } else {
490 if (alarm.whenElapsed > newStart) {
491 newStart = alarm.whenElapsed;
492 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700493 if (alarm.maxWhenElapsed < newEnd) {
494 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700495 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700496 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700497 i++;
498 }
499 }
500 if (didRemove) {
501 // commit the new batch bounds
502 start = newStart;
503 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700504 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700505 }
506 return didRemove;
507 }
508
509 boolean remove(final String packageName) {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700510 if (packageName == null) {
511 if (localLOGV) {
512 Slog.w(TAG, "requested remove() of null packageName",
513 new RuntimeException("here"));
514 }
515 return false;
516 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700517 boolean didRemove = false;
518 long newStart = 0; // recalculate endpoints as we go
519 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700520 int newFlags = 0;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700521 for (int i = alarms.size()-1; i >= 0; i--) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700522 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700523 if (alarm.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700524 alarms.remove(i);
525 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200526 if (alarm.alarmClock != null) {
527 mNextAlarmClockMayChange = true;
528 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700529 } else {
530 if (alarm.whenElapsed > newStart) {
531 newStart = alarm.whenElapsed;
532 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700533 if (alarm.maxWhenElapsed < newEnd) {
534 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700535 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700536 newFlags |= alarm.flags;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700537 }
538 }
539 if (didRemove) {
540 // commit the new batch bounds
541 start = newStart;
542 end = newEnd;
543 flags = newFlags;
544 }
545 return didRemove;
546 }
547
548 boolean removeForStopped(final int uid) {
549 boolean didRemove = false;
550 long newStart = 0; // recalculate endpoints as we go
551 long newEnd = Long.MAX_VALUE;
552 int newFlags = 0;
553 for (int i = alarms.size()-1; i >= 0; i--) {
554 Alarm alarm = alarms.get(i);
555 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800556 if (alarm.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
557 uid, alarm.packageName)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700558 alarms.remove(i);
559 didRemove = true;
560 if (alarm.alarmClock != null) {
561 mNextAlarmClockMayChange = true;
562 }
563 } else {
564 if (alarm.whenElapsed > newStart) {
565 newStart = alarm.whenElapsed;
566 }
567 if (alarm.maxWhenElapsed < newEnd) {
568 newEnd = alarm.maxWhenElapsed;
569 }
570 newFlags |= alarm.flags;
571 }
572 } catch (RemoteException e) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700573 }
574 }
575 if (didRemove) {
576 // commit the new batch bounds
577 start = newStart;
578 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700579 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700580 }
581 return didRemove;
582 }
583
584 boolean remove(final int userHandle) {
585 boolean didRemove = false;
586 long newStart = 0; // recalculate endpoints as we go
587 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700588 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700589 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700590 if (UserHandle.getUserId(alarm.creatorUid) == userHandle) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700591 alarms.remove(i);
592 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200593 if (alarm.alarmClock != null) {
594 mNextAlarmClockMayChange = true;
595 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700596 } else {
597 if (alarm.whenElapsed > newStart) {
598 newStart = alarm.whenElapsed;
599 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700600 if (alarm.maxWhenElapsed < newEnd) {
601 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700602 }
603 i++;
604 }
605 }
606 if (didRemove) {
607 // commit the new batch bounds
608 start = newStart;
609 end = newEnd;
610 }
611 return didRemove;
612 }
613
614 boolean hasPackage(final String packageName) {
615 final int N = alarms.size();
616 for (int i = 0; i < N; i++) {
617 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700618 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700619 return true;
620 }
621 }
622 return false;
623 }
624
625 boolean hasWakeups() {
626 final int N = alarms.size();
627 for (int i = 0; i < N; i++) {
628 Alarm a = alarms.get(i);
629 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
630 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
631 return true;
632 }
633 }
634 return false;
635 }
636
637 @Override
638 public String toString() {
639 StringBuilder b = new StringBuilder(40);
640 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
641 b.append(" num="); b.append(size());
642 b.append(" start="); b.append(start);
643 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700644 if (flags != 0) {
645 b.append(" flgs=0x");
646 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700647 }
648 b.append('}');
649 return b.toString();
650 }
Kweku Adams61e03292017-10-19 14:27:12 -0700651
652 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
653 long nowRTC) {
654 final long token = proto.start(fieldId);
655
656 proto.write(BatchProto.START_REALTIME, start);
657 proto.write(BatchProto.END_REALTIME, end);
658 proto.write(BatchProto.FLAGS, flags);
659 for (Alarm a : alarms) {
660 a.writeToProto(proto, BatchProto.ALARMS, nowElapsed, nowRTC);
661 }
662
663 proto.end(token);
664 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700665 }
666
667 static class BatchTimeOrder implements Comparator<Batch> {
668 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800669 long when1 = b1.start;
670 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800671 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700672 return 1;
673 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800674 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700675 return -1;
676 }
677 return 0;
678 }
679 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800680
681 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
682 @Override
683 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700684 // priority class trumps everything. TICK < WAKEUP < NORMAL
685 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
686 return -1;
687 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
688 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800689 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700690
691 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800692 if (lhs.whenElapsed < rhs.whenElapsed) {
693 return -1;
694 } else if (lhs.whenElapsed > rhs.whenElapsed) {
695 return 1;
696 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700697
698 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800699 return 0;
700 }
701 };
702
Christopher Tate1590f1e2014-10-02 17:27:57 -0700703 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
704 final int N = alarms.size();
705 for (int i = 0; i < N; i++) {
706 Alarm a = alarms.get(i);
707
708 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700709 if (a.operation != null
710 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700711 alarmPrio = PRIO_TICK;
712 } else if (a.wakeup) {
713 alarmPrio = PRIO_WAKEUP;
714 } else {
715 alarmPrio = PRIO_NORMAL;
716 }
717
718 PriorityClass packagePrio = a.priorityClass;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700719 String alarmPackage = (a.operation != null)
720 ? a.operation.getCreatorPackage()
721 : a.packageName;
722 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700723 if (packagePrio == null) {
724 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700725 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700726 }
727 a.priorityClass = packagePrio;
728
729 if (packagePrio.seq != mCurrentSeq) {
730 // first alarm we've seen in the current delivery generation from this package
731 packagePrio.priority = alarmPrio;
732 packagePrio.seq = mCurrentSeq;
733 } else {
734 // Multiple alarms from this package being delivered in this generation;
735 // bump the package's delivery class if it's warranted.
736 // TICK < WAKEUP < NORMAL
737 if (alarmPrio < packagePrio.priority) {
738 packagePrio.priority = alarmPrio;
739 }
740 }
741 }
742 }
743
Christopher Tatee0a22b32013-07-11 14:43:13 -0700744 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800745 static final long MIN_FUZZABLE_INTERVAL = 10000;
746 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700747 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
748
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700749 // 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 -0700750 // to run during this time are placed in mPendingWhileIdleAlarms
751 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700752 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700753 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700754
Jeff Brownb880d882014-02-10 19:47:07 -0800755 public AlarmManagerService(Context context) {
756 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700757 mConstants = new Constants(mHandler);
Makoto Onuki2206af32017-11-21 16:25:35 -0800758
759 mForceAppStandbyTracker = ForceAppStandbyTracker.getInstance(context);
760 mForceAppStandbyTracker.addListener(mForceAppStandbyListener);
Jeff Brownb880d882014-02-10 19:47:07 -0800761 }
762
Christopher Tatee0a22b32013-07-11 14:43:13 -0700763 static long convertToElapsed(long when, int type) {
764 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
765 if (isRtc) {
766 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
767 }
768 return when;
769 }
770
771 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
772 // calculate the end of our nominal delivery window for the alarm.
773 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
774 // Current heuristic: batchable window is 75% of either the recurrence interval
775 // [for a periodic alarm] or of the time from now to the desired delivery time,
776 // with a minimum delay/interval of 10 seconds, under which we will simply not
777 // defer the alarm.
778 long futurity = (interval == 0)
779 ? (triggerAtTime - now)
780 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700781 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700782 futurity = 0;
783 }
784 return triggerAtTime + (long)(.75 * futurity);
785 }
786
787 // returns true if the batch was added at the head
788 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
789 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
790 if (index < 0) {
791 index = 0 - index - 1;
792 }
793 list.add(index, newBatch);
794 return (index == 0);
795 }
796
Christopher Tate385e4982013-07-23 18:22:29 -0700797 // Return the index of the matching batch, or -1 if none found.
798 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700799 final int N = mAlarmBatches.size();
800 for (int i = 0; i < N; i++) {
801 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700802 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700803 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700804 }
805 }
Christopher Tate385e4982013-07-23 18:22:29 -0700806 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700807 }
808
809 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
810 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700811 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700812 rebatchAllAlarmsLocked(true);
813 }
814 }
815
816 void rebatchAllAlarmsLocked(boolean doValidate) {
817 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
818 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700819 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700820 final long nowElapsed = SystemClock.elapsedRealtime();
821 final int oldBatches = oldSet.size();
822 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
823 Batch batch = oldSet.get(batchNum);
824 final int N = batch.size();
825 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700826 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700827 }
828 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700829 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
830 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
831 + " to " + mPendingIdleUntil);
832 if (mPendingIdleUntil == null) {
833 // Somehow we lost this... we need to restore all of the pending alarms.
834 restorePendingWhileIdleAlarmsLocked();
835 }
836 }
837 rescheduleKernelAlarmsLocked();
838 updateNextAlarmClockLocked();
839 }
840
841 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
842 a.when = a.origWhen;
843 long whenElapsed = convertToElapsed(a.when, a.type);
844 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700845 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700846 // Exact
847 maxElapsed = whenElapsed;
848 } else {
849 // Not exact. Preserve any explicit window, otherwise recalculate
850 // the window based on the alarm's new futurity. Note that this
851 // reflects a policy of preferring timely to deferred delivery.
852 maxElapsed = (a.windowLength > 0)
853 ? (whenElapsed + a.windowLength)
854 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
855 }
856 a.whenElapsed = whenElapsed;
857 a.maxWhenElapsed = maxElapsed;
858 setImplLocked(a, true, doValidate);
859 }
860
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700861 /**
862 * Sends alarms that were blocked due to user applied background restrictions - either because
863 * the user lifted those or the uid came to foreground.
864 *
865 * @param uid uid to filter on
866 * @param packageName package to filter on, or null for all packages in uid
867 */
868 void sendPendingBackgroundAlarmsLocked(int uid, String packageName) {
869 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(uid);
870 if (alarmsForUid == null || alarmsForUid.size() == 0) {
871 return;
872 }
873 final ArrayList<Alarm> alarmsToDeliver;
874 if (packageName != null) {
875 if (DEBUG_BG_LIMIT) {
876 Slog.d(TAG, "Sending blocked alarms for uid " + uid + ", package " + packageName);
877 }
878 alarmsToDeliver = new ArrayList<>();
879 for (int i = alarmsForUid.size() - 1; i >= 0; i--) {
880 final Alarm a = alarmsForUid.get(i);
881 if (a.matches(packageName)) {
882 alarmsToDeliver.add(alarmsForUid.remove(i));
883 }
884 }
885 if (alarmsForUid.size() == 0) {
886 mPendingBackgroundAlarms.remove(uid);
887 }
888 } else {
889 if (DEBUG_BG_LIMIT) {
890 Slog.d(TAG, "Sending blocked alarms for uid " + uid);
891 }
892 alarmsToDeliver = alarmsForUid;
893 mPendingBackgroundAlarms.remove(uid);
894 }
895 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
896 }
897
Makoto Onuki2206af32017-11-21 16:25:35 -0800898 /**
899 * Check all alarms in {@link #mPendingBackgroundAlarms} and send the ones that are not
900 * restricted.
901 *
902 * This is only called when the global "force all apps-standby" flag changes or when the
903 * power save whitelist changes, so it's okay to be slow.
904 */
905 void sendAllUnrestrictedPendingBackgroundAlarmsLocked() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700906 final ArrayList<Alarm> alarmsToDeliver = new ArrayList<>();
Makoto Onuki2206af32017-11-21 16:25:35 -0800907
908 findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
909 mPendingBackgroundAlarms, alarmsToDeliver, this::isBackgroundRestricted);
910
911 if (alarmsToDeliver.size() > 0) {
912 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
913 }
914 }
915
916 @VisibleForTesting
917 static void findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
918 SparseArray<ArrayList<Alarm>> pendingAlarms, ArrayList<Alarm> unrestrictedAlarms,
919 Predicate<Alarm> isBackgroundRestricted) {
920
921 for (int uidIndex = pendingAlarms.size() - 1; uidIndex >= 0; uidIndex--) {
922 final int uid = pendingAlarms.keyAt(uidIndex);
923 final ArrayList<Alarm> alarmsForUid = pendingAlarms.valueAt(uidIndex);
924
925 for (int alarmIndex = alarmsForUid.size() - 1; alarmIndex >= 0; alarmIndex--) {
926 final Alarm alarm = alarmsForUid.get(alarmIndex);
927
928 if (isBackgroundRestricted.test(alarm)) {
929 continue;
930 }
931
932 unrestrictedAlarms.add(alarm);
933 alarmsForUid.remove(alarmIndex);
934 }
935
936 if (alarmsForUid.size() == 0) {
937 pendingAlarms.removeAt(uidIndex);
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700938 }
939 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700940 }
941
942 private void deliverPendingBackgroundAlarmsLocked(ArrayList<Alarm> alarms, long nowELAPSED) {
943 final int N = alarms.size();
944 boolean hasWakeup = false;
945 for (int i = 0; i < N; i++) {
946 final Alarm alarm = alarms.get(i);
947 if (alarm.wakeup) {
948 hasWakeup = true;
949 }
950 alarm.count = 1;
951 // Recurring alarms may have passed several alarm intervals while the
952 // alarm was kept pending. Send the appropriate trigger count.
953 if (alarm.repeatInterval > 0) {
954 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
955 // Also schedule its next recurrence
956 final long delta = alarm.count * alarm.repeatInterval;
957 final long nextElapsed = alarm.whenElapsed + delta;
958 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
959 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
960 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
961 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
962 // Kernel alarms will be rescheduled as needed in setImplLocked
963 }
964 }
965 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
966 // No need to wakeup for non wakeup alarms
967 if (mPendingNonWakeupAlarms.size() == 0) {
968 mStartCurrentDelayTime = nowELAPSED;
969 mNextNonWakeupDeliveryTime = nowELAPSED
970 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
971 }
972 mPendingNonWakeupAlarms.addAll(alarms);
973 mNumDelayedAlarms += alarms.size();
974 } else {
975 if (DEBUG_BG_LIMIT) {
976 Slog.d(TAG, "Waking up to deliver pending blocked alarms");
977 }
978 // Since we are waking up, also deliver any pending non wakeup alarms we have.
979 if (mPendingNonWakeupAlarms.size() > 0) {
980 alarms.addAll(mPendingNonWakeupAlarms);
981 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
982 mTotalDelayTime += thisDelayTime;
983 if (mMaxDelayTime < thisDelayTime) {
984 mMaxDelayTime = thisDelayTime;
985 }
986 mPendingNonWakeupAlarms.clear();
987 }
988 calculateDeliveryPriorities(alarms);
989 Collections.sort(alarms, mAlarmDispatchComparator);
990 deliverAlarmsLocked(alarms, nowELAPSED);
991 }
992 }
993
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700994 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700995 if (RECORD_DEVICE_IDLE_ALARMS) {
996 IdleDispatchEntry ent = new IdleDispatchEntry();
997 ent.uid = 0;
998 ent.pkg = "FINISH IDLE";
999 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1000 mAllowWhileIdleDispatches.add(ent);
1001 }
1002
Dianne Hackborn35d54032015-04-23 10:30:43 -07001003 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001004 if (mPendingWhileIdleAlarms.size() > 0) {
1005 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
1006 mPendingWhileIdleAlarms = new ArrayList<>();
1007 final long nowElapsed = SystemClock.elapsedRealtime();
1008 for (int i=alarms.size() - 1; i >= 0; i--) {
1009 Alarm a = alarms.get(i);
1010 reAddAlarmLocked(a, nowElapsed, false);
1011 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001012 }
Dianne Hackborn35d54032015-04-23 10:30:43 -07001013
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001014 // Make sure we are using the correct ALLOW_WHILE_IDLE min time.
Dianne Hackborna750a632015-06-16 17:18:23 -07001015 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001016
Dianne Hackborn35d54032015-04-23 10:30:43 -07001017 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001018 rescheduleKernelAlarmsLocked();
1019 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -07001020
1021 // And send a TIME_TICK right now, since it is important to get the UI updated.
1022 try {
1023 mTimeTickSender.send();
1024 } catch (PendingIntent.CanceledException e) {
1025 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001026 }
1027
Christopher Tate14a7bb02015-10-01 10:24:31 -07001028 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -08001029 final PendingIntent mPendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001030 final long mWhenElapsed;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001031 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -07001032 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001033 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001034 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001035 final BroadcastStats mBroadcastStats;
1036 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001037 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001038
Christopher Tate14a7bb02015-10-01 10:24:31 -07001039 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
1040 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
1041 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001042 mPendingIntent = pendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001043 mWhenElapsed = nowELAPSED;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001044 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -07001045 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001046 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001047 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001048 mBroadcastStats = (pendingIntent != null)
1049 ? service.getStatsLocked(pendingIntent)
1050 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001051 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001052 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001053 fs = new FilterStats(mBroadcastStats, mTag);
1054 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -08001055 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001056 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -08001057 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001058 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001059 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001060
1061 @Override
1062 public String toString() {
1063 return "InFlight{"
1064 + "pendingIntent=" + mPendingIntent
Christopher Tateeabba732017-08-17 17:12:52 -07001065 + ", when=" + mWhenElapsed
Makoto Onuki33955e12017-03-01 18:11:00 -08001066 + ", workSource=" + mWorkSource
1067 + ", uid=" + mUid
1068 + ", tag=" + mTag
1069 + ", broadcastStats=" + mBroadcastStats
1070 + ", filterStats=" + mFilterStats
1071 + ", alarmType=" + mAlarmType
1072 + "}";
1073 }
Kweku Adams61e03292017-10-19 14:27:12 -07001074
1075 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1076 final long token = proto.start(fieldId);
1077
1078 proto.write(InFlightProto.UID, mUid);
1079 proto.write(InFlightProto.TAG, mTag);
1080 proto.write(InFlightProto.WHEN_ELAPSED_MS, mWhenElapsed);
1081 proto.write(InFlightProto.ALARM_TYPE, mAlarmType);
1082 if (mPendingIntent != null) {
1083 mPendingIntent.writeToProto(proto, InFlightProto.PENDING_INTENT);
1084 }
1085 if (mBroadcastStats != null) {
1086 mBroadcastStats.writeToProto(proto, InFlightProto.BROADCAST_STATS);
1087 }
1088 if (mFilterStats != null) {
1089 mFilterStats.writeToProto(proto, InFlightProto.FILTER_STATS);
1090 }
1091 if (mWorkSource != null) {
1092 mWorkSource.writeToProto(proto, InFlightProto.WORK_SOURCE);
1093 }
1094
1095 proto.end(token);
1096 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001098
Adam Lesinski182f73f2013-12-05 16:48:06 -08001099 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -08001100 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001101 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001102
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001103 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -08001105 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 int numWakeup;
1107 long startTime;
1108 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -08001109
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001110 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001111 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001112 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001113 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001114
1115 @Override
1116 public String toString() {
1117 return "FilterStats{"
1118 + "tag=" + mTag
1119 + ", lastTime=" + lastTime
1120 + ", aggregateTime=" + aggregateTime
1121 + ", count=" + count
1122 + ", numWakeup=" + numWakeup
1123 + ", startTime=" + startTime
1124 + ", nesting=" + nesting
1125 + "}";
1126 }
Kweku Adams61e03292017-10-19 14:27:12 -07001127
1128 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1129 final long token = proto.start(fieldId);
1130
1131 proto.write(FilterStatsProto.TAG, mTag);
1132 proto.write(FilterStatsProto.LAST_FLIGHT_TIME_REALTIME, lastTime);
1133 proto.write(FilterStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1134 proto.write(FilterStatsProto.COUNT, count);
1135 proto.write(FilterStatsProto.WAKEUP_COUNT, numWakeup);
1136 proto.write(FilterStatsProto.START_TIME_REALTIME, startTime);
1137 proto.write(FilterStatsProto.NESTING, nesting);
1138
1139 proto.end(token);
1140 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001141 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001142
Adam Lesinski182f73f2013-12-05 16:48:06 -08001143 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001144 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001145 final String mPackageName;
1146
1147 long aggregateTime;
1148 int count;
1149 int numWakeup;
1150 long startTime;
1151 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001152 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -08001153
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001154 BroadcastStats(int uid, String packageName) {
1155 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001156 mPackageName = packageName;
1157 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001158
1159 @Override
1160 public String toString() {
1161 return "BroadcastStats{"
1162 + "uid=" + mUid
1163 + ", packageName=" + mPackageName
1164 + ", aggregateTime=" + aggregateTime
1165 + ", count=" + count
1166 + ", numWakeup=" + numWakeup
1167 + ", startTime=" + startTime
1168 + ", nesting=" + nesting
1169 + "}";
1170 }
Kweku Adams61e03292017-10-19 14:27:12 -07001171
1172 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1173 final long token = proto.start(fieldId);
1174
1175 proto.write(BroadcastStatsProto.UID, mUid);
1176 proto.write(BroadcastStatsProto.PACKAGE_NAME, mPackageName);
1177 proto.write(BroadcastStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1178 proto.write(BroadcastStatsProto.COUNT, count);
1179 proto.write(BroadcastStatsProto.WAKEUP_COUNT, numWakeup);
1180 proto.write(BroadcastStatsProto.START_TIME_REALTIME, startTime);
1181 proto.write(BroadcastStatsProto.NESTING, nesting);
1182
1183 proto.end(token);
1184 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001186
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001187 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
1188 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001189
1190 int mNumDelayedAlarms = 0;
1191 long mTotalDelayTime = 0;
1192 long mMaxDelayTime = 0;
1193
Adam Lesinski182f73f2013-12-05 16:48:06 -08001194 @Override
1195 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001196 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001197 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001198
1199 // We have to set current TimeZone info to kernel
1200 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -08001201 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001202
Christopher Tate247571462017-04-10 11:45:05 -07001203 // Also sure that we're booting with a halfway sensible current time
1204 if (mNativeData != 0) {
1205 final long systemBuildTime = Environment.getRootDirectory().lastModified();
1206 if (System.currentTimeMillis() < systemBuildTime) {
1207 Slog.i(TAG, "Current time only " + System.currentTimeMillis()
1208 + ", advancing to build time " + systemBuildTime);
1209 setKernelTime(mNativeData, systemBuildTime);
1210 }
1211 }
1212
Christopher Tatebb9cce52017-04-18 14:19:43 -07001213 // Determine SysUI's uid
1214 final PackageManager packMan = getContext().getPackageManager();
1215 try {
1216 PermissionInfo sysUiPerm = packMan.getPermissionInfo(SYSTEM_UI_SELF_PERMISSION, 0);
1217 ApplicationInfo sysUi = packMan.getApplicationInfo(sysUiPerm.packageName, 0);
1218 if ((sysUi.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1219 mSystemUiUid = sysUi.uid;
1220 } else {
1221 Slog.e(TAG, "SysUI permission " + SYSTEM_UI_SELF_PERMISSION
1222 + " defined by non-privileged app " + sysUi.packageName
1223 + " - ignoring");
1224 }
1225 } catch (NameNotFoundException e) {
1226 }
1227
1228 if (mSystemUiUid <= 0) {
1229 Slog.wtf(TAG, "SysUI package not found!");
1230 }
1231
Adam Lesinski182f73f2013-12-05 16:48:06 -08001232 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001233 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001234
Adam Lesinski182f73f2013-12-05 16:48:06 -08001235 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001236 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001237 Intent.FLAG_RECEIVER_REGISTERED_ONLY
Chad Brubaker291df4f2017-03-14 10:23:02 -07001238 | Intent.FLAG_RECEIVER_FOREGROUND
1239 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001240 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001241 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001242 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1243 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001244 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001245 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
Kweku Adams61e03292017-10-19 14:27:12 -07001246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001247 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -08001248 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249 mClockReceiver.scheduleTimeTickEvent();
1250 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001251 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001252 mUninstallReceiver = new UninstallReceiver();
Kweku Adams61e03292017-10-19 14:27:12 -07001253
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001254 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001255 AlarmThread waitThread = new AlarmThread();
1256 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001258 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001259 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001260
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001261 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001262 ActivityManager.getService().registerUidObserver(new UidObserver(),
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001263 ActivityManager.UID_OBSERVER_GONE | ActivityManager.UID_OBSERVER_IDLE
1264 | ActivityManager.UID_OBSERVER_ACTIVE,
1265 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001266 } catch (RemoteException e) {
1267 // ignored; both services live in system_server
1268 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001269 publishBinderService(Context.ALARM_SERVICE, mService);
Makoto Onuki2206af32017-11-21 16:25:35 -08001270 mForceAppStandbyTracker.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001272
1273 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001274 public void onBootPhase(int phase) {
1275 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1276 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -07001277 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001278 mLocalDeviceIdleController
1279 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackborna750a632015-06-16 17:18:23 -07001280 }
1281 }
1282
1283 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 protected void finalize() throws Throwable {
1285 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001286 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287 } finally {
1288 super.finalize();
1289 }
1290 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001291
Adam Lesinski182f73f2013-12-05 16:48:06 -08001292 void setTimeZoneImpl(String tz) {
1293 if (TextUtils.isEmpty(tz)) {
1294 return;
David Christieebe51fc2013-07-26 13:23:29 -07001295 }
1296
Adam Lesinski182f73f2013-12-05 16:48:06 -08001297 TimeZone zone = TimeZone.getTimeZone(tz);
1298 // Prevent reentrant calls from stepping on each other when writing
1299 // the time zone property
1300 boolean timeZoneWasChanged = false;
1301 synchronized (this) {
1302 String current = SystemProperties.get(TIMEZONE_PROPERTY);
1303 if (current == null || !current.equals(zone.getID())) {
1304 if (localLOGV) {
1305 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
1306 }
1307 timeZoneWasChanged = true;
1308 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
1309 }
1310
1311 // Update the kernel timezone information
1312 // Kernel tracks time offsets as 'minutes west of GMT'
1313 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001314 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001315 }
1316
1317 TimeZone.setDefault(null);
1318
1319 if (timeZoneWasChanged) {
1320 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001321 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate5cdf9f82017-05-03 18:10:39 -07001322 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
Chad Brubaker291df4f2017-03-14 10:23:02 -07001323 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001324 intent.putExtra("time-zone", zone.getID());
1325 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1326 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001328
Adam Lesinski182f73f2013-12-05 16:48:06 -08001329 void removeImpl(PendingIntent operation) {
1330 if (operation == null) {
1331 return;
1332 }
1333 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001334 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001335 }
1336 }
1337
1338 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001339 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1340 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1341 int callingUid, String callingPackage) {
1342 // must be *either* PendingIntent or AlarmReceiver, but not both
1343 if ((operation == null && directReceiver == null)
1344 || (operation != null && directReceiver != null)) {
1345 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1346 // NB: previous releases failed silently here, so we are continuing to do the same
1347 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348 return;
1349 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001350
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001351 // Sanity check the window length. This will catch people mistakenly
1352 // trying to pass an end-of-window timestamp rather than a duration.
1353 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1354 Slog.w(TAG, "Window length " + windowLength
1355 + "ms suspiciously long; limiting to 1 hour");
1356 windowLength = AlarmManager.INTERVAL_HOUR;
1357 }
1358
Christopher Tate498c6cb2014-11-17 16:09:27 -08001359 // Sanity check the recurrence interval. This will catch people who supply
1360 // seconds when the API expects milliseconds.
Dianne Hackborna750a632015-06-16 17:18:23 -07001361 final long minInterval = mConstants.MIN_INTERVAL;
1362 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001363 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001364 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001365 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001366 interval = minInterval;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001367 }
1368
Christopher Tatee0a22b32013-07-11 14:43:13 -07001369 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1370 throw new IllegalArgumentException("Invalid alarm type " + type);
1371 }
1372
Christopher Tate5f221e82013-07-30 17:13:15 -07001373 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001374 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001375 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001376 + " pid=" + what);
1377 triggerAtTime = 0;
1378 }
1379
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001380 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001381 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1382 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001383 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001384 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1385
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001386 final long maxElapsed;
1387 if (windowLength == AlarmManager.WINDOW_EXACT) {
1388 maxElapsed = triggerElapsed;
1389 } else if (windowLength < 0) {
1390 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001391 // Fix this window in place, so that as time approaches we don't collapse it.
1392 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001393 } else {
1394 maxElapsed = triggerElapsed + windowLength;
1395 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001398 if (DEBUG_BATCH) {
1399 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001400 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001401 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001402 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001404 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001405 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1406 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 }
1408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409
Christopher Tate3e04b472013-10-21 17:51:31 -07001410 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001411 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1412 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1413 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001414 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001415 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1416 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001417 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001418 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001419 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1420 + " -- package not allowed to start");
1421 return;
1422 }
1423 } catch (RemoteException e) {
1424 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001425 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001426 setImplLocked(a, false, doValidate);
1427 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001428
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001429 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1430 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001431 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001432 // The caller has given the time they want this to happen at, however we need
1433 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001434 // bring us out of idle at an earlier time.
1435 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001436 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001437 }
1438 // Add fuzz to make the alarm go off some time before the actual desired time.
1439 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001440 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001441 if (fuzz > 0) {
1442 if (mRandom == null) {
1443 mRandom = new Random();
1444 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001445 final int delta = mRandom.nextInt(fuzz);
1446 a.whenElapsed -= delta;
1447 if (false) {
1448 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1449 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1450 Slog.d(TAG, "Applied fuzz: " + fuzz);
1451 Slog.d(TAG, "Final delta: " + delta);
1452 Slog.d(TAG, "Final when: " + a.whenElapsed);
1453 }
1454 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001455 }
1456
1457 } else if (mPendingIdleUntil != null) {
1458 // We currently have an idle until alarm scheduled; if the new alarm has
1459 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001460 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1461 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1462 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001463 == 0) {
1464 mPendingWhileIdleAlarms.add(a);
1465 return;
1466 }
1467 }
1468
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001469 if (RECORD_DEVICE_IDLE_ALARMS) {
1470 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1471 IdleDispatchEntry ent = new IdleDispatchEntry();
1472 ent.uid = a.uid;
1473 ent.pkg = a.operation.getCreatorPackage();
1474 ent.tag = a.operation.getTag("");
1475 ent.op = "SET";
1476 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1477 ent.argRealtime = a.whenElapsed;
1478 mAllowWhileIdleDispatches.add(ent);
1479 }
1480 }
1481
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001482 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
1483 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -07001484 if (whichBatch < 0) {
1485 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001486 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 } else {
Christopher Tate385e4982013-07-23 18:22:29 -07001488 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001489 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001490 // The start time of this batch advanced, so batch ordering may
1491 // have just been broken. Move it to where it now belongs.
1492 mAlarmBatches.remove(whichBatch);
1493 addBatchLocked(mAlarmBatches, batch);
1494 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001495 }
1496
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001497 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001498 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001499 }
1500
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001501 boolean needRebatch = false;
1502
1503 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001504 if (RECORD_DEVICE_IDLE_ALARMS) {
1505 if (mPendingIdleUntil == null) {
1506 IdleDispatchEntry ent = new IdleDispatchEntry();
1507 ent.uid = 0;
1508 ent.pkg = "START IDLE";
1509 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1510 mAllowWhileIdleDispatches.add(ent);
1511 }
1512 }
Makoto Onuki4274a6d2017-04-21 12:21:25 -07001513 if ((mPendingIdleUntil != a) && (mPendingIdleUntil != null)) {
1514 Slog.wtfStack(TAG, "setImplLocked: idle until changed from " + mPendingIdleUntil
1515 + " to " + a);
1516 }
1517
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001518 mPendingIdleUntil = a;
Dianne Hackborna750a632015-06-16 17:18:23 -07001519 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001520 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001521 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1522 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1523 mNextWakeFromIdle = a;
1524 // If this wake from idle is earlier than whatever was previously scheduled,
1525 // and we are currently idling, then we need to rebatch alarms in case the idle
1526 // until time needs to be updated.
1527 if (mPendingIdleUntil != null) {
1528 needRebatch = true;
1529 }
1530 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001531 }
1532
1533 if (!rebatching) {
1534 if (DEBUG_VALIDATE) {
1535 if (doValidate && !validateConsistencyLocked()) {
1536 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1537 + " when(hex)=" + Long.toHexString(a.when)
1538 + " whenElapsed=" + a.whenElapsed
1539 + " maxWhenElapsed=" + a.maxWhenElapsed
1540 + " interval=" + a.repeatInterval + " op=" + a.operation
1541 + " flags=0x" + Integer.toHexString(a.flags));
1542 rebatchAllAlarmsLocked(false);
1543 needRebatch = false;
1544 }
1545 }
1546
1547 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001548 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001549 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001550
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001551 rescheduleKernelAlarmsLocked();
1552 updateNextAlarmClockLocked();
1553 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001554 }
1555
Adam Lesinski182f73f2013-12-05 16:48:06 -08001556 private final IBinder mService = new IAlarmManager.Stub() {
1557 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001558 public void set(String callingPackage,
1559 int type, long triggerAtTime, long windowLength, long interval, int flags,
1560 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1561 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001562 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001563
1564 // make sure the caller is not lying about which package should be blamed for
1565 // wakelock time spent in alarm delivery
1566 mAppOps.checkPackage(callingUid, callingPackage);
1567
1568 // Repeating alarms must use PendingIntent, not direct listener
1569 if (interval != 0) {
1570 if (directReceiver != null) {
1571 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1572 }
1573 }
1574
Adam Lesinski182f73f2013-12-05 16:48:06 -08001575 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001576 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001577 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001578 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001579 }
1580
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001581 // No incoming callers can request either WAKE_FROM_IDLE or
1582 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1583 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1584 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1585
1586 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1587 // manager when to come out of idle mode, which is only for DeviceIdleController.
1588 if (callingUid != Process.SYSTEM_UID) {
1589 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1590 }
1591
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001592 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001593 if (windowLength == AlarmManager.WINDOW_EXACT) {
1594 flags |= AlarmManager.FLAG_STANDALONE;
1595 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001596
1597 // If this alarm is for an alarm clock, then it must be standalone and we will
1598 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001599 if (alarmClock != null) {
1600 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001601
1602 // If the caller is a core system component or on the user's whitelist, and not calling
1603 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1604 // This means we will allow these alarms to go off as normal even while idle, with no
1605 // timing restrictions.
1606 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
Christopher Tatebb9cce52017-04-18 14:19:43 -07001607 || callingUid == mSystemUiUid
Makoto Onuki2206af32017-11-21 16:25:35 -08001608 || mForceAppStandbyTracker.isUidPowerSaveWhitelisted(callingUid))) {
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001609 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1610 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001611 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001612
Christopher Tate14a7bb02015-10-01 10:24:31 -07001613 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1614 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001615 }
Christopher Tate89779822012-08-31 14:40:03 -07001616
Adam Lesinski182f73f2013-12-05 16:48:06 -08001617 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001618 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001619 getContext().enforceCallingOrSelfPermission(
1620 "android.permission.SET_TIME",
1621 "setTime");
1622
Greg Hackmann0cab8962014-02-21 16:35:52 -08001623 if (mNativeData == 0) {
1624 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1625 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001626 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001627
1628 synchronized (mLock) {
1629 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001632
1633 @Override
1634 public void setTimeZone(String tz) {
1635 getContext().enforceCallingOrSelfPermission(
1636 "android.permission.SET_TIME_ZONE",
1637 "setTimeZone");
1638
1639 final long oldId = Binder.clearCallingIdentity();
1640 try {
1641 setTimeZoneImpl(tz);
1642 } finally {
1643 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 }
1645 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001646
Adam Lesinski182f73f2013-12-05 16:48:06 -08001647 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001648 public void remove(PendingIntent operation, IAlarmListener listener) {
1649 if (operation == null && listener == null) {
1650 Slog.w(TAG, "remove() with no intent or listener");
1651 return;
1652 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001653
Christopher Tate14a7bb02015-10-01 10:24:31 -07001654 synchronized (mLock) {
1655 removeLocked(operation, listener);
1656 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001658
Adam Lesinski182f73f2013-12-05 16:48:06 -08001659 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001660 public long getNextWakeFromIdleTime() {
1661 return getNextWakeFromIdleTimeImpl();
1662 }
1663
1664 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001665 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001666 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1667 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1668 "getNextAlarmClock", null);
1669
1670 return getNextAlarmClockImpl(userId);
1671 }
1672
1673 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001674 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06001675 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Kweku Adams61e03292017-10-19 14:27:12 -07001676
1677 if (args.length > 0 && "--proto".equals(args[0])) {
1678 dumpProto(fd);
1679 } else {
1680 dumpImpl(pw);
1681 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001682 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001683 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001684
Adam Lesinski182f73f2013-12-05 16:48:06 -08001685 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 synchronized (mLock) {
1687 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001688 mConstants.dump(pw);
1689 pw.println();
1690
Makoto Onuki2206af32017-11-21 16:25:35 -08001691 mForceAppStandbyTracker.dump(pw, " ");
1692
Christopher Tatee0a22b32013-07-11 14:43:13 -07001693 final long nowRTC = System.currentTimeMillis();
1694 final long nowELAPSED = SystemClock.elapsedRealtime();
1695 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1696
Dianne Hackborna750a632015-06-16 17:18:23 -07001697 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001698 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001699 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001700 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001701 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001702 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001703 pw.print(" mLastTimeChangeRealtime=");
Dianne Hackbornc3527222015-05-13 14:03:20 -07001704 TimeUtils.formatDuration(mLastTimeChangeRealtime, pw);
1705 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001706 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001707 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001708 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1709 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001710 pw.print(" Max wakeup delay: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001711 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1712 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001713 pw.print(" Time since last dispatch: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001714 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1715 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001716 pw.print(" Next non-wakeup delivery time: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001717 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1718 pw.println();
1719 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001720
1721 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1722 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001723 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001724 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001725 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001726 pw.print(" Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001727 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001728 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
1729 pw.print(" set at "); TimeUtils.formatDuration(mLastWakeupSet, nowELAPSED, pw);
1730 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001731 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001732
John Spurlock604a5ee2015-06-01 12:27:22 -04001733 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001734 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001735 final TreeSet<Integer> users = new TreeSet<>();
1736 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1737 users.add(mNextAlarmClockForUser.keyAt(i));
1738 }
1739 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1740 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1741 }
1742 for (int user : users) {
1743 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1744 final long time = next != null ? next.getTriggerTime() : 0;
1745 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001746 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001747 pw.print(" pendingSend:"); pw.print(pendingSend);
1748 pw.print(" time:"); pw.print(time);
1749 if (time > 0) {
1750 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1751 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1752 }
1753 pw.println();
1754 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001755 if (mAlarmBatches.size() > 0) {
1756 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001757 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001758 pw.println(mAlarmBatches.size());
1759 for (Batch b : mAlarmBatches) {
1760 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001761 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001762 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001763 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001764 pw.println();
1765 pw.println(" Pending user blocked background alarms: ");
1766 boolean blocked = false;
1767 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
1768 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
1769 if (blockedAlarms != null && blockedAlarms.size() > 0) {
1770 blocked = true;
1771 dumpAlarmList(pw, blockedAlarms, " ", nowELAPSED, nowRTC, sdf);
1772 }
1773 }
1774 if (!blocked) {
1775 pw.println(" none");
1776 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001777 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001778 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001779 pw.println(" Idle mode state:");
1780 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001781 if (mPendingIdleUntil != null) {
1782 pw.println(mPendingIdleUntil);
Kweku Adams61e03292017-10-19 14:27:12 -07001783 mPendingIdleUntil.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001784 } else {
1785 pw.println("null");
1786 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001787 pw.println(" Pending alarms:");
1788 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001789 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001790 if (mNextWakeFromIdle != null) {
1791 pw.println();
1792 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
Kweku Adams61e03292017-10-19 14:27:12 -07001793 mNextWakeFromIdle.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001794 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001795
1796 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001797 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001798 if (mPendingNonWakeupAlarms.size() > 0) {
1799 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001800 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001801 } else {
1802 pw.println("(none)");
1803 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001804 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001805 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1806 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001807 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001808 pw.print(", max non-interactive time: ");
1809 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1810 pw.println();
1811
1812 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001813 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Christopher Tateeabba732017-08-17 17:12:52 -07001814 pw.print(" PendingIntent send count: "); pw.println(mSendCount);
1815 pw.print(" PendingIntent finish count: "); pw.println(mSendFinishCount);
1816 pw.print(" Listener send count: "); pw.println(mListenerCount);
1817 pw.print(" Listener finish count: "); pw.println(mListenerFinishCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001818 pw.println();
1819
Christopher Tate7f2a0352015-12-08 10:24:33 -08001820 if (mInFlight.size() > 0) {
1821 pw.println("Outstanding deliveries:");
1822 for (int i = 0; i < mInFlight.size(); i++) {
1823 pw.print(" #"); pw.print(i); pw.print(": ");
1824 pw.println(mInFlight.get(i));
1825 }
1826 pw.println();
1827 }
1828
Dianne Hackborna750a632015-06-16 17:18:23 -07001829 pw.print(" mAllowWhileIdleMinTime=");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001830 TimeUtils.formatDuration(mAllowWhileIdleMinTime, pw);
1831 pw.println();
1832 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001833 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001834 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
1835 pw.print(" UID ");
1836 UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
1837 pw.print(": ");
1838 TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i),
1839 nowELAPSED, pw);
1840 pw.println();
1841 }
1842 }
1843 pw.println();
1844
Dianne Hackborn81038902012-11-26 17:04:09 -08001845 if (mLog.dump(pw, " Recent problems", " ")) {
1846 pw.println();
1847 }
1848
1849 final FilterStats[] topFilters = new FilterStats[10];
1850 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1851 @Override
1852 public int compare(FilterStats lhs, FilterStats rhs) {
1853 if (lhs.aggregateTime < rhs.aggregateTime) {
1854 return 1;
1855 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1856 return -1;
1857 }
1858 return 0;
1859 }
1860 };
1861 int len = 0;
Kweku Adams61e03292017-10-19 14:27:12 -07001862 // Get the top 10 FilterStats, ordered by aggregateTime.
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001863 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1864 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1865 for (int ip=0; ip<uidStats.size(); ip++) {
1866 BroadcastStats bs = uidStats.valueAt(ip);
1867 for (int is=0; is<bs.filterStats.size(); is++) {
1868 FilterStats fs = bs.filterStats.valueAt(is);
1869 int pos = len > 0
1870 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1871 if (pos < 0) {
1872 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001873 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001874 if (pos < topFilters.length) {
1875 int copylen = topFilters.length - pos - 1;
1876 if (copylen > 0) {
1877 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1878 }
1879 topFilters[pos] = fs;
1880 if (len < topFilters.length) {
1881 len++;
1882 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001883 }
1884 }
1885 }
1886 }
1887 if (len > 0) {
1888 pw.println(" Top Alarms:");
1889 for (int i=0; i<len; i++) {
1890 FilterStats fs = topFilters[i];
1891 pw.print(" ");
1892 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1893 TimeUtils.formatDuration(fs.aggregateTime, pw);
1894 pw.print(" running, "); pw.print(fs.numWakeup);
1895 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001896 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1897 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001898 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001899 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001900 pw.println();
1901 }
1902 }
1903
1904 pw.println(" ");
1905 pw.println(" Alarm Stats:");
1906 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001907 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1908 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1909 for (int ip=0; ip<uidStats.size(); ip++) {
1910 BroadcastStats bs = uidStats.valueAt(ip);
1911 pw.print(" ");
1912 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1913 UserHandle.formatUid(pw, bs.mUid);
1914 pw.print(":");
1915 pw.print(bs.mPackageName);
1916 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1917 pw.print(" running, "); pw.print(bs.numWakeup);
1918 pw.println(" wakeups:");
1919 tmpFilters.clear();
1920 for (int is=0; is<bs.filterStats.size(); is++) {
1921 tmpFilters.add(bs.filterStats.valueAt(is));
1922 }
1923 Collections.sort(tmpFilters, comparator);
1924 for (int i=0; i<tmpFilters.size(); i++) {
1925 FilterStats fs = tmpFilters.get(i);
1926 pw.print(" ");
1927 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1928 TimeUtils.formatDuration(fs.aggregateTime, pw);
1929 pw.print(" "); pw.print(fs.numWakeup);
1930 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001931 pw.print(" alarms, last ");
1932 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1933 pw.println(":");
1934 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001935 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001936 pw.println();
1937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001938 }
1939 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001940
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001941 if (RECORD_DEVICE_IDLE_ALARMS) {
1942 pw.println();
1943 pw.println(" Allow while idle dispatches:");
1944 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
1945 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
1946 pw.print(" ");
1947 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
1948 pw.print(": ");
1949 UserHandle.formatUid(pw, ent.uid);
1950 pw.print(":");
1951 pw.println(ent.pkg);
1952 if (ent.op != null) {
1953 pw.print(" ");
1954 pw.print(ent.op);
1955 pw.print(" / ");
1956 pw.print(ent.tag);
1957 if (ent.argRealtime != 0) {
1958 pw.print(" (");
1959 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
1960 pw.print(")");
1961 }
1962 pw.println();
1963 }
1964 }
1965 }
1966
Christopher Tate18a75f12013-07-01 18:18:59 -07001967 if (WAKEUP_STATS) {
1968 pw.println();
1969 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001970 long last = -1;
1971 for (WakeupEvent event : mRecentWakeups) {
1972 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1973 pw.print('|');
1974 if (last < 0) {
1975 pw.print('0');
1976 } else {
1977 pw.print(event.when - last);
1978 }
1979 last = event.when;
1980 pw.print('|'); pw.print(event.uid);
1981 pw.print('|'); pw.print(event.action);
1982 pw.println();
1983 }
1984 pw.println();
1985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986 }
1987 }
1988
Kweku Adams61e03292017-10-19 14:27:12 -07001989 void dumpProto(FileDescriptor fd) {
1990 final ProtoOutputStream proto = new ProtoOutputStream(fd);
1991
1992 synchronized (mLock) {
1993 final long nowRTC = System.currentTimeMillis();
1994 final long nowElapsed = SystemClock.elapsedRealtime();
1995 proto.write(AlarmManagerServiceProto.CURRENT_TIME, nowRTC);
1996 proto.write(AlarmManagerServiceProto.ELAPSED_REALTIME, nowElapsed);
1997 proto.write(AlarmManagerServiceProto.LAST_TIME_CHANGE_CLOCK_TIME,
1998 mLastTimeChangeClockTime);
1999 proto.write(AlarmManagerServiceProto.LAST_TIME_CHANGE_REALTIME,
2000 mLastTimeChangeRealtime);
2001
2002 mConstants.dumpProto(proto, AlarmManagerServiceProto.SETTINGS);
2003
Makoto Onuki2206af32017-11-21 16:25:35 -08002004 mForceAppStandbyTracker.dumpProto(proto,
2005 AlarmManagerServiceProto.FORCE_APP_STANDBY_TRACKER);
Kweku Adams61e03292017-10-19 14:27:12 -07002006
2007 proto.write(AlarmManagerServiceProto.IS_INTERACTIVE, mInteractive);
2008 if (!mInteractive) {
2009 // Durations
2010 proto.write(AlarmManagerServiceProto.TIME_SINCE_NON_INTERACTIVE_MS,
2011 nowElapsed - mNonInteractiveStartTime);
2012 proto.write(AlarmManagerServiceProto.MAX_WAKEUP_DELAY_MS,
2013 currentNonWakeupFuzzLocked(nowElapsed));
2014 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_DISPATCH_MS,
2015 nowElapsed - mLastAlarmDeliveryTime);
2016 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_NON_WAKEUP_DELIVERY_MS,
2017 nowElapsed - mNextNonWakeupDeliveryTime);
2018 }
2019
2020 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_NON_WAKEUP_ALARM_MS,
2021 mNextNonWakeup - nowElapsed);
2022 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_WAKEUP_MS,
2023 mNextWakeup - nowElapsed);
2024 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_WAKEUP_MS,
2025 nowElapsed - mLastWakeup);
2026 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_WAKEUP_SET_MS,
2027 nowElapsed - mLastWakeupSet);
2028 proto.write(AlarmManagerServiceProto.TIME_CHANGE_EVENT_COUNT, mNumTimeChanged);
Kweku Adams61e03292017-10-19 14:27:12 -07002029
2030 final TreeSet<Integer> users = new TreeSet<>();
2031 final int nextAlarmClockForUserSize = mNextAlarmClockForUser.size();
2032 for (int i = 0; i < nextAlarmClockForUserSize; i++) {
2033 users.add(mNextAlarmClockForUser.keyAt(i));
2034 }
2035 final int pendingSendNextAlarmClockChangedForUserSize =
2036 mPendingSendNextAlarmClockChangedForUser.size();
2037 for (int i = 0; i < pendingSendNextAlarmClockChangedForUserSize; i++) {
2038 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2039 }
2040 for (int user : users) {
2041 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2042 final long time = next != null ? next.getTriggerTime() : 0;
2043 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
2044 final long aToken = proto.start(AlarmManagerServiceProto.NEXT_ALARM_CLOCK_METADATA);
2045 proto.write(AlarmClockMetadataProto.USER, user);
2046 proto.write(AlarmClockMetadataProto.IS_PENDING_SEND, pendingSend);
2047 proto.write(AlarmClockMetadataProto.TRIGGER_TIME_MS, time);
2048 proto.end(aToken);
2049 }
2050 for (Batch b : mAlarmBatches) {
2051 b.writeToProto(proto, AlarmManagerServiceProto.PENDING_ALARM_BATCHES,
2052 nowElapsed, nowRTC);
2053 }
2054 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2055 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2056 if (blockedAlarms != null) {
2057 for (Alarm a : blockedAlarms) {
2058 a.writeToProto(proto,
2059 AlarmManagerServiceProto.PENDING_USER_BLOCKED_BACKGROUND_ALARMS,
2060 nowElapsed, nowRTC);
2061 }
2062 }
2063 }
2064 if (mPendingIdleUntil != null) {
2065 mPendingIdleUntil.writeToProto(
2066 proto, AlarmManagerServiceProto.PENDING_IDLE_UNTIL, nowElapsed, nowRTC);
2067 }
2068 for (Alarm a : mPendingWhileIdleAlarms) {
2069 a.writeToProto(proto, AlarmManagerServiceProto.PENDING_WHILE_IDLE_ALARMS,
2070 nowElapsed, nowRTC);
2071 }
2072 if (mNextWakeFromIdle != null) {
2073 mNextWakeFromIdle.writeToProto(proto, AlarmManagerServiceProto.NEXT_WAKE_FROM_IDLE,
2074 nowElapsed, nowRTC);
2075 }
2076
2077 for (Alarm a : mPendingNonWakeupAlarms) {
2078 a.writeToProto(proto, AlarmManagerServiceProto.PAST_DUE_NON_WAKEUP_ALARMS,
2079 nowElapsed, nowRTC);
2080 }
2081
2082 proto.write(AlarmManagerServiceProto.DELAYED_ALARM_COUNT, mNumDelayedAlarms);
2083 proto.write(AlarmManagerServiceProto.TOTAL_DELAY_TIME_MS, mTotalDelayTime);
2084 proto.write(AlarmManagerServiceProto.MAX_DELAY_DURATION_MS, mMaxDelayTime);
2085 proto.write(AlarmManagerServiceProto.MAX_NON_INTERACTIVE_DURATION_MS,
2086 mNonInteractiveTime);
2087
2088 proto.write(AlarmManagerServiceProto.BROADCAST_REF_COUNT, mBroadcastRefCount);
2089 proto.write(AlarmManagerServiceProto.PENDING_INTENT_SEND_COUNT, mSendCount);
2090 proto.write(AlarmManagerServiceProto.PENDING_INTENT_FINISH_COUNT, mSendFinishCount);
2091 proto.write(AlarmManagerServiceProto.LISTENER_SEND_COUNT, mListenerCount);
2092 proto.write(AlarmManagerServiceProto.LISTENER_FINISH_COUNT, mListenerFinishCount);
2093
2094 for (InFlight f : mInFlight) {
2095 f.writeToProto(proto, AlarmManagerServiceProto.OUTSTANDING_DELIVERIES);
2096 }
2097
2098 proto.write(AlarmManagerServiceProto.ALLOW_WHILE_IDLE_MIN_DURATION_MS,
2099 mAllowWhileIdleMinTime);
2100 for (int i = 0; i < mLastAllowWhileIdleDispatch.size(); ++i) {
2101 final long token = proto.start(
2102 AlarmManagerServiceProto.LAST_ALLOW_WHILE_IDLE_DISPATCH_TIMES);
2103 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.UID,
2104 mLastAllowWhileIdleDispatch.keyAt(i));
2105 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.TIME_MS,
2106 mLastAllowWhileIdleDispatch.valueAt(i));
2107 proto.end(token);
2108 }
2109
2110 mLog.writeToProto(proto, AlarmManagerServiceProto.RECENT_PROBLEMS);
2111
2112 final FilterStats[] topFilters = new FilterStats[10];
2113 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2114 @Override
2115 public int compare(FilterStats lhs, FilterStats rhs) {
2116 if (lhs.aggregateTime < rhs.aggregateTime) {
2117 return 1;
2118 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2119 return -1;
2120 }
2121 return 0;
2122 }
2123 };
2124 int len = 0;
2125 // Get the top 10 FilterStats, ordered by aggregateTime.
2126 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2127 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2128 for (int ip = 0; ip < uidStats.size(); ++ip) {
2129 BroadcastStats bs = uidStats.valueAt(ip);
2130 for (int is = 0; is < bs.filterStats.size(); ++is) {
2131 FilterStats fs = bs.filterStats.valueAt(is);
2132 int pos = len > 0
2133 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2134 if (pos < 0) {
2135 pos = -pos - 1;
2136 }
2137 if (pos < topFilters.length) {
2138 int copylen = topFilters.length - pos - 1;
2139 if (copylen > 0) {
2140 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2141 }
2142 topFilters[pos] = fs;
2143 if (len < topFilters.length) {
2144 len++;
2145 }
2146 }
2147 }
2148 }
2149 }
2150 for (int i = 0; i < len; ++i) {
2151 final long token = proto.start(AlarmManagerServiceProto.TOP_ALARMS);
2152 FilterStats fs = topFilters[i];
2153
2154 proto.write(AlarmManagerServiceProto.TopAlarm.UID, fs.mBroadcastStats.mUid);
2155 proto.write(AlarmManagerServiceProto.TopAlarm.PACKAGE_NAME,
2156 fs.mBroadcastStats.mPackageName);
2157 fs.writeToProto(proto, AlarmManagerServiceProto.TopAlarm.FILTER);
2158
2159 proto.end(token);
2160 }
2161
2162 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
2163 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2164 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2165 for (int ip = 0; ip < uidStats.size(); ++ip) {
2166 final long token = proto.start(AlarmManagerServiceProto.ALARM_STATS);
2167
2168 BroadcastStats bs = uidStats.valueAt(ip);
2169 bs.writeToProto(proto, AlarmManagerServiceProto.AlarmStat.BROADCAST);
2170
2171 // uidStats is an ArrayMap, which we can't sort.
2172 tmpFilters.clear();
2173 for (int is = 0; is < bs.filterStats.size(); ++is) {
2174 tmpFilters.add(bs.filterStats.valueAt(is));
2175 }
2176 Collections.sort(tmpFilters, comparator);
2177 for (FilterStats fs : tmpFilters) {
2178 fs.writeToProto(proto, AlarmManagerServiceProto.AlarmStat.FILTERS);
2179 }
2180
2181 proto.end(token);
2182 }
2183 }
2184
2185 if (RECORD_DEVICE_IDLE_ALARMS) {
2186 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2187 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2188 final long token = proto.start(
2189 AlarmManagerServiceProto.ALLOW_WHILE_IDLE_DISPATCHES);
2190
2191 proto.write(IdleDispatchEntryProto.UID, ent.uid);
2192 proto.write(IdleDispatchEntryProto.PKG, ent.pkg);
2193 proto.write(IdleDispatchEntryProto.TAG, ent.tag);
2194 proto.write(IdleDispatchEntryProto.OP, ent.op);
2195 proto.write(IdleDispatchEntryProto.ENTRY_CREATION_REALTIME,
2196 ent.elapsedRealtime);
2197 proto.write(IdleDispatchEntryProto.ARG_REALTIME, ent.argRealtime);
2198
2199 proto.end(token);
2200 }
2201 }
2202
2203 if (WAKEUP_STATS) {
2204 for (WakeupEvent event : mRecentWakeups) {
2205 final long token = proto.start(AlarmManagerServiceProto.RECENT_WAKEUP_HISTORY);
2206 proto.write(WakeupEventProto.UID, event.uid);
2207 proto.write(WakeupEventProto.ACTION, event.action);
2208 proto.write(WakeupEventProto.WHEN, event.when);
2209 proto.end(token);
2210 }
2211 }
2212 }
2213
2214 proto.flush();
2215 }
2216
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002217 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002218 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
2219 PrintWriter pw = new PrintWriter(bs);
2220 final long nowRTC = System.currentTimeMillis();
2221 final long nowELAPSED = SystemClock.elapsedRealtime();
2222 final int NZ = mAlarmBatches.size();
2223 for (int iz = 0; iz < NZ; iz++) {
2224 Batch bz = mAlarmBatches.get(iz);
2225 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002226 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002227 pw.flush();
2228 Slog.v(TAG, bs.toString());
2229 bs.reset();
2230 }
2231 }
2232
2233 private boolean validateConsistencyLocked() {
2234 if (DEBUG_VALIDATE) {
2235 long lastTime = Long.MIN_VALUE;
2236 final int N = mAlarmBatches.size();
2237 for (int i = 0; i < N; i++) {
2238 Batch b = mAlarmBatches.get(i);
2239 if (b.start >= lastTime) {
2240 // duplicate start times are okay because of standalone batches
2241 lastTime = b.start;
2242 } else {
2243 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002244 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2245 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002246 return false;
2247 }
2248 }
2249 }
2250 return true;
2251 }
2252
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002253 private Batch findFirstWakeupBatchLocked() {
2254 final int N = mAlarmBatches.size();
2255 for (int i = 0; i < N; i++) {
2256 Batch b = mAlarmBatches.get(i);
2257 if (b.hasWakeups()) {
2258 return b;
2259 }
2260 }
2261 return null;
2262 }
2263
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002264 long getNextWakeFromIdleTimeImpl() {
2265 synchronized (mLock) {
2266 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
2267 }
2268 }
2269
2270 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002271 synchronized (mLock) {
2272 return mNextAlarmClockForUser.get(userId);
2273 }
2274 }
2275
2276 /**
2277 * Recomputes the next alarm clock for all users.
2278 */
2279 private void updateNextAlarmClockLocked() {
2280 if (!mNextAlarmClockMayChange) {
2281 return;
2282 }
2283 mNextAlarmClockMayChange = false;
2284
Jose Lima235510e2014-08-13 12:50:01 -07002285 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002286 nextForUser.clear();
2287
2288 final int N = mAlarmBatches.size();
2289 for (int i = 0; i < N; i++) {
2290 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
2291 final int M = alarms.size();
2292
2293 for (int j = 0; j < M; j++) {
2294 Alarm a = alarms.get(j);
2295 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002296 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07002297 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002298
2299 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07002300 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002301 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02002302 " for user " + userId);
2303 }
2304
2305 // Alarms and batches are sorted by time, no need to compare times here.
2306 if (nextForUser.get(userId) == null) {
2307 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07002308 } else if (a.alarmClock.equals(current)
2309 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
2310 // same/earlier time and it's the one we cited before, so stick with it
2311 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002312 }
2313 }
2314 }
2315 }
2316
2317 // Update mNextAlarmForUser with new values.
2318 final int NN = nextForUser.size();
2319 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07002320 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002321 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002322 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002323 if (!newAlarm.equals(currentAlarm)) {
2324 updateNextAlarmInfoForUserLocked(userId, newAlarm);
2325 }
2326 }
2327
2328 // Remove users without any alarm clocks scheduled.
2329 final int NNN = mNextAlarmClockForUser.size();
2330 for (int i = NNN - 1; i >= 0; i--) {
2331 int userId = mNextAlarmClockForUser.keyAt(i);
2332 if (nextForUser.get(userId) == null) {
2333 updateNextAlarmInfoForUserLocked(userId, null);
2334 }
2335 }
2336 }
2337
Jose Lima235510e2014-08-13 12:50:01 -07002338 private void updateNextAlarmInfoForUserLocked(int userId,
2339 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002340 if (alarmClock != null) {
2341 if (DEBUG_ALARM_CLOCK) {
2342 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002343 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02002344 }
2345 mNextAlarmClockForUser.put(userId, alarmClock);
2346 } else {
2347 if (DEBUG_ALARM_CLOCK) {
2348 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
2349 }
2350 mNextAlarmClockForUser.remove(userId);
2351 }
2352
2353 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
2354 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2355 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2356 }
2357
2358 /**
2359 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
2360 * for which alarm clocks have changed since the last call to this.
2361 *
2362 * Do not call with a lock held. Only call from mHandler's thread.
2363 *
2364 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
2365 */
2366 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07002367 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002368 pendingUsers.clear();
2369
2370 synchronized (mLock) {
2371 final int N = mPendingSendNextAlarmClockChangedForUser.size();
2372 for (int i = 0; i < N; i++) {
2373 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
2374 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
2375 }
2376 mPendingSendNextAlarmClockChangedForUser.clear();
2377 }
2378
2379 final int N = pendingUsers.size();
2380 for (int i = 0; i < N; i++) {
2381 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002382 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002383 Settings.System.putStringForUser(getContext().getContentResolver(),
2384 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01002385 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02002386 userId);
2387
2388 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
2389 new UserHandle(userId));
2390 }
2391 }
2392
2393 /**
2394 * Formats an alarm like platform/packages/apps/DeskClock used to.
2395 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01002396 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
2397 int userId) {
2398 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02002399 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
2400 return (info == null) ? "" :
2401 DateFormat.format(pattern, info.getTriggerTime()).toString();
2402 }
2403
Adam Lesinski182f73f2013-12-05 16:48:06 -08002404 void rescheduleKernelAlarmsLocked() {
2405 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
2406 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002407 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002408 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002409 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002410 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07002411 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002412 mNextWakeup = firstWakeup.start;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002413 mLastWakeupSet = SystemClock.elapsedRealtime();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002414 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002415 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002416 if (firstBatch != firstWakeup) {
2417 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002418 }
2419 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002420 if (mPendingNonWakeupAlarms.size() > 0) {
2421 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
2422 nextNonWakeup = mNextNonWakeupDeliveryTime;
2423 }
2424 }
Prashant Malani753e9e02015-06-10 17:43:49 -07002425 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002426 mNextNonWakeup = nextNonWakeup;
2427 setLocked(ELAPSED_REALTIME, nextNonWakeup);
2428 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002429 }
2430
Christopher Tate14a7bb02015-10-01 10:24:31 -07002431 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002432 boolean didRemove = false;
2433 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2434 Batch b = mAlarmBatches.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002435 didRemove |= b.remove(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002436 if (b.size() == 0) {
2437 mAlarmBatches.remove(i);
2438 }
2439 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002440 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002441 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002442 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2443 mPendingWhileIdleAlarms.remove(i);
2444 }
2445 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002446 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2447 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2448 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2449 if (alarmsForUid.get(j).matches(operation, directReceiver)) {
2450 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2451 alarmsForUid.remove(j);
2452 }
2453 }
2454 if (alarmsForUid.size() == 0) {
2455 mPendingBackgroundAlarms.removeAt(i);
2456 }
2457 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002458 if (didRemove) {
2459 if (DEBUG_BATCH) {
2460 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
2461 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002462 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002463 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002464 mPendingIdleUntil = null;
2465 restorePending = true;
2466 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002467 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002468 mNextWakeFromIdle = null;
2469 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002470 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002471 if (restorePending) {
2472 restorePendingWhileIdleAlarmsLocked();
2473 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002474 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002475 }
2476 }
2477
2478 void removeLocked(String packageName) {
2479 boolean didRemove = false;
2480 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2481 Batch b = mAlarmBatches.get(i);
2482 didRemove |= b.remove(packageName);
2483 if (b.size() == 0) {
2484 mAlarmBatches.remove(i);
2485 }
2486 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002487 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002488 final Alarm a = mPendingWhileIdleAlarms.get(i);
2489 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002490 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2491 mPendingWhileIdleAlarms.remove(i);
2492 }
2493 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002494 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2495 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2496 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2497 if (alarmsForUid.get(j).matches(packageName)) {
2498 alarmsForUid.remove(j);
2499 }
2500 }
2501 if (alarmsForUid.size() == 0) {
2502 mPendingBackgroundAlarms.removeAt(i);
2503 }
2504 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002505 if (didRemove) {
2506 if (DEBUG_BATCH) {
2507 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2508 }
2509 rebatchAllAlarmsLocked(true);
2510 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002511 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002512 }
2513 }
2514
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002515 void removeForStoppedLocked(int uid) {
2516 boolean didRemove = false;
2517 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2518 Batch b = mAlarmBatches.get(i);
2519 didRemove |= b.removeForStopped(uid);
2520 if (b.size() == 0) {
2521 mAlarmBatches.remove(i);
2522 }
2523 }
2524 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2525 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08002526 if (a.uid == uid) {
2527 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2528 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002529 }
2530 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002531 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2532 if (mPendingBackgroundAlarms.keyAt(i) == uid) {
2533 mPendingBackgroundAlarms.removeAt(i);
2534 }
2535 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002536 if (didRemove) {
2537 if (DEBUG_BATCH) {
2538 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2539 }
2540 rebatchAllAlarmsLocked(true);
2541 rescheduleKernelAlarmsLocked();
2542 updateNextAlarmClockLocked();
2543 }
2544 }
2545
Adam Lesinski182f73f2013-12-05 16:48:06 -08002546 void removeUserLocked(int userHandle) {
2547 boolean didRemove = false;
2548 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2549 Batch b = mAlarmBatches.get(i);
2550 didRemove |= b.remove(userHandle);
2551 if (b.size() == 0) {
2552 mAlarmBatches.remove(i);
2553 }
2554 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002555 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002556 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002557 == userHandle) {
2558 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2559 mPendingWhileIdleAlarms.remove(i);
2560 }
2561 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002562 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2563 if (UserHandle.getUserId(mPendingBackgroundAlarms.keyAt(i)) == userHandle) {
2564 mPendingBackgroundAlarms.removeAt(i);
2565 }
2566 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002567 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
2568 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
2569 mLastAllowWhileIdleDispatch.removeAt(i);
2570 }
2571 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002572
2573 if (didRemove) {
2574 if (DEBUG_BATCH) {
2575 Slog.v(TAG, "remove(user) changed bounds; rebatching");
2576 }
2577 rebatchAllAlarmsLocked(true);
2578 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002579 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002580 }
2581 }
2582
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002583 void interactiveStateChangedLocked(boolean interactive) {
2584 if (mInteractive != interactive) {
2585 mInteractive = interactive;
2586 final long nowELAPSED = SystemClock.elapsedRealtime();
2587 if (interactive) {
2588 if (mPendingNonWakeupAlarms.size() > 0) {
2589 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2590 mTotalDelayTime += thisDelayTime;
2591 if (mMaxDelayTime < thisDelayTime) {
2592 mMaxDelayTime = thisDelayTime;
2593 }
2594 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2595 mPendingNonWakeupAlarms.clear();
2596 }
2597 if (mNonInteractiveStartTime > 0) {
2598 long dur = nowELAPSED - mNonInteractiveStartTime;
2599 if (dur > mNonInteractiveTime) {
2600 mNonInteractiveTime = dur;
2601 }
2602 }
2603 } else {
2604 mNonInteractiveStartTime = nowELAPSED;
2605 }
2606 }
2607 }
2608
Adam Lesinski182f73f2013-12-05 16:48:06 -08002609 boolean lookForPackageLocked(String packageName) {
2610 for (int i = 0; i < mAlarmBatches.size(); i++) {
2611 Batch b = mAlarmBatches.get(i);
2612 if (b.hasPackage(packageName)) {
2613 return true;
2614 }
2615 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002616 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002617 final Alarm a = mPendingWhileIdleAlarms.get(i);
2618 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002619 return true;
2620 }
2621 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002622 return false;
2623 }
2624
2625 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002626 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002627 // The kernel never triggers alarms with negative wakeup times
2628 // so we ensure they are positive.
2629 long alarmSeconds, alarmNanoseconds;
2630 if (when < 0) {
2631 alarmSeconds = 0;
2632 alarmNanoseconds = 0;
2633 } else {
2634 alarmSeconds = when / 1000;
2635 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2636 }
Kweku Adams61e03292017-10-19 14:27:12 -07002637
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002638 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002639 } else {
2640 Message msg = Message.obtain();
2641 msg.what = ALARM_EVENT;
Kweku Adams61e03292017-10-19 14:27:12 -07002642
Adam Lesinski182f73f2013-12-05 16:48:06 -08002643 mHandler.removeMessages(ALARM_EVENT);
2644 mHandler.sendMessageAtTime(msg, when);
2645 }
2646 }
2647
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002648 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Kweku Adams61e03292017-10-19 14:27:12 -07002649 String prefix, String label, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002650 for (int i=list.size()-1; i>=0; i--) {
2651 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002652 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2653 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002654 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002655 }
2656 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002657
2658 private static final String labelForType(int type) {
2659 switch (type) {
2660 case RTC: return "RTC";
2661 case RTC_WAKEUP : return "RTC_WAKEUP";
2662 case ELAPSED_REALTIME : return "ELAPSED";
2663 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
Christopher Tatee0a22b32013-07-11 14:43:13 -07002664 }
2665 return "--unknown--";
2666 }
2667
2668 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002669 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002670 for (int i=list.size()-1; i>=0; i--) {
2671 Alarm a = list.get(i);
2672 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002673 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2674 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002675 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002676 }
2677 }
2678
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002679 private boolean isBackgroundRestricted(Alarm alarm) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002680 if (alarm.alarmClock != null) {
2681 // Don't block alarm clocks
2682 return false;
2683 }
2684 if (alarm.operation != null
2685 && (alarm.operation.isActivity() || alarm.operation.isForegroundService())) {
2686 // Don't block starting foreground components
2687 return false;
2688 }
2689 final String sourcePackage =
2690 (alarm.operation != null) ? alarm.operation.getCreatorPackage() : alarm.packageName;
2691 final int sourceUid = alarm.creatorUid;
Makoto Onuki2206af32017-11-21 16:25:35 -08002692 return mForceAppStandbyTracker.areAlarmsRestricted(sourceUid, sourcePackage);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002693 }
2694
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002695 private native long init();
2696 private native void close(long nativeData);
2697 private native void set(long nativeData, int type, long seconds, long nanoseconds);
2698 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08002699 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002700 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002701
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002702 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002703 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002704 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002705 // batches are temporally sorted, so we need only pull from the
2706 // start of the list until we either empty it or hit a batch
2707 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07002708 while (mAlarmBatches.size() > 0) {
2709 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002710 if (batch.start > nowELAPSED) {
2711 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002712 break;
2713 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002714
Christopher Tatee0a22b32013-07-11 14:43:13 -07002715 // We will (re)schedule some alarms now; don't let that interfere
2716 // with delivery of this current batch
2717 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002718
Christopher Tatee0a22b32013-07-11 14:43:13 -07002719 final int N = batch.size();
2720 for (int i = 0; i < N; i++) {
2721 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002722
2723 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
2724 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
2725 // schedule such alarms.
2726 long lastTime = mLastAllowWhileIdleDispatch.get(alarm.uid, 0);
2727 long minTime = lastTime + mAllowWhileIdleMinTime;
2728 if (nowELAPSED < minTime) {
2729 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
2730 // alarm went off for this app. Reschedule the alarm to be in the
2731 // correct time period.
2732 alarm.whenElapsed = minTime;
2733 if (alarm.maxWhenElapsed < minTime) {
2734 alarm.maxWhenElapsed = minTime;
2735 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002736 if (RECORD_DEVICE_IDLE_ALARMS) {
2737 IdleDispatchEntry ent = new IdleDispatchEntry();
2738 ent.uid = alarm.uid;
2739 ent.pkg = alarm.operation.getCreatorPackage();
2740 ent.tag = alarm.operation.getTag("");
2741 ent.op = "RESCHEDULE";
2742 ent.elapsedRealtime = nowELAPSED;
2743 ent.argRealtime = lastTime;
2744 mAllowWhileIdleDispatches.add(ent);
2745 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002746 setImplLocked(alarm, true, false);
2747 continue;
2748 }
2749 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002750 if (isBackgroundRestricted(alarm)) {
2751 // Alarms with FLAG_WAKE_FROM_IDLE or mPendingIdleUntil alarm are not deferred
2752 if (DEBUG_BG_LIMIT) {
2753 Slog.d(TAG, "Deferring alarm " + alarm + " due to user forced app standby");
2754 }
2755 ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(alarm.creatorUid);
2756 if (alarmsForUid == null) {
2757 alarmsForUid = new ArrayList<>();
2758 mPendingBackgroundAlarms.put(alarm.creatorUid, alarmsForUid);
2759 }
2760 alarmsForUid.add(alarm);
2761 continue;
2762 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002763
Christopher Tatee0a22b32013-07-11 14:43:13 -07002764 alarm.count = 1;
2765 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002766 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
2767 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002768 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002769 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002770 if (mPendingIdleUntil == alarm) {
2771 mPendingIdleUntil = null;
2772 rebatchAllAlarmsLocked(false);
2773 restorePendingWhileIdleAlarmsLocked();
2774 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002775 if (mNextWakeFromIdle == alarm) {
2776 mNextWakeFromIdle = null;
2777 rebatchAllAlarmsLocked(false);
2778 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002779
2780 // Recurring alarms may have passed several alarm intervals while the
2781 // phone was asleep or off, so pass a trigger count when sending them.
2782 if (alarm.repeatInterval > 0) {
2783 // this adjustment will be zero if we're late by
2784 // less than one full repeat interval
2785 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
2786
2787 // Also schedule its next recurrence
2788 final long delta = alarm.count * alarm.repeatInterval;
2789 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07002790 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07002791 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07002792 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
2793 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08002794 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002795
Christopher Tate864d42e2014-12-02 11:48:53 -08002796 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002797 hasWakeup = true;
2798 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002799
2800 // We removed an alarm clock. Let the caller recompute the next alarm clock.
2801 if (alarm.alarmClock != null) {
2802 mNextAlarmClockMayChange = true;
2803 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07002804 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002805 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002806
Christopher Tate1590f1e2014-10-02 17:27:57 -07002807 // This is a new alarm delivery set; bump the sequence number to indicate that
2808 // all apps' alarm delivery classes should be recalculated.
2809 mCurrentSeq++;
2810 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002811 Collections.sort(triggerList, mAlarmDispatchComparator);
2812
2813 if (localLOGV) {
2814 for (int i=0; i<triggerList.size(); i++) {
2815 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
2816 }
2817 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002818
2819 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002820 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822 /**
2823 * This Comparator sorts Alarms into increasing time order.
2824 */
2825 public static class IncreasingTimeOrder implements Comparator<Alarm> {
2826 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09002827 long when1 = a1.whenElapsed;
2828 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002829 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002830 return 1;
2831 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002832 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 return -1;
2834 }
2835 return 0;
2836 }
2837 }
Kweku Adams61e03292017-10-19 14:27:12 -07002838
Makoto Onuki2206af32017-11-21 16:25:35 -08002839 @VisibleForTesting
2840 static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002841 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002842 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002843 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002844 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002845 public final IAlarmListener listener;
2846 public final String listenerTag;
2847 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002848 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002849 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002850 public final AlarmManager.AlarmClockInfo alarmClock;
2851 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002852 public final int creatorUid;
2853 public final String packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002854 public int count;
2855 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07002856 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002857 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002858 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002859 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07002860 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002861
Christopher Tate3e04b472013-10-21 17:51:31 -07002862 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002863 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
2864 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
2865 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002866 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002867 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002868 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
2869 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002870 when = _when;
2871 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07002872 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002873 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002874 repeatInterval = _interval;
2875 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002876 listener = _rec;
2877 listenerTag = _listenerTag;
2878 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07002879 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002880 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002881 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002882 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002883 packageName = _pkgName;
2884
2885 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002886 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002887
Christopher Tate14a7bb02015-10-01 10:24:31 -07002888 public static String makeTag(PendingIntent pi, String tag, int type) {
2889 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
2890 ? "*walarm*:" : "*alarm*:";
2891 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
2892 }
2893
2894 public WakeupEvent makeWakeupEvent(long nowRTC) {
2895 return new WakeupEvent(nowRTC, creatorUid,
2896 (operation != null)
2897 ? operation.getIntent().getAction()
2898 : ("<listener>:" + listenerTag));
2899 }
2900
2901 // Returns true if either matches
2902 public boolean matches(PendingIntent pi, IAlarmListener rec) {
2903 return (operation != null)
2904 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09002905 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07002906 }
2907
2908 public boolean matches(String packageName) {
2909 return (operation != null)
2910 ? packageName.equals(operation.getTargetPackage())
2911 : packageName.equals(this.packageName);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002912 }
2913
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002914 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002915 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002916 StringBuilder sb = new StringBuilder(128);
2917 sb.append("Alarm{");
2918 sb.append(Integer.toHexString(System.identityHashCode(this)));
2919 sb.append(" type ");
2920 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002921 sb.append(" when ");
2922 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002923 sb.append(" ");
Christopher Tate14a7bb02015-10-01 10:24:31 -07002924 if (operation != null) {
2925 sb.append(operation.getTargetPackage());
2926 } else {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002927 sb.append(packageName);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002928 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002929 sb.append('}');
2930 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002931 }
2932
Kweku Adams61e03292017-10-19 14:27:12 -07002933 public void dump(PrintWriter pw, String prefix, long nowELAPSED, long nowRTC,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002934 SimpleDateFormat sdf) {
2935 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002936 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002937 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002938 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
2939 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002940 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002941 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002942 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002943 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002944 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002945 }
2946 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002947 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002948 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002949 pw.print(" count="); pw.print(count);
2950 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002951 if (alarmClock != null) {
2952 pw.print(prefix); pw.println("Alarm clock:");
2953 pw.print(prefix); pw.print(" triggerTime=");
2954 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
2955 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
2956 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002957 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002958 if (listener != null) {
2959 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
2960 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002961 }
Kweku Adams61e03292017-10-19 14:27:12 -07002962
2963 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
2964 long nowRTC) {
2965 final long token = proto.start(fieldId);
2966
2967 proto.write(AlarmProto.TAG, statsTag);
2968 proto.write(AlarmProto.TYPE, type);
2969 proto.write(AlarmProto.WHEN_ELAPSED_MS, whenElapsed - nowElapsed);
2970 proto.write(AlarmProto.WINDOW_LENGTH_MS, windowLength);
2971 proto.write(AlarmProto.REPEAT_INTERVAL_MS, repeatInterval);
2972 proto.write(AlarmProto.COUNT, count);
2973 proto.write(AlarmProto.FLAGS, flags);
2974 if (alarmClock != null) {
2975 alarmClock.writeToProto(proto, AlarmProto.ALARM_CLOCK);
2976 }
2977 if (operation != null) {
2978 operation.writeToProto(proto, AlarmProto.OPERATION);
2979 }
2980 if (listener != null) {
2981 proto.write(AlarmProto.LISTENER, listener.asBinder().toString());
2982 }
2983
2984 proto.end(token);
2985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002986 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002987
Christopher Tatee0a22b32013-07-11 14:43:13 -07002988 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
2989 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002990 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
2991 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002992 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07002993 break;
2994 }
2995
Christopher Tatee0a22b32013-07-11 14:43:13 -07002996 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002997 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
2998 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002999 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07003000 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003001 }
3002 }
3003
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003004 long currentNonWakeupFuzzLocked(long nowELAPSED) {
3005 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
3006 if (timeSinceOn < 5*60*1000) {
3007 // If the screen has been off for 5 minutes, only delay by at most two minutes.
3008 return 2*60*1000;
3009 } else if (timeSinceOn < 30*60*1000) {
3010 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
3011 return 15*60*1000;
3012 } else {
3013 // Otherwise, we will delay by at most an hour.
3014 return 60*60*1000;
3015 }
3016 }
3017
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003018 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003019 if (duration < 15*60*1000) {
3020 // If the duration until the time is less than 15 minutes, the maximum fuzz
3021 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003022 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003023 } else if (duration < 90*60*1000) {
3024 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
3025 return 15*60*1000;
3026 } else {
3027 // Otherwise, we will fuzz by at most half an hour.
3028 return 30*60*1000;
3029 }
3030 }
3031
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003032 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
3033 if (mInteractive) {
3034 return false;
3035 }
3036 if (mLastAlarmDeliveryTime <= 0) {
3037 return false;
3038 }
minho.choo649acab2014-12-12 16:13:55 +09003039 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003040 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
3041 // and the next delivery time is in the past, then just deliver them all. This
3042 // avoids bugs where we get stuck in a loop trying to poll for alarms.
3043 return false;
3044 }
3045 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
3046 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
3047 }
3048
3049 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
3050 mLastAlarmDeliveryTime = nowELAPSED;
3051 for (int i=0; i<triggerList.size(); i++) {
3052 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07003053 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003054 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07003055 if (localLOGV) {
3056 Slog.v(TAG, "sending alarm " + alarm);
3057 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07003058 if (RECORD_ALARMS_IN_HISTORY) {
3059 if (alarm.workSource != null && alarm.workSource.size() > 0) {
3060 for (int wi=0; wi<alarm.workSource.size(); wi++) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003061 ActivityManager.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003062 alarm.operation, alarm.workSource.get(wi), alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003063 }
3064 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003065 ActivityManager.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003066 alarm.operation, alarm.uid, alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003067 }
3068 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003069 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003070 } catch (RuntimeException e) {
3071 Slog.w(TAG, "Failure sending alarm.", e);
3072 }
3073 }
3074 }
3075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003076 private class AlarmThread extends Thread
3077 {
3078 public AlarmThread()
3079 {
3080 super("AlarmManager");
3081 }
Kweku Adams61e03292017-10-19 14:27:12 -07003082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003083 public void run()
3084 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003085 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3086
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003087 while (true)
3088 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003089 int result = waitForAlarm(mNativeData);
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003090 mLastWakeup = SystemClock.elapsedRealtime();
Dianne Hackborn390517b2013-05-30 15:03:32 -07003091
3092 triggerList.clear();
3093
Dianne Hackbornc3527222015-05-13 14:03:20 -07003094 final long nowRTC = System.currentTimeMillis();
3095 final long nowELAPSED = SystemClock.elapsedRealtime();
3096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003097 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003098 // The kernel can give us spurious time change notifications due to
3099 // small adjustments it makes internally; we want to filter those out.
3100 final long lastTimeChangeClockTime;
3101 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07003102 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003103 lastTimeChangeClockTime = mLastTimeChangeClockTime;
3104 expectedClockTime = lastTimeChangeClockTime
3105 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07003106 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003107 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
3108 || nowRTC > (expectedClockTime+1000)) {
3109 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07003110 // let's do it!
3111 if (DEBUG_BATCH) {
3112 Slog.v(TAG, "Time changed notification from kernel; rebatching");
3113 }
3114 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07003115 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003116 rebatchAllAlarms();
3117 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07003118 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003119 synchronized (mLock) {
3120 mNumTimeChanged++;
3121 mLastTimeChangeClockTime = nowRTC;
3122 mLastTimeChangeRealtime = nowELAPSED;
3123 }
3124 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
3125 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003126 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07003127 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
3128 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003129 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
3130
3131 // The world has changed on us, so we need to re-evaluate alarms
3132 // regardless of whether the kernel has told us one went off.
3133 result |= IS_WAKEUP_MASK;
3134 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003135 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003136
Dianne Hackbornc3527222015-05-13 14:03:20 -07003137 if (result != TIME_CHANGED_MASK) {
3138 // If this was anything besides just a time change, then figure what if
3139 // anything to do about alarms.
3140 synchronized (mLock) {
3141 if (localLOGV) Slog.v(
3142 TAG, "Checking for alarms... rtc=" + nowRTC
3143 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07003144
Dianne Hackbornc3527222015-05-13 14:03:20 -07003145 if (WAKEUP_STATS) {
3146 if ((result & IS_WAKEUP_MASK) != 0) {
3147 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
3148 int n = 0;
3149 for (WakeupEvent event : mRecentWakeups) {
3150 if (event.when > newEarliest) break;
3151 n++; // number of now-stale entries at the list head
3152 }
3153 for (int i = 0; i < n; i++) {
3154 mRecentWakeups.remove();
3155 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003156
Dianne Hackbornc3527222015-05-13 14:03:20 -07003157 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003158 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003159 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003160
3161 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3162 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
3163 // if there are no wakeup alarms and the screen is off, we can
3164 // delay what we have so far until the future.
3165 if (mPendingNonWakeupAlarms.size() == 0) {
3166 mStartCurrentDelayTime = nowELAPSED;
3167 mNextNonWakeupDeliveryTime = nowELAPSED
3168 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
3169 }
3170 mPendingNonWakeupAlarms.addAll(triggerList);
3171 mNumDelayedAlarms += triggerList.size();
3172 rescheduleKernelAlarmsLocked();
3173 updateNextAlarmClockLocked();
3174 } else {
3175 // now deliver the alarm intents; if there are pending non-wakeup
3176 // alarms, we need to merge them in to the list. note we don't
3177 // just deliver them first because we generally want non-wakeup
3178 // alarms delivered after wakeup alarms.
3179 rescheduleKernelAlarmsLocked();
3180 updateNextAlarmClockLocked();
3181 if (mPendingNonWakeupAlarms.size() > 0) {
3182 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
3183 triggerList.addAll(mPendingNonWakeupAlarms);
3184 Collections.sort(triggerList, mAlarmDispatchComparator);
3185 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3186 mTotalDelayTime += thisDelayTime;
3187 if (mMaxDelayTime < thisDelayTime) {
3188 mMaxDelayTime = thisDelayTime;
3189 }
3190 mPendingNonWakeupAlarms.clear();
3191 }
3192 deliverAlarmsLocked(triggerList, nowELAPSED);
3193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003194 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003195
3196 } else {
3197 // Just in case -- even though no wakeup flag was set, make sure
3198 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07003199 synchronized (mLock) {
3200 rescheduleKernelAlarmsLocked();
3201 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003202 }
3203 }
3204 }
3205 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003206
David Christieebe51fc2013-07-26 13:23:29 -07003207 /**
3208 * Attribute blame for a WakeLock.
3209 * @param pi PendingIntent to attribute blame to if ws is null.
3210 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003211 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07003212 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003213 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003214 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07003215 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003216 final boolean unimportant = pi == mTimeTickSender;
3217 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003218 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003219 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003220 } else {
3221 mWakeLock.setHistoryTag(null);
3222 }
3223 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07003224 if (ws != null) {
3225 mWakeLock.setWorkSource(ws);
3226 return;
3227 }
3228
Christopher Tate14a7bb02015-10-01 10:24:31 -07003229 final int uid = (knownUid >= 0)
3230 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003231 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07003232 if (uid >= 0) {
3233 mWakeLock.setWorkSource(new WorkSource(uid));
3234 return;
3235 }
3236 } catch (Exception e) {
3237 }
3238
3239 // Something went wrong; fall back to attributing the lock to the OS
3240 mWakeLock.setWorkSource(null);
3241 }
3242
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003243 private class AlarmHandler extends Handler {
3244 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003245 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
3246 public static final int LISTENER_TIMEOUT = 3;
3247 public static final int REPORT_ALARMS_ACTIVE = 4;
Kweku Adams61e03292017-10-19 14:27:12 -07003248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003249 public AlarmHandler() {
3250 }
Kweku Adams61e03292017-10-19 14:27:12 -07003251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003252 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003253 switch (msg.what) {
3254 case ALARM_EVENT: {
3255 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3256 synchronized (mLock) {
3257 final long nowRTC = System.currentTimeMillis();
3258 final long nowELAPSED = SystemClock.elapsedRealtime();
3259 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3260 updateNextAlarmClockLocked();
3261 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003262
Christopher Tate14a7bb02015-10-01 10:24:31 -07003263 // now trigger the alarms without the lock held
3264 for (int i=0; i<triggerList.size(); i++) {
3265 Alarm alarm = triggerList.get(i);
3266 try {
3267 alarm.operation.send();
3268 } catch (PendingIntent.CanceledException e) {
3269 if (alarm.repeatInterval > 0) {
3270 // This IntentSender is no longer valid, but this
3271 // is a repeating alarm, so toss the hoser.
3272 removeImpl(alarm.operation);
3273 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003274 }
3275 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003276 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003277 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003278
3279 case SEND_NEXT_ALARM_CLOCK_CHANGED:
3280 sendNextAlarmClockChanged();
3281 break;
3282
3283 case LISTENER_TIMEOUT:
3284 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
3285 break;
3286
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003287 case REPORT_ALARMS_ACTIVE:
3288 if (mLocalDeviceIdleController != null) {
3289 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
3290 }
3291 break;
3292
Christopher Tate14a7bb02015-10-01 10:24:31 -07003293 default:
3294 // nope, just ignore it
3295 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003296 }
3297 }
3298 }
Kweku Adams61e03292017-10-19 14:27:12 -07003299
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003300 class ClockReceiver extends BroadcastReceiver {
3301 public ClockReceiver() {
3302 IntentFilter filter = new IntentFilter();
3303 filter.addAction(Intent.ACTION_TIME_TICK);
3304 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003305 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003306 }
Kweku Adams61e03292017-10-19 14:27:12 -07003307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003308 @Override
3309 public void onReceive(Context context, Intent intent) {
3310 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07003311 if (DEBUG_BATCH) {
3312 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
3313 }
3314 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003315 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
3316 // Since the kernel does not keep track of DST, we need to
3317 // reset the TZ information at the beginning of each day
3318 // based off of the current Zone gmt offset + userspace tracked
3319 // daylight savings information.
3320 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02003321 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003322 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07003323 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003324 }
3325 }
Kweku Adams61e03292017-10-19 14:27:12 -07003326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003327 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07003328 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09003329 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07003330
3331 // Schedule this event for the amount of time that it would take to get to
3332 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09003333 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07003334
David Christieebe51fc2013-07-26 13:23:29 -07003335 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08003336 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003337 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
3338 null, Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003339 }
Christopher Tate385e4982013-07-23 18:22:29 -07003340
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003341 public void scheduleDateChangedEvent() {
3342 Calendar calendar = Calendar.getInstance();
3343 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07003344 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003345 calendar.set(Calendar.MINUTE, 0);
3346 calendar.set(Calendar.SECOND, 0);
3347 calendar.set(Calendar.MILLISECOND, 0);
3348 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07003349
3350 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003351 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
3352 AlarmManager.FLAG_STANDALONE, workSource, null,
3353 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003354 }
3355 }
Kweku Adams61e03292017-10-19 14:27:12 -07003356
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003357 class InteractiveStateReceiver extends BroadcastReceiver {
3358 public InteractiveStateReceiver() {
3359 IntentFilter filter = new IntentFilter();
3360 filter.addAction(Intent.ACTION_SCREEN_OFF);
3361 filter.addAction(Intent.ACTION_SCREEN_ON);
3362 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
3363 getContext().registerReceiver(this, filter);
3364 }
3365
3366 @Override
3367 public void onReceive(Context context, Intent intent) {
3368 synchronized (mLock) {
3369 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
3370 }
3371 }
3372 }
3373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003374 class UninstallReceiver extends BroadcastReceiver {
3375 public UninstallReceiver() {
3376 IntentFilter filter = new IntentFilter();
3377 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
3378 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003379 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003380 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08003381 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003382 // Register for events related to sdcard installation.
3383 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08003384 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003385 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003386 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003387 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003388 }
Kweku Adams61e03292017-10-19 14:27:12 -07003389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003390 @Override
3391 public void onReceive(Context context, Intent intent) {
3392 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003393 String action = intent.getAction();
3394 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003395 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
3396 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
3397 for (String packageName : pkgList) {
3398 if (lookForPackageLocked(packageName)) {
3399 setResultCode(Activity.RESULT_OK);
3400 return;
3401 }
3402 }
3403 return;
3404 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003405 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003406 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
3407 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
3408 if (userHandle >= 0) {
3409 removeUserLocked(userHandle);
3410 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003411 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
3412 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
3413 if (uid >= 0) {
3414 mLastAllowWhileIdleDispatch.delete(uid);
3415 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003416 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08003417 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
3418 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
3419 // This package is being updated; don't kill its alarms.
3420 return;
3421 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003422 Uri data = intent.getData();
3423 if (data != null) {
3424 String pkg = data.getSchemeSpecificPart();
3425 if (pkg != null) {
3426 pkgList = new String[]{pkg};
3427 }
3428 }
3429 }
3430 if (pkgList != null && (pkgList.length > 0)) {
3431 for (String pkg : pkgList) {
3432 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07003433 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003434 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
3435 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
3436 if (uidStats.remove(pkg) != null) {
3437 if (uidStats.size() <= 0) {
3438 mBroadcastStats.removeAt(i);
3439 }
3440 }
3441 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003443 }
3444 }
3445 }
3446 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003447
3448 final class UidObserver extends IUidObserver.Stub {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003449 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003450 }
3451
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003452 @Override public void onUidGone(int uid, boolean disabled) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003453 synchronized (mLock) {
3454 if (disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -08003455 removeForStoppedLocked(uid);
3456 }
3457 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003458 }
3459
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003460 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003461 }
3462
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003463 @Override public void onUidIdle(int uid, boolean disabled) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003464 synchronized (mLock) {
3465 if (disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -08003466 removeForStoppedLocked(uid);
3467 }
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08003468 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003469 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003470
3471 @Override public void onUidCachedChanged(int uid, boolean cached) {
3472 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003473 };
3474
Makoto Onuki2206af32017-11-21 16:25:35 -08003475
3476 private final Listener mForceAppStandbyListener = new Listener() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003477 @Override
Makoto Onuki2206af32017-11-21 16:25:35 -08003478 public void unblockAllUnrestrictedAlarms() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003479 synchronized (mLock) {
Makoto Onuki2206af32017-11-21 16:25:35 -08003480 sendAllUnrestrictedPendingBackgroundAlarmsLocked();
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003481 }
3482 }
Makoto Onuki2206af32017-11-21 16:25:35 -08003483
3484 @Override
3485 public void unblockAlarmsForUid(int uid) {
3486 synchronized (mLock) {
3487 sendPendingBackgroundAlarmsLocked(uid, null);
3488 }
3489 }
3490
3491 @Override
3492 public void unblockAlarmsForUidPackage(int uid, String packageName) {
3493 synchronized (mLock) {
3494 sendPendingBackgroundAlarmsLocked(uid, packageName);
3495 }
3496 }
3497 };
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003498
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003499 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003500 String pkg = pi.getCreatorPackage();
3501 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003502 return getStatsLocked(uid, pkg);
3503 }
3504
3505 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003506 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
3507 if (uidStats == null) {
3508 uidStats = new ArrayMap<String, BroadcastStats>();
3509 mBroadcastStats.put(uid, uidStats);
3510 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003511 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003512 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003513 bs = new BroadcastStats(uid, pkgName);
3514 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003515 }
3516 return bs;
3517 }
Dianne Hackborn81038902012-11-26 17:04:09 -08003518
Christopher Tate21e9f192017-08-08 13:49:11 -07003519 /**
3520 * Canonical count of (operation.send() - onSendFinished()) and
3521 * listener send/complete/timeout invocations.
3522 * Guarded by the usual lock.
3523 */
3524 @GuardedBy("mLock")
3525 private int mSendCount = 0;
3526 @GuardedBy("mLock")
Christopher Tateeabba732017-08-17 17:12:52 -07003527 private int mSendFinishCount = 0;
3528 @GuardedBy("mLock")
Christopher Tate21e9f192017-08-08 13:49:11 -07003529 private int mListenerCount = 0;
Christopher Tateeabba732017-08-17 17:12:52 -07003530 @GuardedBy("mLock")
3531 private int mListenerFinishCount = 0;
Christopher Tate21e9f192017-08-08 13:49:11 -07003532
Christopher Tate14a7bb02015-10-01 10:24:31 -07003533 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
Christopher Tate21e9f192017-08-08 13:49:11 -07003534
Christopher Tate14a7bb02015-10-01 10:24:31 -07003535 private InFlight removeLocked(PendingIntent pi, Intent intent) {
3536 for (int i = 0; i < mInFlight.size(); i++) {
Christopher Tatedb9ae422017-08-21 11:24:30 -07003537 if (mInFlight.get(i).mPendingIntent == pi) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003538 return mInFlight.remove(i);
3539 }
3540 }
3541 mLog.w("No in-flight alarm for " + pi + " " + intent);
3542 return null;
3543 }
3544
3545 private InFlight removeLocked(IBinder listener) {
3546 for (int i = 0; i < mInFlight.size(); i++) {
3547 if (mInFlight.get(i).mListener == listener) {
3548 return mInFlight.remove(i);
3549 }
3550 }
3551 mLog.w("No in-flight alarm for listener " + listener);
3552 return null;
3553 }
3554
3555 private void updateStatsLocked(InFlight inflight) {
3556 final long nowELAPSED = SystemClock.elapsedRealtime();
3557 BroadcastStats bs = inflight.mBroadcastStats;
3558 bs.nesting--;
3559 if (bs.nesting <= 0) {
3560 bs.nesting = 0;
3561 bs.aggregateTime += nowELAPSED - bs.startTime;
3562 }
3563 FilterStats fs = inflight.mFilterStats;
3564 fs.nesting--;
3565 if (fs.nesting <= 0) {
3566 fs.nesting = 0;
3567 fs.aggregateTime += nowELAPSED - fs.startTime;
3568 }
3569 if (RECORD_ALARMS_IN_HISTORY) {
3570 if (inflight.mWorkSource != null && inflight.mWorkSource.size() > 0) {
3571 for (int wi=0; wi<inflight.mWorkSource.size(); wi++) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003572 ActivityManager.noteAlarmFinish(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003573 inflight.mPendingIntent, inflight.mWorkSource.get(wi), inflight.mTag);
3574 }
3575 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003576 ActivityManager.noteAlarmFinish(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003577 inflight.mPendingIntent, inflight.mUid, inflight.mTag);
3578 }
3579 }
3580 }
3581
3582 private void updateTrackingLocked(InFlight inflight) {
3583 if (inflight != null) {
3584 updateStatsLocked(inflight);
3585 }
3586 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08003587 if (DEBUG_WAKELOCK) {
3588 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
3589 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003590 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003591 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003592 mWakeLock.release();
3593 if (mInFlight.size() > 0) {
3594 mLog.w("Finished all dispatches with " + mInFlight.size()
3595 + " remaining inflights");
3596 for (int i=0; i<mInFlight.size(); i++) {
3597 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
3598 }
3599 mInFlight.clear();
3600 }
3601 } else {
3602 // the next of our alarms is now in flight. reattribute the wakelock.
3603 if (mInFlight.size() > 0) {
3604 InFlight inFlight = mInFlight.get(0);
3605 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
3606 inFlight.mAlarmType, inFlight.mTag, -1, false);
3607 } else {
3608 // should never happen
3609 mLog.w("Alarm wakelock still held but sent queue empty");
3610 mWakeLock.setWorkSource(null);
3611 }
3612 }
3613 }
3614
3615 /**
3616 * Callback that arrives when a direct-call alarm reports that delivery has finished
3617 */
3618 @Override
3619 public void alarmComplete(IBinder who) {
3620 if (who == null) {
Christopher Tate21e9f192017-08-08 13:49:11 -07003621 mLog.w("Invalid alarmComplete: uid=" + Binder.getCallingUid()
Christopher Tate14a7bb02015-10-01 10:24:31 -07003622 + " pid=" + Binder.getCallingPid());
3623 return;
3624 }
3625
3626 final long ident = Binder.clearCallingIdentity();
3627 try {
3628 synchronized (mLock) {
3629 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
3630 InFlight inflight = removeLocked(who);
3631 if (inflight != null) {
3632 if (DEBUG_LISTENER_CALLBACK) {
3633 Slog.i(TAG, "alarmComplete() from " + who);
3634 }
3635 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07003636 mListenerFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003637 } else {
3638 // Delivery timed out, and the timeout handling already took care of
3639 // updating our tracking here, so we needn't do anything further.
3640 if (DEBUG_LISTENER_CALLBACK) {
3641 Slog.i(TAG, "Late alarmComplete() from " + who);
3642 }
3643 }
3644 }
3645 } finally {
3646 Binder.restoreCallingIdentity(ident);
3647 }
3648 }
3649
3650 /**
3651 * Callback that arrives when a PendingIntent alarm has finished delivery
3652 */
3653 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003654 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
3655 String resultData, Bundle resultExtras) {
3656 synchronized (mLock) {
Christopher Tateeabba732017-08-17 17:12:52 -07003657 mSendFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003658 updateTrackingLocked(removeLocked(pi, intent));
3659 }
3660 }
3661
3662 /**
3663 * Timeout of a direct-call alarm delivery
3664 */
3665 public void alarmTimedOut(IBinder who) {
3666 synchronized (mLock) {
3667 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08003668 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003669 // TODO: implement ANR policy for the target
3670 if (DEBUG_LISTENER_CALLBACK) {
3671 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003672 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003673 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07003674 mListenerFinishCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08003675 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003676 if (DEBUG_LISTENER_CALLBACK) {
3677 Slog.i(TAG, "Spurious timeout of listener " + who);
3678 }
Christopher Tate21e9f192017-08-08 13:49:11 -07003679 mLog.w("Spurious timeout of listener " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003680 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003681 }
3682 }
3683
3684 /**
3685 * Deliver an alarm and set up the post-delivery handling appropriately
3686 */
3687 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
3688 if (alarm.operation != null) {
3689 // PendingIntent alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07003690 mSendCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003691 try {
3692 alarm.operation.send(getContext(), 0,
3693 mBackgroundIntent.putExtra(
3694 Intent.EXTRA_ALARM_COUNT, alarm.count),
3695 mDeliveryTracker, mHandler, null,
3696 allowWhileIdle ? mIdleOptions : null);
3697 } catch (PendingIntent.CanceledException e) {
3698 if (alarm.repeatInterval > 0) {
3699 // This IntentSender is no longer valid, but this
3700 // is a repeating alarm, so toss it
3701 removeImpl(alarm.operation);
3702 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003703 // No actual delivery was possible, so the delivery tracker's
3704 // 'finished' callback won't be invoked. We also don't need
3705 // to do any wakelock or stats tracking, so we have nothing
3706 // left to do here but go on to the next thing.
Christopher Tateeabba732017-08-17 17:12:52 -07003707 mSendFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08003708 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003709 }
3710 } else {
3711 // Direct listener callback alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07003712 mListenerCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003713 try {
3714 if (DEBUG_LISTENER_CALLBACK) {
3715 Slog.v(TAG, "Alarm to uid=" + alarm.uid
3716 + " listener=" + alarm.listener.asBinder());
3717 }
3718 alarm.listener.doAlarm(this);
3719 mHandler.sendMessageDelayed(
3720 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
3721 alarm.listener.asBinder()),
3722 mConstants.LISTENER_TIMEOUT);
3723 } catch (Exception e) {
3724 if (DEBUG_LISTENER_CALLBACK) {
3725 Slog.i(TAG, "Alarm undeliverable to listener "
3726 + alarm.listener.asBinder(), e);
3727 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003728 // As in the PendingIntent.CanceledException case, delivery of the
3729 // alarm was not possible, so we have no wakelock or timeout or
3730 // stats management to do. It threw before we posted the delayed
3731 // timeout message, so we're done here.
Christopher Tateeabba732017-08-17 17:12:52 -07003732 mListenerFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08003733 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003734 }
3735 }
3736
3737 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08003738 if (DEBUG_WAKELOCK) {
3739 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
3740 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003741 if (mBroadcastRefCount == 0) {
3742 setWakelockWorkSource(alarm.operation, alarm.workSource,
3743 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
3744 true);
3745 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003746 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003747 }
3748 final InFlight inflight = new InFlight(AlarmManagerService.this,
3749 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
3750 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
3751 mInFlight.add(inflight);
3752 mBroadcastRefCount++;
3753
3754 if (allowWhileIdle) {
3755 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
3756 mLastAllowWhileIdleDispatch.put(alarm.uid, nowELAPSED);
3757 if (RECORD_DEVICE_IDLE_ALARMS) {
3758 IdleDispatchEntry ent = new IdleDispatchEntry();
3759 ent.uid = alarm.uid;
3760 ent.pkg = alarm.packageName;
3761 ent.tag = alarm.statsTag;
3762 ent.op = "DELIVER";
3763 ent.elapsedRealtime = nowELAPSED;
3764 mAllowWhileIdleDispatches.add(ent);
3765 }
3766 }
3767
3768 final BroadcastStats bs = inflight.mBroadcastStats;
3769 bs.count++;
3770 if (bs.nesting == 0) {
3771 bs.nesting = 1;
3772 bs.startTime = nowELAPSED;
3773 } else {
3774 bs.nesting++;
3775 }
3776 final FilterStats fs = inflight.mFilterStats;
3777 fs.count++;
3778 if (fs.nesting == 0) {
3779 fs.nesting = 1;
3780 fs.startTime = nowELAPSED;
3781 } else {
3782 fs.nesting++;
3783 }
3784 if (alarm.type == ELAPSED_REALTIME_WAKEUP
3785 || alarm.type == RTC_WAKEUP) {
3786 bs.numWakeup++;
3787 fs.numWakeup++;
3788 if (alarm.workSource != null && alarm.workSource.size() > 0) {
3789 for (int wi=0; wi<alarm.workSource.size(); wi++) {
Christopher Tate0029f572016-06-14 10:16:28 -07003790 final String wsName = alarm.workSource.getName(wi);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003791 ActivityManager.noteWakeupAlarm(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003792 alarm.operation, alarm.workSource.get(wi),
Christopher Tate0029f572016-06-14 10:16:28 -07003793 (wsName != null) ? wsName : alarm.packageName,
3794 alarm.statsTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08003795 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003796 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003797 ActivityManager.noteWakeupAlarm(
Joe Onorato78bcdf92016-05-09 10:10:29 -07003798 alarm.operation, alarm.uid, alarm.packageName, alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003799 }
3800 }
3801 }
3802 }
3803}