blob: 4c08f6290c6cf2cbeb84a3fcce6ef6abfc5ba5df [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;
Suprabh Shukladb6bf662017-08-30 15:41:53 -070049import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.os.SystemClock;
51import android.os.SystemProperties;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070052import android.os.UserHandle;
Christopher Tatec4a07d12012-04-06 14:19:13 -070053import android.os.WorkSource;
Adrian Roosc42a1e12014-07-07 23:35:53 +020054import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.text.TextUtils;
Adrian Roosc42a1e12014-07-07 23:35:53 +020056import android.text.format.DateFormat;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080057import android.util.ArrayMap;
Suprabh Shukladb6bf662017-08-30 15:41:53 -070058import android.util.ArraySet;
Dianne Hackborna750a632015-06-16 17:18:23 -070059import android.util.KeyValueListParser;
Adrian Roosc42a1e12014-07-07 23:35:53 +020060import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080061import android.util.Slog;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080062import android.util.SparseArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +020063import android.util.SparseBooleanArray;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -070064import android.util.SparseLongArray;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070065import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066
Christopher Tate4cb338d2013-07-26 13:11:31 -070067import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import java.io.FileDescriptor;
69import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070070import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -080072import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import java.util.Calendar;
74import java.util.Collections;
75import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -050076import java.util.Date;
Christopher Tate1590f1e2014-10-02 17:27:57 -070077import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -070078import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +020079import java.util.Locale;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070080import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import java.util.TimeZone;
John Spurlock604a5ee2015-06-01 12:27:22 -040082import java.util.TreeSet;
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;
Suprabh Shukladb6bf662017-08-30 15:41:53 -070090import com.android.internal.app.IAppOpsCallback;
91import com.android.internal.app.IAppOpsService;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060092import com.android.internal.util.DumpUtils;
Dianne Hackborn81038902012-11-26 17:04:09 -080093import com.android.internal.util.LocalLog;
94
Adam Lesinski182f73f2013-12-05 16:48:06 -080095class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -070096 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
97 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -080098 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -070099 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800100 static final int TIME_CHANGED_MASK = 1 << 16;
101 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -0800102
Christopher Tatee0a22b32013-07-11 14:43:13 -0700103 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -0800104 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -0800105
Adam Lesinski182f73f2013-12-05 16:48:06 -0800106 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -0800107 static final boolean localLOGV = false;
108 static final boolean DEBUG_BATCH = localLOGV || false;
109 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200110 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700111 static final boolean DEBUG_LISTENER_CALLBACK = localLOGV || false;
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800112 static final boolean DEBUG_WAKELOCK = localLOGV || false;
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700113 static final boolean DEBUG_BG_LIMIT = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700114 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700115 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800116 static final int ALARM_EVENT = 1;
117 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200118
Christopher Tate14a7bb02015-10-01 10:24:31 -0700119 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800121 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700122
Adam Lesinski182f73f2013-12-05 16:48:06 -0800123 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700124
Christopher Tate24cd46f2016-02-02 14:28:01 -0800125 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT =
126 new Intent(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED)
Christopher Tate50191db2017-05-09 16:02:25 -0700127 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
128 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Adrian Roosc42a1e12014-07-07 23:35:53 +0200129
Adam Lesinski182f73f2013-12-05 16:48:06 -0800130 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800131
Christopher Tate14a7bb02015-10-01 10:24:31 -0700132 AppOpsManager mAppOps;
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700133 IAppOpsService mAppOpsService;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800134 DeviceIdleController.LocalService mLocalDeviceIdleController;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700135
Adam Lesinski182f73f2013-12-05 16:48:06 -0800136 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800137
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700138 ArraySet<String> mForcedAppStandbyPackages = new ArraySet<>();
139 SparseBooleanArray mForegroundUids = new SparseBooleanArray();
140 // List of alarms per uid deferred due to user applied background restrictions on the source app
141 SparseArray<ArrayList<Alarm>> mPendingBackgroundAlarms = new SparseArray<>();
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800142 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800143 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700144 private long mNextNonWakeup;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -0700145 private long mLastWakeupSet;
146 private long mLastWakeup;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800147 int mBroadcastRefCount = 0;
148 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700149 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700150 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
151 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800152 final AlarmHandler mHandler = new AlarmHandler();
153 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700154 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700156 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800157 PendingIntent mTimeTickSender;
158 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700159 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700160 boolean mInteractive = true;
161 long mNonInteractiveStartTime;
162 long mNonInteractiveTime;
163 long mLastAlarmDeliveryTime;
164 long mStartCurrentDelayTime;
165 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700166 long mLastTimeChangeClockTime;
167 long mLastTimeChangeRealtime;
Dianne Hackborna750a632015-06-16 17:18:23 -0700168 long mAllowWhileIdleMinTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700169 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800170
Christopher Tatebb9cce52017-04-18 14:19:43 -0700171 // Bookkeeping about the identity of the "System UI" package, determined at runtime.
172
173 /**
174 * This permission must be defined by the canonical System UI package,
175 * with protection level "signature".
176 */
177 private static final String SYSTEM_UI_SELF_PERMISSION =
178 "android.permission.systemui.IDENTITY";
179
180 /**
181 * At boot we use SYSTEM_UI_SELF_PERMISSION to look up the definer's uid.
182 */
183 int mSystemUiUid;
184
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700185 /**
Dianne Hackborn262ae5c2016-02-10 16:28:29 -0800186 * The current set of user whitelisted apps for device idle mode, meaning these are allowed
187 * to freely schedule alarms.
188 */
189 int[] mDeviceIdleUserWhitelist = new int[0];
190
191 /**
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700192 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
193 * used to determine the earliest we can dispatch the next such alarm.
194 */
195 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
196
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700197 final static class IdleDispatchEntry {
198 int uid;
199 String pkg;
200 String tag;
201 String op;
202 long elapsedRealtime;
203 long argRealtime;
204 }
205 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
206
Dianne Hackborna750a632015-06-16 17:18:23 -0700207 /**
208 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
209 */
210 Bundle mIdleOptions;
211
Jose Lima235510e2014-08-13 12:50:01 -0700212 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
213 new SparseArray<>();
214 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
215 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200216 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
217 new SparseBooleanArray();
218 private boolean mNextAlarmClockMayChange;
219
220 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700221 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
222 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200223
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 }
358 }
359
360 final Constants mConstants;
361
Christopher Tate1590f1e2014-10-02 17:27:57 -0700362 // Alarm delivery ordering bookkeeping
363 static final int PRIO_TICK = 0;
364 static final int PRIO_WAKEUP = 1;
365 static final int PRIO_NORMAL = 2;
366
Dianne Hackborna750a632015-06-16 17:18:23 -0700367 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700368 int seq;
369 int priority;
370
371 PriorityClass() {
372 seq = mCurrentSeq - 1;
373 priority = PRIO_NORMAL;
374 }
375 }
376
Dianne Hackborna750a632015-06-16 17:18:23 -0700377 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700378 int mCurrentSeq = 0;
379
Dianne Hackborna750a632015-06-16 17:18:23 -0700380 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700381 public long when;
382 public int uid;
383 public String action;
384
385 public WakeupEvent(long theTime, int theUid, String theAction) {
386 when = theTime;
387 uid = theUid;
388 action = theAction;
389 }
390 }
391
Adam Lesinski182f73f2013-12-05 16:48:06 -0800392 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
393 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700394
Adrian Roosc42a1e12014-07-07 23:35:53 +0200395 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700396 long start; // These endpoints are always in ELAPSED
397 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700398 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700399
400 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
401
402 Batch() {
403 start = 0;
404 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700405 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700406 }
407
408 Batch(Alarm seed) {
409 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700410 end = seed.maxWhenElapsed;
411 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700412 alarms.add(seed);
413 }
414
415 int size() {
416 return alarms.size();
417 }
418
419 Alarm get(int index) {
420 return alarms.get(index);
421 }
422
423 boolean canHold(long whenElapsed, long maxWhen) {
424 return (end >= whenElapsed) && (start <= maxWhen);
425 }
426
427 boolean add(Alarm alarm) {
428 boolean newStart = false;
429 // narrows the batch if necessary; presumes that canHold(alarm) is true
430 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
431 if (index < 0) {
432 index = 0 - index - 1;
433 }
434 alarms.add(index, alarm);
435 if (DEBUG_BATCH) {
436 Slog.v(TAG, "Adding " + alarm + " to " + this);
437 }
438 if (alarm.whenElapsed > start) {
439 start = alarm.whenElapsed;
440 newStart = true;
441 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700442 if (alarm.maxWhenElapsed < end) {
443 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700444 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700445 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700446
447 if (DEBUG_BATCH) {
448 Slog.v(TAG, " => now " + this);
449 }
450 return newStart;
451 }
452
Christopher Tate14a7bb02015-10-01 10:24:31 -0700453 boolean remove(final PendingIntent operation, final IAlarmListener listener) {
454 if (operation == null && listener == null) {
455 if (localLOGV) {
456 Slog.w(TAG, "requested remove() of null operation",
457 new RuntimeException("here"));
458 }
459 return false;
460 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700461 boolean didRemove = false;
462 long newStart = 0; // recalculate endpoints as we go
463 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700464 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700465 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700466 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700467 if (alarm.matches(operation, listener)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700468 alarms.remove(i);
469 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200470 if (alarm.alarmClock != null) {
471 mNextAlarmClockMayChange = true;
472 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700473 } else {
474 if (alarm.whenElapsed > newStart) {
475 newStart = alarm.whenElapsed;
476 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700477 if (alarm.maxWhenElapsed < newEnd) {
478 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700479 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700480 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700481 i++;
482 }
483 }
484 if (didRemove) {
485 // commit the new batch bounds
486 start = newStart;
487 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700488 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700489 }
490 return didRemove;
491 }
492
493 boolean remove(final String packageName) {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700494 if (packageName == null) {
495 if (localLOGV) {
496 Slog.w(TAG, "requested remove() of null packageName",
497 new RuntimeException("here"));
498 }
499 return false;
500 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700501 boolean didRemove = false;
502 long newStart = 0; // recalculate endpoints as we go
503 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700504 int newFlags = 0;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700505 for (int i = alarms.size()-1; i >= 0; i--) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700506 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700507 if (alarm.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700508 alarms.remove(i);
509 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200510 if (alarm.alarmClock != null) {
511 mNextAlarmClockMayChange = true;
512 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700513 } else {
514 if (alarm.whenElapsed > newStart) {
515 newStart = alarm.whenElapsed;
516 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700517 if (alarm.maxWhenElapsed < newEnd) {
518 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700519 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700520 newFlags |= alarm.flags;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700521 }
522 }
523 if (didRemove) {
524 // commit the new batch bounds
525 start = newStart;
526 end = newEnd;
527 flags = newFlags;
528 }
529 return didRemove;
530 }
531
532 boolean removeForStopped(final int uid) {
533 boolean didRemove = false;
534 long newStart = 0; // recalculate endpoints as we go
535 long newEnd = Long.MAX_VALUE;
536 int newFlags = 0;
537 for (int i = alarms.size()-1; i >= 0; i--) {
538 Alarm alarm = alarms.get(i);
539 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800540 if (alarm.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
541 uid, alarm.packageName)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700542 alarms.remove(i);
543 didRemove = true;
544 if (alarm.alarmClock != null) {
545 mNextAlarmClockMayChange = true;
546 }
547 } else {
548 if (alarm.whenElapsed > newStart) {
549 newStart = alarm.whenElapsed;
550 }
551 if (alarm.maxWhenElapsed < newEnd) {
552 newEnd = alarm.maxWhenElapsed;
553 }
554 newFlags |= alarm.flags;
555 }
556 } catch (RemoteException e) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700557 }
558 }
559 if (didRemove) {
560 // commit the new batch bounds
561 start = newStart;
562 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700563 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700564 }
565 return didRemove;
566 }
567
568 boolean remove(final int userHandle) {
569 boolean didRemove = false;
570 long newStart = 0; // recalculate endpoints as we go
571 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700572 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700573 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700574 if (UserHandle.getUserId(alarm.creatorUid) == userHandle) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700575 alarms.remove(i);
576 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200577 if (alarm.alarmClock != null) {
578 mNextAlarmClockMayChange = true;
579 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700580 } else {
581 if (alarm.whenElapsed > newStart) {
582 newStart = alarm.whenElapsed;
583 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700584 if (alarm.maxWhenElapsed < newEnd) {
585 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700586 }
587 i++;
588 }
589 }
590 if (didRemove) {
591 // commit the new batch bounds
592 start = newStart;
593 end = newEnd;
594 }
595 return didRemove;
596 }
597
598 boolean hasPackage(final String packageName) {
599 final int N = alarms.size();
600 for (int i = 0; i < N; i++) {
601 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700602 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700603 return true;
604 }
605 }
606 return false;
607 }
608
609 boolean hasWakeups() {
610 final int N = alarms.size();
611 for (int i = 0; i < N; i++) {
612 Alarm a = alarms.get(i);
613 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
614 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
615 return true;
616 }
617 }
618 return false;
619 }
620
621 @Override
622 public String toString() {
623 StringBuilder b = new StringBuilder(40);
624 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
625 b.append(" num="); b.append(size());
626 b.append(" start="); b.append(start);
627 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700628 if (flags != 0) {
629 b.append(" flgs=0x");
630 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700631 }
632 b.append('}');
633 return b.toString();
634 }
635 }
636
637 static class BatchTimeOrder implements Comparator<Batch> {
638 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800639 long when1 = b1.start;
640 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800641 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700642 return 1;
643 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800644 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700645 return -1;
646 }
647 return 0;
648 }
649 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800650
651 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
652 @Override
653 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700654 // priority class trumps everything. TICK < WAKEUP < NORMAL
655 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
656 return -1;
657 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
658 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800659 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700660
661 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800662 if (lhs.whenElapsed < rhs.whenElapsed) {
663 return -1;
664 } else if (lhs.whenElapsed > rhs.whenElapsed) {
665 return 1;
666 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700667
668 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800669 return 0;
670 }
671 };
672
Christopher Tate1590f1e2014-10-02 17:27:57 -0700673 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
674 final int N = alarms.size();
675 for (int i = 0; i < N; i++) {
676 Alarm a = alarms.get(i);
677
678 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700679 if (a.operation != null
680 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700681 alarmPrio = PRIO_TICK;
682 } else if (a.wakeup) {
683 alarmPrio = PRIO_WAKEUP;
684 } else {
685 alarmPrio = PRIO_NORMAL;
686 }
687
688 PriorityClass packagePrio = a.priorityClass;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700689 String alarmPackage = (a.operation != null)
690 ? a.operation.getCreatorPackage()
691 : a.packageName;
692 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700693 if (packagePrio == null) {
694 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700695 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700696 }
697 a.priorityClass = packagePrio;
698
699 if (packagePrio.seq != mCurrentSeq) {
700 // first alarm we've seen in the current delivery generation from this package
701 packagePrio.priority = alarmPrio;
702 packagePrio.seq = mCurrentSeq;
703 } else {
704 // Multiple alarms from this package being delivered in this generation;
705 // bump the package's delivery class if it's warranted.
706 // TICK < WAKEUP < NORMAL
707 if (alarmPrio < packagePrio.priority) {
708 packagePrio.priority = alarmPrio;
709 }
710 }
711 }
712 }
713
Christopher Tatee0a22b32013-07-11 14:43:13 -0700714 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800715 static final long MIN_FUZZABLE_INTERVAL = 10000;
716 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700717 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
718
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700719 // 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 -0700720 // to run during this time are placed in mPendingWhileIdleAlarms
721 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700722 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700723 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700724
Jeff Brownb880d882014-02-10 19:47:07 -0800725 public AlarmManagerService(Context context) {
726 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700727 mConstants = new Constants(mHandler);
Jeff Brownb880d882014-02-10 19:47:07 -0800728 }
729
Christopher Tatee0a22b32013-07-11 14:43:13 -0700730 static long convertToElapsed(long when, int type) {
731 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
732 if (isRtc) {
733 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
734 }
735 return when;
736 }
737
738 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
739 // calculate the end of our nominal delivery window for the alarm.
740 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
741 // Current heuristic: batchable window is 75% of either the recurrence interval
742 // [for a periodic alarm] or of the time from now to the desired delivery time,
743 // with a minimum delay/interval of 10 seconds, under which we will simply not
744 // defer the alarm.
745 long futurity = (interval == 0)
746 ? (triggerAtTime - now)
747 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700748 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700749 futurity = 0;
750 }
751 return triggerAtTime + (long)(.75 * futurity);
752 }
753
754 // returns true if the batch was added at the head
755 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
756 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
757 if (index < 0) {
758 index = 0 - index - 1;
759 }
760 list.add(index, newBatch);
761 return (index == 0);
762 }
763
Christopher Tate385e4982013-07-23 18:22:29 -0700764 // Return the index of the matching batch, or -1 if none found.
765 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700766 final int N = mAlarmBatches.size();
767 for (int i = 0; i < N; i++) {
768 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700769 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700770 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700771 }
772 }
Christopher Tate385e4982013-07-23 18:22:29 -0700773 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700774 }
775
776 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
777 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700778 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700779 rebatchAllAlarmsLocked(true);
780 }
781 }
782
783 void rebatchAllAlarmsLocked(boolean doValidate) {
784 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
785 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700786 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700787 final long nowElapsed = SystemClock.elapsedRealtime();
788 final int oldBatches = oldSet.size();
789 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
790 Batch batch = oldSet.get(batchNum);
791 final int N = batch.size();
792 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700793 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700794 }
795 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700796 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
797 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
798 + " to " + mPendingIdleUntil);
799 if (mPendingIdleUntil == null) {
800 // Somehow we lost this... we need to restore all of the pending alarms.
801 restorePendingWhileIdleAlarmsLocked();
802 }
803 }
804 rescheduleKernelAlarmsLocked();
805 updateNextAlarmClockLocked();
806 }
807
808 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
809 a.when = a.origWhen;
810 long whenElapsed = convertToElapsed(a.when, a.type);
811 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700812 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700813 // Exact
814 maxElapsed = whenElapsed;
815 } else {
816 // Not exact. Preserve any explicit window, otherwise recalculate
817 // the window based on the alarm's new futurity. Note that this
818 // reflects a policy of preferring timely to deferred delivery.
819 maxElapsed = (a.windowLength > 0)
820 ? (whenElapsed + a.windowLength)
821 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
822 }
823 a.whenElapsed = whenElapsed;
824 a.maxWhenElapsed = maxElapsed;
825 setImplLocked(a, true, doValidate);
826 }
827
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700828 /**
829 * Sends alarms that were blocked due to user applied background restrictions - either because
830 * the user lifted those or the uid came to foreground.
831 *
832 * @param uid uid to filter on
833 * @param packageName package to filter on, or null for all packages in uid
834 */
835 void sendPendingBackgroundAlarmsLocked(int uid, String packageName) {
836 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(uid);
837 if (alarmsForUid == null || alarmsForUid.size() == 0) {
838 return;
839 }
840 final ArrayList<Alarm> alarmsToDeliver;
841 if (packageName != null) {
842 if (DEBUG_BG_LIMIT) {
843 Slog.d(TAG, "Sending blocked alarms for uid " + uid + ", package " + packageName);
844 }
845 alarmsToDeliver = new ArrayList<>();
846 for (int i = alarmsForUid.size() - 1; i >= 0; i--) {
847 final Alarm a = alarmsForUid.get(i);
848 if (a.matches(packageName)) {
849 alarmsToDeliver.add(alarmsForUid.remove(i));
850 }
851 }
852 if (alarmsForUid.size() == 0) {
853 mPendingBackgroundAlarms.remove(uid);
854 }
855 } else {
856 if (DEBUG_BG_LIMIT) {
857 Slog.d(TAG, "Sending blocked alarms for uid " + uid);
858 }
859 alarmsToDeliver = alarmsForUid;
860 mPendingBackgroundAlarms.remove(uid);
861 }
862 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
863 }
864
865 void sendPendingBackgroundAlarmsForAppIdLocked(int appId) {
866 final ArrayList<Alarm> alarmsToDeliver = new ArrayList<>();
867 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
868 final int uid = mPendingBackgroundAlarms.keyAt(i);
869 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
870 if (UserHandle.getAppId(uid) == appId) {
871 alarmsToDeliver.addAll(alarmsForUid);
872 mPendingBackgroundAlarms.removeAt(i);
873 }
874 }
875 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
876 }
877
878 private void deliverPendingBackgroundAlarmsLocked(ArrayList<Alarm> alarms, long nowELAPSED) {
879 final int N = alarms.size();
880 boolean hasWakeup = false;
881 for (int i = 0; i < N; i++) {
882 final Alarm alarm = alarms.get(i);
883 if (alarm.wakeup) {
884 hasWakeup = true;
885 }
886 alarm.count = 1;
887 // Recurring alarms may have passed several alarm intervals while the
888 // alarm was kept pending. Send the appropriate trigger count.
889 if (alarm.repeatInterval > 0) {
890 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
891 // Also schedule its next recurrence
892 final long delta = alarm.count * alarm.repeatInterval;
893 final long nextElapsed = alarm.whenElapsed + delta;
894 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
895 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
896 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
897 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
898 // Kernel alarms will be rescheduled as needed in setImplLocked
899 }
900 }
901 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
902 // No need to wakeup for non wakeup alarms
903 if (mPendingNonWakeupAlarms.size() == 0) {
904 mStartCurrentDelayTime = nowELAPSED;
905 mNextNonWakeupDeliveryTime = nowELAPSED
906 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
907 }
908 mPendingNonWakeupAlarms.addAll(alarms);
909 mNumDelayedAlarms += alarms.size();
910 } else {
911 if (DEBUG_BG_LIMIT) {
912 Slog.d(TAG, "Waking up to deliver pending blocked alarms");
913 }
914 // Since we are waking up, also deliver any pending non wakeup alarms we have.
915 if (mPendingNonWakeupAlarms.size() > 0) {
916 alarms.addAll(mPendingNonWakeupAlarms);
917 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
918 mTotalDelayTime += thisDelayTime;
919 if (mMaxDelayTime < thisDelayTime) {
920 mMaxDelayTime = thisDelayTime;
921 }
922 mPendingNonWakeupAlarms.clear();
923 }
924 calculateDeliveryPriorities(alarms);
925 Collections.sort(alarms, mAlarmDispatchComparator);
926 deliverAlarmsLocked(alarms, nowELAPSED);
927 }
928 }
929
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700930 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700931 if (RECORD_DEVICE_IDLE_ALARMS) {
932 IdleDispatchEntry ent = new IdleDispatchEntry();
933 ent.uid = 0;
934 ent.pkg = "FINISH IDLE";
935 ent.elapsedRealtime = SystemClock.elapsedRealtime();
936 mAllowWhileIdleDispatches.add(ent);
937 }
938
Dianne Hackborn35d54032015-04-23 10:30:43 -0700939 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700940 if (mPendingWhileIdleAlarms.size() > 0) {
941 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
942 mPendingWhileIdleAlarms = new ArrayList<>();
943 final long nowElapsed = SystemClock.elapsedRealtime();
944 for (int i=alarms.size() - 1; i >= 0; i--) {
945 Alarm a = alarms.get(i);
946 reAddAlarmLocked(a, nowElapsed, false);
947 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700948 }
Dianne Hackborn35d54032015-04-23 10:30:43 -0700949
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700950 // Make sure we are using the correct ALLOW_WHILE_IDLE min time.
Dianne Hackborna750a632015-06-16 17:18:23 -0700951 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700952
Dianne Hackborn35d54032015-04-23 10:30:43 -0700953 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700954 rescheduleKernelAlarmsLocked();
955 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -0700956
957 // And send a TIME_TICK right now, since it is important to get the UI updated.
958 try {
959 mTimeTickSender.send();
960 } catch (PendingIntent.CanceledException e) {
961 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700962 }
963
Christopher Tate14a7bb02015-10-01 10:24:31 -0700964 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -0800965 final PendingIntent mPendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -0700966 final long mWhenElapsed;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700967 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -0700968 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700969 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700970 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800971 final BroadcastStats mBroadcastStats;
972 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800973 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800974
Christopher Tate14a7bb02015-10-01 10:24:31 -0700975 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
976 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
977 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800978 mPendingIntent = pendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -0700979 mWhenElapsed = nowELAPSED;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700980 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -0700981 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700982 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700983 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700984 mBroadcastStats = (pendingIntent != null)
985 ? service.getStatsLocked(pendingIntent)
986 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700987 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -0800988 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700989 fs = new FilterStats(mBroadcastStats, mTag);
990 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -0800991 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700992 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -0800993 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800994 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800995 }
Makoto Onuki33955e12017-03-01 18:11:00 -0800996
997 @Override
998 public String toString() {
999 return "InFlight{"
1000 + "pendingIntent=" + mPendingIntent
Christopher Tateeabba732017-08-17 17:12:52 -07001001 + ", when=" + mWhenElapsed
Makoto Onuki33955e12017-03-01 18:11:00 -08001002 + ", workSource=" + mWorkSource
1003 + ", uid=" + mUid
1004 + ", tag=" + mTag
1005 + ", broadcastStats=" + mBroadcastStats
1006 + ", filterStats=" + mFilterStats
1007 + ", alarmType=" + mAlarmType
1008 + "}";
1009 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001011
Adam Lesinski182f73f2013-12-05 16:48:06 -08001012 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -08001013 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001014 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001015
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001016 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -08001018 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 int numWakeup;
1020 long startTime;
1021 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -08001022
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001023 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001024 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001025 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001026 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001027
1028 @Override
1029 public String toString() {
1030 return "FilterStats{"
1031 + "tag=" + mTag
1032 + ", lastTime=" + lastTime
1033 + ", aggregateTime=" + aggregateTime
1034 + ", count=" + count
1035 + ", numWakeup=" + numWakeup
1036 + ", startTime=" + startTime
1037 + ", nesting=" + nesting
1038 + "}";
1039 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001040 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001041
Adam Lesinski182f73f2013-12-05 16:48:06 -08001042 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001043 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001044 final String mPackageName;
1045
1046 long aggregateTime;
1047 int count;
1048 int numWakeup;
1049 long startTime;
1050 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001051 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -08001052
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001053 BroadcastStats(int uid, String packageName) {
1054 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001055 mPackageName = packageName;
1056 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001057
1058 @Override
1059 public String toString() {
1060 return "BroadcastStats{"
1061 + "uid=" + mUid
1062 + ", packageName=" + mPackageName
1063 + ", aggregateTime=" + aggregateTime
1064 + ", count=" + count
1065 + ", numWakeup=" + numWakeup
1066 + ", startTime=" + startTime
1067 + ", nesting=" + nesting
1068 + "}";
1069 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001070 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001071
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001072 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
1073 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001074
1075 int mNumDelayedAlarms = 0;
1076 long mTotalDelayTime = 0;
1077 long mMaxDelayTime = 0;
1078
Adam Lesinski182f73f2013-12-05 16:48:06 -08001079 @Override
1080 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001081 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001082 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001083
1084 // We have to set current TimeZone info to kernel
1085 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -08001086 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001087
Christopher Tate247571462017-04-10 11:45:05 -07001088 // Also sure that we're booting with a halfway sensible current time
1089 if (mNativeData != 0) {
1090 final long systemBuildTime = Environment.getRootDirectory().lastModified();
1091 if (System.currentTimeMillis() < systemBuildTime) {
1092 Slog.i(TAG, "Current time only " + System.currentTimeMillis()
1093 + ", advancing to build time " + systemBuildTime);
1094 setKernelTime(mNativeData, systemBuildTime);
1095 }
1096 }
1097
Christopher Tatebb9cce52017-04-18 14:19:43 -07001098 // Determine SysUI's uid
1099 final PackageManager packMan = getContext().getPackageManager();
1100 try {
1101 PermissionInfo sysUiPerm = packMan.getPermissionInfo(SYSTEM_UI_SELF_PERMISSION, 0);
1102 ApplicationInfo sysUi = packMan.getApplicationInfo(sysUiPerm.packageName, 0);
1103 if ((sysUi.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1104 mSystemUiUid = sysUi.uid;
1105 } else {
1106 Slog.e(TAG, "SysUI permission " + SYSTEM_UI_SELF_PERMISSION
1107 + " defined by non-privileged app " + sysUi.packageName
1108 + " - ignoring");
1109 }
1110 } catch (NameNotFoundException e) {
1111 }
1112
1113 if (mSystemUiUid <= 0) {
1114 Slog.wtf(TAG, "SysUI package not found!");
1115 }
1116
Adam Lesinski182f73f2013-12-05 16:48:06 -08001117 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001118 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001119
Adam Lesinski182f73f2013-12-05 16:48:06 -08001120 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001122 Intent.FLAG_RECEIVER_REGISTERED_ONLY
Chad Brubaker291df4f2017-03-14 10:23:02 -07001123 | Intent.FLAG_RECEIVER_FOREGROUND
1124 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001125 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001126 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001127 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1128 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001129 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001130 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131
1132 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -08001133 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 mClockReceiver.scheduleTimeTickEvent();
1135 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001136 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001137 mUninstallReceiver = new UninstallReceiver();
1138
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001139 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001140 AlarmThread waitThread = new AlarmThread();
1141 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001143 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001145
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001146 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001147 ActivityManager.getService().registerUidObserver(new UidObserver(),
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001148 ActivityManager.UID_OBSERVER_GONE | ActivityManager.UID_OBSERVER_IDLE
1149 | ActivityManager.UID_OBSERVER_ACTIVE,
1150 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001151 } catch (RemoteException e) {
1152 // ignored; both services live in system_server
1153 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001154 mAppOpsService = IAppOpsService.Stub.asInterface(
1155 ServiceManager.getService(Context.APP_OPS_SERVICE));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001156 publishBinderService(Context.ALARM_SERVICE, mService);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001157 publishLocalService(LocalService.class, new LocalService());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001159
1160 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001161 public void onBootPhase(int phase) {
1162 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1163 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -07001164 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001165 mLocalDeviceIdleController
1166 = LocalServices.getService(DeviceIdleController.LocalService.class);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001167 try {
1168 mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, null,
1169 new AppOpsWatcher());
1170 } catch (RemoteException rexc) {
1171 // Shouldn't happen as they are in the same process.
1172 Slog.e(TAG, "AppOps service not reachable", rexc);
1173 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001174 }
1175 }
1176
1177 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 protected void finalize() throws Throwable {
1179 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001180 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 } finally {
1182 super.finalize();
1183 }
1184 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001185
Adam Lesinski182f73f2013-12-05 16:48:06 -08001186 void setTimeZoneImpl(String tz) {
1187 if (TextUtils.isEmpty(tz)) {
1188 return;
David Christieebe51fc2013-07-26 13:23:29 -07001189 }
1190
Adam Lesinski182f73f2013-12-05 16:48:06 -08001191 TimeZone zone = TimeZone.getTimeZone(tz);
1192 // Prevent reentrant calls from stepping on each other when writing
1193 // the time zone property
1194 boolean timeZoneWasChanged = false;
1195 synchronized (this) {
1196 String current = SystemProperties.get(TIMEZONE_PROPERTY);
1197 if (current == null || !current.equals(zone.getID())) {
1198 if (localLOGV) {
1199 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
1200 }
1201 timeZoneWasChanged = true;
1202 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
1203 }
1204
1205 // Update the kernel timezone information
1206 // Kernel tracks time offsets as 'minutes west of GMT'
1207 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001208 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001209 }
1210
1211 TimeZone.setDefault(null);
1212
1213 if (timeZoneWasChanged) {
1214 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001215 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate5cdf9f82017-05-03 18:10:39 -07001216 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
Chad Brubaker291df4f2017-03-14 10:23:02 -07001217 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001218 intent.putExtra("time-zone", zone.getID());
1219 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1220 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001221 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001222
Adam Lesinski182f73f2013-12-05 16:48:06 -08001223 void removeImpl(PendingIntent operation) {
1224 if (operation == null) {
1225 return;
1226 }
1227 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001228 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001229 }
1230 }
1231
1232 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001233 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1234 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1235 int callingUid, String callingPackage) {
1236 // must be *either* PendingIntent or AlarmReceiver, but not both
1237 if ((operation == null && directReceiver == null)
1238 || (operation != null && directReceiver != null)) {
1239 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1240 // NB: previous releases failed silently here, so we are continuing to do the same
1241 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001242 return;
1243 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001244
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001245 // Sanity check the window length. This will catch people mistakenly
1246 // trying to pass an end-of-window timestamp rather than a duration.
1247 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1248 Slog.w(TAG, "Window length " + windowLength
1249 + "ms suspiciously long; limiting to 1 hour");
1250 windowLength = AlarmManager.INTERVAL_HOUR;
1251 }
1252
Christopher Tate498c6cb2014-11-17 16:09:27 -08001253 // Sanity check the recurrence interval. This will catch people who supply
1254 // seconds when the API expects milliseconds.
Dianne Hackborna750a632015-06-16 17:18:23 -07001255 final long minInterval = mConstants.MIN_INTERVAL;
1256 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001257 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001258 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001259 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001260 interval = minInterval;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001261 }
1262
Christopher Tatee0a22b32013-07-11 14:43:13 -07001263 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1264 throw new IllegalArgumentException("Invalid alarm type " + type);
1265 }
1266
Christopher Tate5f221e82013-07-30 17:13:15 -07001267 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001268 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001269 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001270 + " pid=" + what);
1271 triggerAtTime = 0;
1272 }
1273
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001274 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001275 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1276 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001277 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001278 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1279
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001280 final long maxElapsed;
1281 if (windowLength == AlarmManager.WINDOW_EXACT) {
1282 maxElapsed = triggerElapsed;
1283 } else if (windowLength < 0) {
1284 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001285 // Fix this window in place, so that as time approaches we don't collapse it.
1286 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001287 } else {
1288 maxElapsed = triggerElapsed + windowLength;
1289 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001292 if (DEBUG_BATCH) {
1293 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001294 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001295 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001296 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001298 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001299 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1300 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301 }
1302 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001303
Christopher Tate3e04b472013-10-21 17:51:31 -07001304 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001305 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1306 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1307 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001308 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001309 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1310 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001311 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001312 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001313 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1314 + " -- package not allowed to start");
1315 return;
1316 }
1317 } catch (RemoteException e) {
1318 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001319 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001320 setImplLocked(a, false, doValidate);
1321 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001322
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001323 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1324 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001325 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001326 // The caller has given the time they want this to happen at, however we need
1327 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001328 // bring us out of idle at an earlier time.
1329 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001330 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001331 }
1332 // Add fuzz to make the alarm go off some time before the actual desired time.
1333 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001334 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001335 if (fuzz > 0) {
1336 if (mRandom == null) {
1337 mRandom = new Random();
1338 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001339 final int delta = mRandom.nextInt(fuzz);
1340 a.whenElapsed -= delta;
1341 if (false) {
1342 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1343 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1344 Slog.d(TAG, "Applied fuzz: " + fuzz);
1345 Slog.d(TAG, "Final delta: " + delta);
1346 Slog.d(TAG, "Final when: " + a.whenElapsed);
1347 }
1348 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001349 }
1350
1351 } else if (mPendingIdleUntil != null) {
1352 // We currently have an idle until alarm scheduled; if the new alarm has
1353 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001354 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1355 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1356 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001357 == 0) {
1358 mPendingWhileIdleAlarms.add(a);
1359 return;
1360 }
1361 }
1362
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001363 if (RECORD_DEVICE_IDLE_ALARMS) {
1364 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1365 IdleDispatchEntry ent = new IdleDispatchEntry();
1366 ent.uid = a.uid;
1367 ent.pkg = a.operation.getCreatorPackage();
1368 ent.tag = a.operation.getTag("");
1369 ent.op = "SET";
1370 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1371 ent.argRealtime = a.whenElapsed;
1372 mAllowWhileIdleDispatches.add(ent);
1373 }
1374 }
1375
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001376 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
1377 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -07001378 if (whichBatch < 0) {
1379 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001380 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 } else {
Christopher Tate385e4982013-07-23 18:22:29 -07001382 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001383 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001384 // The start time of this batch advanced, so batch ordering may
1385 // have just been broken. Move it to where it now belongs.
1386 mAlarmBatches.remove(whichBatch);
1387 addBatchLocked(mAlarmBatches, batch);
1388 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 }
1390
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001391 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001392 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001393 }
1394
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001395 boolean needRebatch = false;
1396
1397 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001398 if (RECORD_DEVICE_IDLE_ALARMS) {
1399 if (mPendingIdleUntil == null) {
1400 IdleDispatchEntry ent = new IdleDispatchEntry();
1401 ent.uid = 0;
1402 ent.pkg = "START IDLE";
1403 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1404 mAllowWhileIdleDispatches.add(ent);
1405 }
1406 }
Makoto Onuki4274a6d2017-04-21 12:21:25 -07001407 if ((mPendingIdleUntil != a) && (mPendingIdleUntil != null)) {
1408 Slog.wtfStack(TAG, "setImplLocked: idle until changed from " + mPendingIdleUntil
1409 + " to " + a);
1410 }
1411
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001412 mPendingIdleUntil = a;
Dianne Hackborna750a632015-06-16 17:18:23 -07001413 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001414 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001415 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1416 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1417 mNextWakeFromIdle = a;
1418 // If this wake from idle is earlier than whatever was previously scheduled,
1419 // and we are currently idling, then we need to rebatch alarms in case the idle
1420 // until time needs to be updated.
1421 if (mPendingIdleUntil != null) {
1422 needRebatch = true;
1423 }
1424 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001425 }
1426
1427 if (!rebatching) {
1428 if (DEBUG_VALIDATE) {
1429 if (doValidate && !validateConsistencyLocked()) {
1430 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1431 + " when(hex)=" + Long.toHexString(a.when)
1432 + " whenElapsed=" + a.whenElapsed
1433 + " maxWhenElapsed=" + a.maxWhenElapsed
1434 + " interval=" + a.repeatInterval + " op=" + a.operation
1435 + " flags=0x" + Integer.toHexString(a.flags));
1436 rebatchAllAlarmsLocked(false);
1437 needRebatch = false;
1438 }
1439 }
1440
1441 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001442 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001443 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001444
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001445 rescheduleKernelAlarmsLocked();
1446 updateNextAlarmClockLocked();
1447 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001448 }
1449
Adam Lesinski182f73f2013-12-05 16:48:06 -08001450 private final IBinder mService = new IAlarmManager.Stub() {
1451 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001452 public void set(String callingPackage,
1453 int type, long triggerAtTime, long windowLength, long interval, int flags,
1454 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1455 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001456 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001457
1458 // make sure the caller is not lying about which package should be blamed for
1459 // wakelock time spent in alarm delivery
1460 mAppOps.checkPackage(callingUid, callingPackage);
1461
1462 // Repeating alarms must use PendingIntent, not direct listener
1463 if (interval != 0) {
1464 if (directReceiver != null) {
1465 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1466 }
1467 }
1468
Adam Lesinski182f73f2013-12-05 16:48:06 -08001469 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001470 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001471 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001472 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001473 }
1474
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001475 // No incoming callers can request either WAKE_FROM_IDLE or
1476 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1477 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1478 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1479
1480 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1481 // manager when to come out of idle mode, which is only for DeviceIdleController.
1482 if (callingUid != Process.SYSTEM_UID) {
1483 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1484 }
1485
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001486 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001487 if (windowLength == AlarmManager.WINDOW_EXACT) {
1488 flags |= AlarmManager.FLAG_STANDALONE;
1489 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001490
1491 // If this alarm is for an alarm clock, then it must be standalone and we will
1492 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001493 if (alarmClock != null) {
1494 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001495
1496 // If the caller is a core system component or on the user's whitelist, and not calling
1497 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1498 // This means we will allow these alarms to go off as normal even while idle, with no
1499 // timing restrictions.
1500 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
Christopher Tatebb9cce52017-04-18 14:19:43 -07001501 || callingUid == mSystemUiUid
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001502 || Arrays.binarySearch(mDeviceIdleUserWhitelist,
1503 UserHandle.getAppId(callingUid)) >= 0)) {
1504 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1505 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001506 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001507
Christopher Tate14a7bb02015-10-01 10:24:31 -07001508 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1509 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001510 }
Christopher Tate89779822012-08-31 14:40:03 -07001511
Adam Lesinski182f73f2013-12-05 16:48:06 -08001512 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001513 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001514 getContext().enforceCallingOrSelfPermission(
1515 "android.permission.SET_TIME",
1516 "setTime");
1517
Greg Hackmann0cab8962014-02-21 16:35:52 -08001518 if (mNativeData == 0) {
1519 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1520 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001521 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001522
1523 synchronized (mLock) {
1524 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001527
1528 @Override
1529 public void setTimeZone(String tz) {
1530 getContext().enforceCallingOrSelfPermission(
1531 "android.permission.SET_TIME_ZONE",
1532 "setTimeZone");
1533
1534 final long oldId = Binder.clearCallingIdentity();
1535 try {
1536 setTimeZoneImpl(tz);
1537 } finally {
1538 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 }
1540 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001541
Adam Lesinski182f73f2013-12-05 16:48:06 -08001542 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001543 public void remove(PendingIntent operation, IAlarmListener listener) {
1544 if (operation == null && listener == null) {
1545 Slog.w(TAG, "remove() with no intent or listener");
1546 return;
1547 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001548
Christopher Tate14a7bb02015-10-01 10:24:31 -07001549 synchronized (mLock) {
1550 removeLocked(operation, listener);
1551 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001553
Adam Lesinski182f73f2013-12-05 16:48:06 -08001554 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001555 public long getNextWakeFromIdleTime() {
1556 return getNextWakeFromIdleTimeImpl();
1557 }
1558
1559 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001560 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001561 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1562 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1563 "getNextAlarmClock", null);
1564
1565 return getNextAlarmClockImpl(userId);
1566 }
1567
1568 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001569 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06001570 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001571 dumpImpl(pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001572 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001573 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001574
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001575 public final class LocalService {
1576 public void setDeviceIdleUserWhitelist(int[] appids) {
1577 setDeviceIdleUserWhitelistImpl(appids);
1578 }
1579 }
1580
Adam Lesinski182f73f2013-12-05 16:48:06 -08001581 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 synchronized (mLock) {
1583 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001584 mConstants.dump(pw);
1585 pw.println();
1586
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001587 pw.print(" Foreground uids: [");
1588 for (int i = 0; i < mForegroundUids.size(); i++) {
1589 if (mForegroundUids.valueAt(i)) pw.print(mForegroundUids.keyAt(i) + " ");
1590 }
1591 pw.println("]");
1592 pw.println(" Forced app standby packages: " + mForcedAppStandbyPackages);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001593 final long nowRTC = System.currentTimeMillis();
1594 final long nowELAPSED = SystemClock.elapsedRealtime();
1595 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1596
Dianne Hackborna750a632015-06-16 17:18:23 -07001597 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001598 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001599 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001600 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001601 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001602 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001603 pw.print(" mLastTimeChangeRealtime=");
Dianne Hackbornc3527222015-05-13 14:03:20 -07001604 TimeUtils.formatDuration(mLastTimeChangeRealtime, pw);
1605 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001606 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001607 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001608 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1609 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001610 pw.print(" Max wakeup delay: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001611 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1612 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001613 pw.print(" Time since last dispatch: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001614 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1615 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001616 pw.print(" Next non-wakeup delivery time: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001617 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1618 pw.println();
1619 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001620
1621 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1622 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001623 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001624 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001625 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001626 pw.print(" Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001627 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001628 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
1629 pw.print(" set at "); TimeUtils.formatDuration(mLastWakeupSet, nowELAPSED, pw);
1630 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001631 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001632 pw.println(" mDeviceIdleUserWhitelist=" + Arrays.toString(mDeviceIdleUserWhitelist));
Christopher Tatee0a22b32013-07-11 14:43:13 -07001633
John Spurlock604a5ee2015-06-01 12:27:22 -04001634 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001635 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001636 final TreeSet<Integer> users = new TreeSet<>();
1637 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1638 users.add(mNextAlarmClockForUser.keyAt(i));
1639 }
1640 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1641 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1642 }
1643 for (int user : users) {
1644 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1645 final long time = next != null ? next.getTriggerTime() : 0;
1646 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001647 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001648 pw.print(" pendingSend:"); pw.print(pendingSend);
1649 pw.print(" time:"); pw.print(time);
1650 if (time > 0) {
1651 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1652 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1653 }
1654 pw.println();
1655 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001656 if (mAlarmBatches.size() > 0) {
1657 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001658 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001659 pw.println(mAlarmBatches.size());
1660 for (Batch b : mAlarmBatches) {
1661 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001662 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001663 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001665 pw.println();
1666 pw.println(" Pending user blocked background alarms: ");
1667 boolean blocked = false;
1668 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
1669 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
1670 if (blockedAlarms != null && blockedAlarms.size() > 0) {
1671 blocked = true;
1672 dumpAlarmList(pw, blockedAlarms, " ", nowELAPSED, nowRTC, sdf);
1673 }
1674 }
1675 if (!blocked) {
1676 pw.println(" none");
1677 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001678 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001679 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001680 pw.println(" Idle mode state:");
1681 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001682 if (mPendingIdleUntil != null) {
1683 pw.println(mPendingIdleUntil);
Dianne Hackbornf3831292015-10-15 14:51:06 -07001684 mPendingIdleUntil.dump(pw, " ", nowRTC, nowELAPSED, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001685 } else {
1686 pw.println("null");
1687 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001688 pw.println(" Pending alarms:");
1689 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001690 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001691 if (mNextWakeFromIdle != null) {
1692 pw.println();
1693 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
1694 mNextWakeFromIdle.dump(pw, " ", nowRTC, nowELAPSED, sdf);
1695 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001696
1697 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001698 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001699 if (mPendingNonWakeupAlarms.size() > 0) {
1700 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001701 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001702 } else {
1703 pw.println("(none)");
1704 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001705 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001706 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1707 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001708 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001709 pw.print(", max non-interactive time: ");
1710 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1711 pw.println();
1712
1713 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001714 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Christopher Tateeabba732017-08-17 17:12:52 -07001715 pw.print(" PendingIntent send count: "); pw.println(mSendCount);
1716 pw.print(" PendingIntent finish count: "); pw.println(mSendFinishCount);
1717 pw.print(" Listener send count: "); pw.println(mListenerCount);
1718 pw.print(" Listener finish count: "); pw.println(mListenerFinishCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001719 pw.println();
1720
Christopher Tate7f2a0352015-12-08 10:24:33 -08001721 if (mInFlight.size() > 0) {
1722 pw.println("Outstanding deliveries:");
1723 for (int i = 0; i < mInFlight.size(); i++) {
1724 pw.print(" #"); pw.print(i); pw.print(": ");
1725 pw.println(mInFlight.get(i));
1726 }
1727 pw.println();
1728 }
1729
Dianne Hackborna750a632015-06-16 17:18:23 -07001730 pw.print(" mAllowWhileIdleMinTime=");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001731 TimeUtils.formatDuration(mAllowWhileIdleMinTime, pw);
1732 pw.println();
1733 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001734 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001735 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
1736 pw.print(" UID ");
1737 UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
1738 pw.print(": ");
1739 TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i),
1740 nowELAPSED, pw);
1741 pw.println();
1742 }
1743 }
1744 pw.println();
1745
Dianne Hackborn81038902012-11-26 17:04:09 -08001746 if (mLog.dump(pw, " Recent problems", " ")) {
1747 pw.println();
1748 }
1749
1750 final FilterStats[] topFilters = new FilterStats[10];
1751 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1752 @Override
1753 public int compare(FilterStats lhs, FilterStats rhs) {
1754 if (lhs.aggregateTime < rhs.aggregateTime) {
1755 return 1;
1756 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1757 return -1;
1758 }
1759 return 0;
1760 }
1761 };
1762 int len = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001763 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1764 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1765 for (int ip=0; ip<uidStats.size(); ip++) {
1766 BroadcastStats bs = uidStats.valueAt(ip);
1767 for (int is=0; is<bs.filterStats.size(); is++) {
1768 FilterStats fs = bs.filterStats.valueAt(is);
1769 int pos = len > 0
1770 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1771 if (pos < 0) {
1772 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001773 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001774 if (pos < topFilters.length) {
1775 int copylen = topFilters.length - pos - 1;
1776 if (copylen > 0) {
1777 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1778 }
1779 topFilters[pos] = fs;
1780 if (len < topFilters.length) {
1781 len++;
1782 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001783 }
1784 }
1785 }
1786 }
1787 if (len > 0) {
1788 pw.println(" Top Alarms:");
1789 for (int i=0; i<len; i++) {
1790 FilterStats fs = topFilters[i];
1791 pw.print(" ");
1792 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1793 TimeUtils.formatDuration(fs.aggregateTime, pw);
1794 pw.print(" running, "); pw.print(fs.numWakeup);
1795 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001796 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1797 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001798 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001799 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001800 pw.println();
1801 }
1802 }
1803
1804 pw.println(" ");
1805 pw.println(" Alarm Stats:");
1806 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001807 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1808 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1809 for (int ip=0; ip<uidStats.size(); ip++) {
1810 BroadcastStats bs = uidStats.valueAt(ip);
1811 pw.print(" ");
1812 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1813 UserHandle.formatUid(pw, bs.mUid);
1814 pw.print(":");
1815 pw.print(bs.mPackageName);
1816 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1817 pw.print(" running, "); pw.print(bs.numWakeup);
1818 pw.println(" wakeups:");
1819 tmpFilters.clear();
1820 for (int is=0; is<bs.filterStats.size(); is++) {
1821 tmpFilters.add(bs.filterStats.valueAt(is));
1822 }
1823 Collections.sort(tmpFilters, comparator);
1824 for (int i=0; i<tmpFilters.size(); i++) {
1825 FilterStats fs = tmpFilters.get(i);
1826 pw.print(" ");
1827 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1828 TimeUtils.formatDuration(fs.aggregateTime, pw);
1829 pw.print(" "); pw.print(fs.numWakeup);
1830 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001831 pw.print(" alarms, last ");
1832 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1833 pw.println(":");
1834 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001835 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001836 pw.println();
1837 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 }
1839 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001840
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001841 if (RECORD_DEVICE_IDLE_ALARMS) {
1842 pw.println();
1843 pw.println(" Allow while idle dispatches:");
1844 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
1845 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
1846 pw.print(" ");
1847 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
1848 pw.print(": ");
1849 UserHandle.formatUid(pw, ent.uid);
1850 pw.print(":");
1851 pw.println(ent.pkg);
1852 if (ent.op != null) {
1853 pw.print(" ");
1854 pw.print(ent.op);
1855 pw.print(" / ");
1856 pw.print(ent.tag);
1857 if (ent.argRealtime != 0) {
1858 pw.print(" (");
1859 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
1860 pw.print(")");
1861 }
1862 pw.println();
1863 }
1864 }
1865 }
1866
Christopher Tate18a75f12013-07-01 18:18:59 -07001867 if (WAKEUP_STATS) {
1868 pw.println();
1869 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001870 long last = -1;
1871 for (WakeupEvent event : mRecentWakeups) {
1872 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1873 pw.print('|');
1874 if (last < 0) {
1875 pw.print('0');
1876 } else {
1877 pw.print(event.when - last);
1878 }
1879 last = event.when;
1880 pw.print('|'); pw.print(event.uid);
1881 pw.print('|'); pw.print(event.action);
1882 pw.println();
1883 }
1884 pw.println();
1885 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886 }
1887 }
1888
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001889 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001890 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
1891 PrintWriter pw = new PrintWriter(bs);
1892 final long nowRTC = System.currentTimeMillis();
1893 final long nowELAPSED = SystemClock.elapsedRealtime();
1894 final int NZ = mAlarmBatches.size();
1895 for (int iz = 0; iz < NZ; iz++) {
1896 Batch bz = mAlarmBatches.get(iz);
1897 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001898 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001899 pw.flush();
1900 Slog.v(TAG, bs.toString());
1901 bs.reset();
1902 }
1903 }
1904
1905 private boolean validateConsistencyLocked() {
1906 if (DEBUG_VALIDATE) {
1907 long lastTime = Long.MIN_VALUE;
1908 final int N = mAlarmBatches.size();
1909 for (int i = 0; i < N; i++) {
1910 Batch b = mAlarmBatches.get(i);
1911 if (b.start >= lastTime) {
1912 // duplicate start times are okay because of standalone batches
1913 lastTime = b.start;
1914 } else {
1915 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001916 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1917 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001918 return false;
1919 }
1920 }
1921 }
1922 return true;
1923 }
1924
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001925 private Batch findFirstWakeupBatchLocked() {
1926 final int N = mAlarmBatches.size();
1927 for (int i = 0; i < N; i++) {
1928 Batch b = mAlarmBatches.get(i);
1929 if (b.hasWakeups()) {
1930 return b;
1931 }
1932 }
1933 return null;
1934 }
1935
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001936 long getNextWakeFromIdleTimeImpl() {
1937 synchronized (mLock) {
1938 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
1939 }
1940 }
1941
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001942 void setDeviceIdleUserWhitelistImpl(int[] appids) {
1943 synchronized (mLock) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001944 // appids are sorted, just send pending alarms for any new appids added to the whitelist
1945 int i = 0, j = 0;
1946 while (i < appids.length) {
1947 while (j < mDeviceIdleUserWhitelist.length
1948 && mDeviceIdleUserWhitelist[j] < appids[i]) {
1949 j++;
1950 }
1951 if (j < mDeviceIdleUserWhitelist.length
1952 && appids[i] != mDeviceIdleUserWhitelist[j]) {
1953 if (DEBUG_BG_LIMIT) {
1954 Slog.d(TAG, "Sending blocked alarms for whitelisted appid " + appids[j]);
1955 }
1956 sendPendingBackgroundAlarmsForAppIdLocked(appids[j]);
1957 }
1958 i++;
1959 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001960 mDeviceIdleUserWhitelist = appids;
1961 }
1962 }
1963
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001964 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001965 synchronized (mLock) {
1966 return mNextAlarmClockForUser.get(userId);
1967 }
1968 }
1969
1970 /**
1971 * Recomputes the next alarm clock for all users.
1972 */
1973 private void updateNextAlarmClockLocked() {
1974 if (!mNextAlarmClockMayChange) {
1975 return;
1976 }
1977 mNextAlarmClockMayChange = false;
1978
Jose Lima235510e2014-08-13 12:50:01 -07001979 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001980 nextForUser.clear();
1981
1982 final int N = mAlarmBatches.size();
1983 for (int i = 0; i < N; i++) {
1984 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
1985 final int M = alarms.size();
1986
1987 for (int j = 0; j < M; j++) {
1988 Alarm a = alarms.get(j);
1989 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001990 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07001991 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02001992
1993 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07001994 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01001995 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02001996 " for user " + userId);
1997 }
1998
1999 // Alarms and batches are sorted by time, no need to compare times here.
2000 if (nextForUser.get(userId) == null) {
2001 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07002002 } else if (a.alarmClock.equals(current)
2003 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
2004 // same/earlier time and it's the one we cited before, so stick with it
2005 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002006 }
2007 }
2008 }
2009 }
2010
2011 // Update mNextAlarmForUser with new values.
2012 final int NN = nextForUser.size();
2013 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07002014 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002015 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002016 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002017 if (!newAlarm.equals(currentAlarm)) {
2018 updateNextAlarmInfoForUserLocked(userId, newAlarm);
2019 }
2020 }
2021
2022 // Remove users without any alarm clocks scheduled.
2023 final int NNN = mNextAlarmClockForUser.size();
2024 for (int i = NNN - 1; i >= 0; i--) {
2025 int userId = mNextAlarmClockForUser.keyAt(i);
2026 if (nextForUser.get(userId) == null) {
2027 updateNextAlarmInfoForUserLocked(userId, null);
2028 }
2029 }
2030 }
2031
Jose Lima235510e2014-08-13 12:50:01 -07002032 private void updateNextAlarmInfoForUserLocked(int userId,
2033 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002034 if (alarmClock != null) {
2035 if (DEBUG_ALARM_CLOCK) {
2036 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002037 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02002038 }
2039 mNextAlarmClockForUser.put(userId, alarmClock);
2040 } else {
2041 if (DEBUG_ALARM_CLOCK) {
2042 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
2043 }
2044 mNextAlarmClockForUser.remove(userId);
2045 }
2046
2047 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
2048 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2049 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2050 }
2051
2052 /**
2053 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
2054 * for which alarm clocks have changed since the last call to this.
2055 *
2056 * Do not call with a lock held. Only call from mHandler's thread.
2057 *
2058 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
2059 */
2060 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07002061 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002062 pendingUsers.clear();
2063
2064 synchronized (mLock) {
2065 final int N = mPendingSendNextAlarmClockChangedForUser.size();
2066 for (int i = 0; i < N; i++) {
2067 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
2068 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
2069 }
2070 mPendingSendNextAlarmClockChangedForUser.clear();
2071 }
2072
2073 final int N = pendingUsers.size();
2074 for (int i = 0; i < N; i++) {
2075 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002076 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002077 Settings.System.putStringForUser(getContext().getContentResolver(),
2078 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01002079 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02002080 userId);
2081
2082 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
2083 new UserHandle(userId));
2084 }
2085 }
2086
2087 /**
2088 * Formats an alarm like platform/packages/apps/DeskClock used to.
2089 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01002090 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
2091 int userId) {
2092 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02002093 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
2094 return (info == null) ? "" :
2095 DateFormat.format(pattern, info.getTriggerTime()).toString();
2096 }
2097
Adam Lesinski182f73f2013-12-05 16:48:06 -08002098 void rescheduleKernelAlarmsLocked() {
2099 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
2100 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002101 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002102 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002103 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002104 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07002105 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002106 mNextWakeup = firstWakeup.start;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002107 mLastWakeupSet = SystemClock.elapsedRealtime();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002108 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002109 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002110 if (firstBatch != firstWakeup) {
2111 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002112 }
2113 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002114 if (mPendingNonWakeupAlarms.size() > 0) {
2115 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
2116 nextNonWakeup = mNextNonWakeupDeliveryTime;
2117 }
2118 }
Prashant Malani753e9e02015-06-10 17:43:49 -07002119 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002120 mNextNonWakeup = nextNonWakeup;
2121 setLocked(ELAPSED_REALTIME, nextNonWakeup);
2122 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002123 }
2124
Christopher Tate14a7bb02015-10-01 10:24:31 -07002125 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002126 boolean didRemove = false;
2127 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2128 Batch b = mAlarmBatches.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002129 didRemove |= b.remove(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002130 if (b.size() == 0) {
2131 mAlarmBatches.remove(i);
2132 }
2133 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002134 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002135 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002136 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2137 mPendingWhileIdleAlarms.remove(i);
2138 }
2139 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002140 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2141 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2142 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2143 if (alarmsForUid.get(j).matches(operation, directReceiver)) {
2144 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2145 alarmsForUid.remove(j);
2146 }
2147 }
2148 if (alarmsForUid.size() == 0) {
2149 mPendingBackgroundAlarms.removeAt(i);
2150 }
2151 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002152 if (didRemove) {
2153 if (DEBUG_BATCH) {
2154 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
2155 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002156 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002157 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002158 mPendingIdleUntil = null;
2159 restorePending = true;
2160 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002161 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002162 mNextWakeFromIdle = null;
2163 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002164 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002165 if (restorePending) {
2166 restorePendingWhileIdleAlarmsLocked();
2167 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002168 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002169 }
2170 }
2171
2172 void removeLocked(String packageName) {
2173 boolean didRemove = false;
2174 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2175 Batch b = mAlarmBatches.get(i);
2176 didRemove |= b.remove(packageName);
2177 if (b.size() == 0) {
2178 mAlarmBatches.remove(i);
2179 }
2180 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002181 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002182 final Alarm a = mPendingWhileIdleAlarms.get(i);
2183 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002184 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2185 mPendingWhileIdleAlarms.remove(i);
2186 }
2187 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002188 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2189 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2190 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2191 if (alarmsForUid.get(j).matches(packageName)) {
2192 alarmsForUid.remove(j);
2193 }
2194 }
2195 if (alarmsForUid.size() == 0) {
2196 mPendingBackgroundAlarms.removeAt(i);
2197 }
2198 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002199 if (didRemove) {
2200 if (DEBUG_BATCH) {
2201 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2202 }
2203 rebatchAllAlarmsLocked(true);
2204 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002205 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002206 }
2207 }
2208
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002209 void removeForStoppedLocked(int uid) {
2210 boolean didRemove = false;
2211 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2212 Batch b = mAlarmBatches.get(i);
2213 didRemove |= b.removeForStopped(uid);
2214 if (b.size() == 0) {
2215 mAlarmBatches.remove(i);
2216 }
2217 }
2218 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2219 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08002220 if (a.uid == uid) {
2221 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2222 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002223 }
2224 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002225 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2226 if (mPendingBackgroundAlarms.keyAt(i) == uid) {
2227 mPendingBackgroundAlarms.removeAt(i);
2228 }
2229 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002230 if (didRemove) {
2231 if (DEBUG_BATCH) {
2232 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2233 }
2234 rebatchAllAlarmsLocked(true);
2235 rescheduleKernelAlarmsLocked();
2236 updateNextAlarmClockLocked();
2237 }
2238 }
2239
Adam Lesinski182f73f2013-12-05 16:48:06 -08002240 void removeUserLocked(int userHandle) {
2241 boolean didRemove = false;
2242 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2243 Batch b = mAlarmBatches.get(i);
2244 didRemove |= b.remove(userHandle);
2245 if (b.size() == 0) {
2246 mAlarmBatches.remove(i);
2247 }
2248 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002249 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002250 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002251 == userHandle) {
2252 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2253 mPendingWhileIdleAlarms.remove(i);
2254 }
2255 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002256 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2257 if (UserHandle.getUserId(mPendingBackgroundAlarms.keyAt(i)) == userHandle) {
2258 mPendingBackgroundAlarms.removeAt(i);
2259 }
2260 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002261 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
2262 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
2263 mLastAllowWhileIdleDispatch.removeAt(i);
2264 }
2265 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002266
2267 if (didRemove) {
2268 if (DEBUG_BATCH) {
2269 Slog.v(TAG, "remove(user) changed bounds; rebatching");
2270 }
2271 rebatchAllAlarmsLocked(true);
2272 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002273 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002274 }
2275 }
2276
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002277 void interactiveStateChangedLocked(boolean interactive) {
2278 if (mInteractive != interactive) {
2279 mInteractive = interactive;
2280 final long nowELAPSED = SystemClock.elapsedRealtime();
2281 if (interactive) {
2282 if (mPendingNonWakeupAlarms.size() > 0) {
2283 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2284 mTotalDelayTime += thisDelayTime;
2285 if (mMaxDelayTime < thisDelayTime) {
2286 mMaxDelayTime = thisDelayTime;
2287 }
2288 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2289 mPendingNonWakeupAlarms.clear();
2290 }
2291 if (mNonInteractiveStartTime > 0) {
2292 long dur = nowELAPSED - mNonInteractiveStartTime;
2293 if (dur > mNonInteractiveTime) {
2294 mNonInteractiveTime = dur;
2295 }
2296 }
2297 } else {
2298 mNonInteractiveStartTime = nowELAPSED;
2299 }
2300 }
2301 }
2302
Adam Lesinski182f73f2013-12-05 16:48:06 -08002303 boolean lookForPackageLocked(String packageName) {
2304 for (int i = 0; i < mAlarmBatches.size(); i++) {
2305 Batch b = mAlarmBatches.get(i);
2306 if (b.hasPackage(packageName)) {
2307 return true;
2308 }
2309 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002310 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002311 final Alarm a = mPendingWhileIdleAlarms.get(i);
2312 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002313 return true;
2314 }
2315 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002316 return false;
2317 }
2318
2319 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002320 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002321 // The kernel never triggers alarms with negative wakeup times
2322 // so we ensure they are positive.
2323 long alarmSeconds, alarmNanoseconds;
2324 if (when < 0) {
2325 alarmSeconds = 0;
2326 alarmNanoseconds = 0;
2327 } else {
2328 alarmSeconds = when / 1000;
2329 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2330 }
2331
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002332 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002333 } else {
2334 Message msg = Message.obtain();
2335 msg.what = ALARM_EVENT;
2336
2337 mHandler.removeMessages(ALARM_EVENT);
2338 mHandler.sendMessageAtTime(msg, when);
2339 }
2340 }
2341
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002342 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002343 String prefix, String label, long nowRTC, long nowELAPSED, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002344 for (int i=list.size()-1; i>=0; i--) {
2345 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002346 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2347 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002348 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002349 }
2350 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002351
2352 private static final String labelForType(int type) {
2353 switch (type) {
2354 case RTC: return "RTC";
2355 case RTC_WAKEUP : return "RTC_WAKEUP";
2356 case ELAPSED_REALTIME : return "ELAPSED";
2357 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
2358 default:
2359 break;
2360 }
2361 return "--unknown--";
2362 }
2363
2364 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002365 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002366 for (int i=list.size()-1; i>=0; i--) {
2367 Alarm a = list.get(i);
2368 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002369 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2370 pw.print(": "); pw.println(a);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002371 a.dump(pw, prefix + " ", nowRTC, nowELAPSED, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002372 }
2373 }
2374
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002375 private boolean isBackgroundRestricted(Alarm alarm) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002376 if (alarm.alarmClock != null) {
2377 // Don't block alarm clocks
2378 return false;
2379 }
2380 if (alarm.operation != null
2381 && (alarm.operation.isActivity() || alarm.operation.isForegroundService())) {
2382 // Don't block starting foreground components
2383 return false;
2384 }
2385 final String sourcePackage =
2386 (alarm.operation != null) ? alarm.operation.getCreatorPackage() : alarm.packageName;
2387 final int sourceUid = alarm.creatorUid;
2388 return mForcedAppStandbyPackages.contains(sourcePackage) && !mForegroundUids.get(sourceUid)
2389 && Arrays.binarySearch(mDeviceIdleUserWhitelist, UserHandle.getAppId(sourceUid))
2390 < 0;
2391 }
2392
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002393 private native long init();
2394 private native void close(long nativeData);
2395 private native void set(long nativeData, int type, long seconds, long nanoseconds);
2396 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08002397 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002398 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002399
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002400 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002401 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002402 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002403 // batches are temporally sorted, so we need only pull from the
2404 // start of the list until we either empty it or hit a batch
2405 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07002406 while (mAlarmBatches.size() > 0) {
2407 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002408 if (batch.start > nowELAPSED) {
2409 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002410 break;
2411 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002412
Christopher Tatee0a22b32013-07-11 14:43:13 -07002413 // We will (re)schedule some alarms now; don't let that interfere
2414 // with delivery of this current batch
2415 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002416
Christopher Tatee0a22b32013-07-11 14:43:13 -07002417 final int N = batch.size();
2418 for (int i = 0; i < N; i++) {
2419 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002420
2421 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
2422 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
2423 // schedule such alarms.
2424 long lastTime = mLastAllowWhileIdleDispatch.get(alarm.uid, 0);
2425 long minTime = lastTime + mAllowWhileIdleMinTime;
2426 if (nowELAPSED < minTime) {
2427 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
2428 // alarm went off for this app. Reschedule the alarm to be in the
2429 // correct time period.
2430 alarm.whenElapsed = minTime;
2431 if (alarm.maxWhenElapsed < minTime) {
2432 alarm.maxWhenElapsed = minTime;
2433 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002434 if (RECORD_DEVICE_IDLE_ALARMS) {
2435 IdleDispatchEntry ent = new IdleDispatchEntry();
2436 ent.uid = alarm.uid;
2437 ent.pkg = alarm.operation.getCreatorPackage();
2438 ent.tag = alarm.operation.getTag("");
2439 ent.op = "RESCHEDULE";
2440 ent.elapsedRealtime = nowELAPSED;
2441 ent.argRealtime = lastTime;
2442 mAllowWhileIdleDispatches.add(ent);
2443 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002444 setImplLocked(alarm, true, false);
2445 continue;
2446 }
2447 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002448 if (isBackgroundRestricted(alarm)) {
2449 // Alarms with FLAG_WAKE_FROM_IDLE or mPendingIdleUntil alarm are not deferred
2450 if (DEBUG_BG_LIMIT) {
2451 Slog.d(TAG, "Deferring alarm " + alarm + " due to user forced app standby");
2452 }
2453 ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(alarm.creatorUid);
2454 if (alarmsForUid == null) {
2455 alarmsForUid = new ArrayList<>();
2456 mPendingBackgroundAlarms.put(alarm.creatorUid, alarmsForUid);
2457 }
2458 alarmsForUid.add(alarm);
2459 continue;
2460 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002461
Christopher Tatee0a22b32013-07-11 14:43:13 -07002462 alarm.count = 1;
2463 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002464 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
2465 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002466 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002467 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002468 if (mPendingIdleUntil == alarm) {
2469 mPendingIdleUntil = null;
2470 rebatchAllAlarmsLocked(false);
2471 restorePendingWhileIdleAlarmsLocked();
2472 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002473 if (mNextWakeFromIdle == alarm) {
2474 mNextWakeFromIdle = null;
2475 rebatchAllAlarmsLocked(false);
2476 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002477
2478 // Recurring alarms may have passed several alarm intervals while the
2479 // phone was asleep or off, so pass a trigger count when sending them.
2480 if (alarm.repeatInterval > 0) {
2481 // this adjustment will be zero if we're late by
2482 // less than one full repeat interval
2483 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
2484
2485 // Also schedule its next recurrence
2486 final long delta = alarm.count * alarm.repeatInterval;
2487 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07002488 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07002489 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07002490 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
2491 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08002492 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002493
Christopher Tate864d42e2014-12-02 11:48:53 -08002494 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002495 hasWakeup = true;
2496 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002497
2498 // We removed an alarm clock. Let the caller recompute the next alarm clock.
2499 if (alarm.alarmClock != null) {
2500 mNextAlarmClockMayChange = true;
2501 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07002502 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002503 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002504
Christopher Tate1590f1e2014-10-02 17:27:57 -07002505 // This is a new alarm delivery set; bump the sequence number to indicate that
2506 // all apps' alarm delivery classes should be recalculated.
2507 mCurrentSeq++;
2508 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002509 Collections.sort(triggerList, mAlarmDispatchComparator);
2510
2511 if (localLOGV) {
2512 for (int i=0; i<triggerList.size(); i++) {
2513 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
2514 }
2515 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002516
2517 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002518 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002520 /**
2521 * This Comparator sorts Alarms into increasing time order.
2522 */
2523 public static class IncreasingTimeOrder implements Comparator<Alarm> {
2524 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09002525 long when1 = a1.whenElapsed;
2526 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002527 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002528 return 1;
2529 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002530 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002531 return -1;
2532 }
2533 return 0;
2534 }
2535 }
2536
2537 private static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002538 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002539 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002540 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002541 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002542 public final IAlarmListener listener;
2543 public final String listenerTag;
2544 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002545 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002546 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002547 public final AlarmManager.AlarmClockInfo alarmClock;
2548 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002549 public final int creatorUid;
2550 public final String packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002551 public int count;
2552 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07002553 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002554 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002555 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07002557 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002558
Christopher Tate3e04b472013-10-21 17:51:31 -07002559 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002560 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
2561 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
2562 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002563 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002564 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002565 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
2566 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002567 when = _when;
2568 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07002569 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002570 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002571 repeatInterval = _interval;
2572 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002573 listener = _rec;
2574 listenerTag = _listenerTag;
2575 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07002576 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002577 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002578 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002579 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002580 packageName = _pkgName;
2581
2582 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002583 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002584
Christopher Tate14a7bb02015-10-01 10:24:31 -07002585 public static String makeTag(PendingIntent pi, String tag, int type) {
2586 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
2587 ? "*walarm*:" : "*alarm*:";
2588 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
2589 }
2590
2591 public WakeupEvent makeWakeupEvent(long nowRTC) {
2592 return new WakeupEvent(nowRTC, creatorUid,
2593 (operation != null)
2594 ? operation.getIntent().getAction()
2595 : ("<listener>:" + listenerTag));
2596 }
2597
2598 // Returns true if either matches
2599 public boolean matches(PendingIntent pi, IAlarmListener rec) {
2600 return (operation != null)
2601 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09002602 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07002603 }
2604
2605 public boolean matches(String packageName) {
2606 return (operation != null)
2607 ? packageName.equals(operation.getTargetPackage())
2608 : packageName.equals(this.packageName);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002609 }
2610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002611 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002612 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002613 StringBuilder sb = new StringBuilder(128);
2614 sb.append("Alarm{");
2615 sb.append(Integer.toHexString(System.identityHashCode(this)));
2616 sb.append(" type ");
2617 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002618 sb.append(" when ");
2619 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002620 sb.append(" ");
Christopher Tate14a7bb02015-10-01 10:24:31 -07002621 if (operation != null) {
2622 sb.append(operation.getTargetPackage());
2623 } else {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002624 sb.append(packageName);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002625 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002626 sb.append('}');
2627 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002628 }
2629
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002630 public void dump(PrintWriter pw, String prefix, long nowRTC, long nowELAPSED,
2631 SimpleDateFormat sdf) {
2632 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002633 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002634 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002635 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
2636 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002637 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002638 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002639 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002640 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002641 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002642 }
2643 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002644 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002645 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002646 pw.print(" count="); pw.print(count);
2647 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002648 if (alarmClock != null) {
2649 pw.print(prefix); pw.println("Alarm clock:");
2650 pw.print(prefix); pw.print(" triggerTime=");
2651 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
2652 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
2653 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002654 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002655 if (listener != null) {
2656 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
2657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002658 }
2659 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002660
Christopher Tatee0a22b32013-07-11 14:43:13 -07002661 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
2662 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002663 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
2664 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002665 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07002666 break;
2667 }
2668
Christopher Tatee0a22b32013-07-11 14:43:13 -07002669 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002670 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
2671 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002672 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07002673 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002674 }
2675 }
2676
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002677 long currentNonWakeupFuzzLocked(long nowELAPSED) {
2678 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
2679 if (timeSinceOn < 5*60*1000) {
2680 // If the screen has been off for 5 minutes, only delay by at most two minutes.
2681 return 2*60*1000;
2682 } else if (timeSinceOn < 30*60*1000) {
2683 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
2684 return 15*60*1000;
2685 } else {
2686 // Otherwise, we will delay by at most an hour.
2687 return 60*60*1000;
2688 }
2689 }
2690
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002691 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002692 if (duration < 15*60*1000) {
2693 // If the duration until the time is less than 15 minutes, the maximum fuzz
2694 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002695 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002696 } else if (duration < 90*60*1000) {
2697 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
2698 return 15*60*1000;
2699 } else {
2700 // Otherwise, we will fuzz by at most half an hour.
2701 return 30*60*1000;
2702 }
2703 }
2704
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002705 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
2706 if (mInteractive) {
2707 return false;
2708 }
2709 if (mLastAlarmDeliveryTime <= 0) {
2710 return false;
2711 }
minho.choo649acab2014-12-12 16:13:55 +09002712 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002713 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
2714 // and the next delivery time is in the past, then just deliver them all. This
2715 // avoids bugs where we get stuck in a loop trying to poll for alarms.
2716 return false;
2717 }
2718 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
2719 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
2720 }
2721
2722 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
2723 mLastAlarmDeliveryTime = nowELAPSED;
2724 for (int i=0; i<triggerList.size(); i++) {
2725 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07002726 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002727 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07002728 if (localLOGV) {
2729 Slog.v(TAG, "sending alarm " + alarm);
2730 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07002731 if (RECORD_ALARMS_IN_HISTORY) {
2732 if (alarm.workSource != null && alarm.workSource.size() > 0) {
2733 for (int wi=0; wi<alarm.workSource.size(); wi++) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002734 ActivityManager.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002735 alarm.operation, alarm.workSource.get(wi), alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002736 }
2737 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002738 ActivityManager.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07002739 alarm.operation, alarm.uid, alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07002740 }
2741 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002742 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002743 } catch (RuntimeException e) {
2744 Slog.w(TAG, "Failure sending alarm.", e);
2745 }
2746 }
2747 }
2748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002749 private class AlarmThread extends Thread
2750 {
2751 public AlarmThread()
2752 {
2753 super("AlarmManager");
2754 }
2755
2756 public void run()
2757 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07002758 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002760 while (true)
2761 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002762 int result = waitForAlarm(mNativeData);
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002763 mLastWakeup = SystemClock.elapsedRealtime();
Dianne Hackborn390517b2013-05-30 15:03:32 -07002764
2765 triggerList.clear();
2766
Dianne Hackbornc3527222015-05-13 14:03:20 -07002767 final long nowRTC = System.currentTimeMillis();
2768 final long nowELAPSED = SystemClock.elapsedRealtime();
2769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002770 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002771 // The kernel can give us spurious time change notifications due to
2772 // small adjustments it makes internally; we want to filter those out.
2773 final long lastTimeChangeClockTime;
2774 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07002775 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07002776 lastTimeChangeClockTime = mLastTimeChangeClockTime;
2777 expectedClockTime = lastTimeChangeClockTime
2778 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07002779 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08002780 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
2781 || nowRTC > (expectedClockTime+1000)) {
2782 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07002783 // let's do it!
2784 if (DEBUG_BATCH) {
2785 Slog.v(TAG, "Time changed notification from kernel; rebatching");
2786 }
2787 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07002788 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07002789 rebatchAllAlarms();
2790 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07002791 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07002792 synchronized (mLock) {
2793 mNumTimeChanged++;
2794 mLastTimeChangeClockTime = nowRTC;
2795 mLastTimeChangeRealtime = nowELAPSED;
2796 }
2797 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
2798 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08002799 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07002800 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
2801 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07002802 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
2803
2804 // The world has changed on us, so we need to re-evaluate alarms
2805 // regardless of whether the kernel has told us one went off.
2806 result |= IS_WAKEUP_MASK;
2807 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002808 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002809
Dianne Hackbornc3527222015-05-13 14:03:20 -07002810 if (result != TIME_CHANGED_MASK) {
2811 // If this was anything besides just a time change, then figure what if
2812 // anything to do about alarms.
2813 synchronized (mLock) {
2814 if (localLOGV) Slog.v(
2815 TAG, "Checking for alarms... rtc=" + nowRTC
2816 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07002817
Dianne Hackbornc3527222015-05-13 14:03:20 -07002818 if (WAKEUP_STATS) {
2819 if ((result & IS_WAKEUP_MASK) != 0) {
2820 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
2821 int n = 0;
2822 for (WakeupEvent event : mRecentWakeups) {
2823 if (event.when > newEarliest) break;
2824 n++; // number of now-stale entries at the list head
2825 }
2826 for (int i = 0; i < n; i++) {
2827 mRecentWakeups.remove();
2828 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002829
Dianne Hackbornc3527222015-05-13 14:03:20 -07002830 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002831 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002832 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07002833
2834 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2835 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
2836 // if there are no wakeup alarms and the screen is off, we can
2837 // delay what we have so far until the future.
2838 if (mPendingNonWakeupAlarms.size() == 0) {
2839 mStartCurrentDelayTime = nowELAPSED;
2840 mNextNonWakeupDeliveryTime = nowELAPSED
2841 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
2842 }
2843 mPendingNonWakeupAlarms.addAll(triggerList);
2844 mNumDelayedAlarms += triggerList.size();
2845 rescheduleKernelAlarmsLocked();
2846 updateNextAlarmClockLocked();
2847 } else {
2848 // now deliver the alarm intents; if there are pending non-wakeup
2849 // alarms, we need to merge them in to the list. note we don't
2850 // just deliver them first because we generally want non-wakeup
2851 // alarms delivered after wakeup alarms.
2852 rescheduleKernelAlarmsLocked();
2853 updateNextAlarmClockLocked();
2854 if (mPendingNonWakeupAlarms.size() > 0) {
2855 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
2856 triggerList.addAll(mPendingNonWakeupAlarms);
2857 Collections.sort(triggerList, mAlarmDispatchComparator);
2858 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2859 mTotalDelayTime += thisDelayTime;
2860 if (mMaxDelayTime < thisDelayTime) {
2861 mMaxDelayTime = thisDelayTime;
2862 }
2863 mPendingNonWakeupAlarms.clear();
2864 }
2865 deliverAlarmsLocked(triggerList, nowELAPSED);
2866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002867 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002868
2869 } else {
2870 // Just in case -- even though no wakeup flag was set, make sure
2871 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07002872 synchronized (mLock) {
2873 rescheduleKernelAlarmsLocked();
2874 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002875 }
2876 }
2877 }
2878 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07002879
David Christieebe51fc2013-07-26 13:23:29 -07002880 /**
2881 * Attribute blame for a WakeLock.
2882 * @param pi PendingIntent to attribute blame to if ws is null.
2883 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07002884 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07002885 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002886 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002887 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07002888 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002889 final boolean unimportant = pi == mTimeTickSender;
2890 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002891 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002892 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07002893 } else {
2894 mWakeLock.setHistoryTag(null);
2895 }
2896 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07002897 if (ws != null) {
2898 mWakeLock.setWorkSource(ws);
2899 return;
2900 }
2901
Christopher Tate14a7bb02015-10-01 10:24:31 -07002902 final int uid = (knownUid >= 0)
2903 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002904 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07002905 if (uid >= 0) {
2906 mWakeLock.setWorkSource(new WorkSource(uid));
2907 return;
2908 }
2909 } catch (Exception e) {
2910 }
2911
2912 // Something went wrong; fall back to attributing the lock to the OS
2913 mWakeLock.setWorkSource(null);
2914 }
2915
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002916 private class AlarmHandler extends Handler {
2917 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002918 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
2919 public static final int LISTENER_TIMEOUT = 3;
2920 public static final int REPORT_ALARMS_ACTIVE = 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002921
2922 public AlarmHandler() {
2923 }
2924
2925 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002926 switch (msg.what) {
2927 case ALARM_EVENT: {
2928 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
2929 synchronized (mLock) {
2930 final long nowRTC = System.currentTimeMillis();
2931 final long nowELAPSED = SystemClock.elapsedRealtime();
2932 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
2933 updateNextAlarmClockLocked();
2934 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002935
Christopher Tate14a7bb02015-10-01 10:24:31 -07002936 // now trigger the alarms without the lock held
2937 for (int i=0; i<triggerList.size(); i++) {
2938 Alarm alarm = triggerList.get(i);
2939 try {
2940 alarm.operation.send();
2941 } catch (PendingIntent.CanceledException e) {
2942 if (alarm.repeatInterval > 0) {
2943 // This IntentSender is no longer valid, but this
2944 // is a repeating alarm, so toss the hoser.
2945 removeImpl(alarm.operation);
2946 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002947 }
2948 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002949 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002950 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002951
2952 case SEND_NEXT_ALARM_CLOCK_CHANGED:
2953 sendNextAlarmClockChanged();
2954 break;
2955
2956 case LISTENER_TIMEOUT:
2957 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
2958 break;
2959
Dianne Hackborn627dfa12015-11-11 18:10:30 -08002960 case REPORT_ALARMS_ACTIVE:
2961 if (mLocalDeviceIdleController != null) {
2962 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
2963 }
2964 break;
2965
Christopher Tate14a7bb02015-10-01 10:24:31 -07002966 default:
2967 // nope, just ignore it
2968 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002969 }
2970 }
2971 }
2972
2973 class ClockReceiver extends BroadcastReceiver {
2974 public ClockReceiver() {
2975 IntentFilter filter = new IntentFilter();
2976 filter.addAction(Intent.ACTION_TIME_TICK);
2977 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002978 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002979 }
2980
2981 @Override
2982 public void onReceive(Context context, Intent intent) {
2983 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07002984 if (DEBUG_BATCH) {
2985 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
2986 }
2987 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002988 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
2989 // Since the kernel does not keep track of DST, we need to
2990 // reset the TZ information at the beginning of each day
2991 // based off of the current Zone gmt offset + userspace tracked
2992 // daylight savings information.
2993 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02002994 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002995 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07002996 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002997 }
2998 }
2999
3000 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07003001 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09003002 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07003003
3004 // Schedule this event for the amount of time that it would take to get to
3005 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09003006 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07003007
David Christieebe51fc2013-07-26 13:23:29 -07003008 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08003009 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003010 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
3011 null, Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003012 }
Christopher Tate385e4982013-07-23 18:22:29 -07003013
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003014 public void scheduleDateChangedEvent() {
3015 Calendar calendar = Calendar.getInstance();
3016 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07003017 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003018 calendar.set(Calendar.MINUTE, 0);
3019 calendar.set(Calendar.SECOND, 0);
3020 calendar.set(Calendar.MILLISECOND, 0);
3021 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07003022
3023 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003024 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
3025 AlarmManager.FLAG_STANDALONE, workSource, null,
3026 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003027 }
3028 }
3029
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003030 class InteractiveStateReceiver extends BroadcastReceiver {
3031 public InteractiveStateReceiver() {
3032 IntentFilter filter = new IntentFilter();
3033 filter.addAction(Intent.ACTION_SCREEN_OFF);
3034 filter.addAction(Intent.ACTION_SCREEN_ON);
3035 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
3036 getContext().registerReceiver(this, filter);
3037 }
3038
3039 @Override
3040 public void onReceive(Context context, Intent intent) {
3041 synchronized (mLock) {
3042 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
3043 }
3044 }
3045 }
3046
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003047 class UninstallReceiver extends BroadcastReceiver {
3048 public UninstallReceiver() {
3049 IntentFilter filter = new IntentFilter();
3050 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
3051 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003052 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003053 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08003054 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003055 // Register for events related to sdcard installation.
3056 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08003057 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003058 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003059 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003060 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003061 }
3062
3063 @Override
3064 public void onReceive(Context context, Intent intent) {
3065 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003066 String action = intent.getAction();
3067 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003068 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
3069 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
3070 for (String packageName : pkgList) {
3071 if (lookForPackageLocked(packageName)) {
3072 setResultCode(Activity.RESULT_OK);
3073 return;
3074 }
3075 }
3076 return;
3077 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003078 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003079 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
3080 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
3081 if (userHandle >= 0) {
3082 removeUserLocked(userHandle);
3083 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003084 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
3085 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
3086 if (uid >= 0) {
3087 mLastAllowWhileIdleDispatch.delete(uid);
3088 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003089 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08003090 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
3091 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
3092 // This package is being updated; don't kill its alarms.
3093 return;
3094 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003095 Uri data = intent.getData();
3096 if (data != null) {
3097 String pkg = data.getSchemeSpecificPart();
3098 if (pkg != null) {
3099 pkgList = new String[]{pkg};
3100 }
3101 }
3102 }
3103 if (pkgList != null && (pkgList.length > 0)) {
3104 for (String pkg : pkgList) {
3105 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07003106 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003107 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
3108 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
3109 if (uidStats.remove(pkg) != null) {
3110 if (uidStats.size() <= 0) {
3111 mBroadcastStats.removeAt(i);
3112 }
3113 }
3114 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003115 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003116 }
3117 }
3118 }
3119 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003120
3121 final class UidObserver extends IUidObserver.Stub {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003122 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003123 }
3124
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003125 @Override public void onUidGone(int uid, boolean disabled) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003126 synchronized (mLock) {
3127 if (disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -08003128 removeForStoppedLocked(uid);
3129 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003130 mForegroundUids.delete(uid);
Dianne Hackborne07641d2016-11-09 15:07:23 -08003131 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003132 }
3133
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003134 @Override public void onUidActive(int uid) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003135 synchronized (mLock) {
3136 if (!mForegroundUids.get(uid)) {
3137 mForegroundUids.put(uid, true);
3138 sendPendingBackgroundAlarmsLocked(uid, null);
3139 }
3140 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003141 }
3142
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003143 @Override public void onUidIdle(int uid, boolean disabled) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003144 synchronized (mLock) {
3145 if (disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -08003146 removeForStoppedLocked(uid);
3147 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003148 mForegroundUids.delete(uid);
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08003149 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003150 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003151
3152 @Override public void onUidCachedChanged(int uid, boolean cached) {
3153 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003154 };
3155
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003156 private final class AppOpsWatcher extends IAppOpsCallback.Stub {
3157 @Override
3158 public void opChanged(int op, int uid, String packageName) throws RemoteException {
3159 synchronized (mLock) {
3160 final int mode = mAppOpsService.checkOperation(op, uid, packageName);
3161 if (DEBUG_BG_LIMIT) {
3162 Slog.d(TAG,
3163 "Appop changed for " + uid + ", " + packageName + " to " + mode);
3164 }
3165 final boolean changed;
3166 if (mode != AppOpsManager.MODE_ALLOWED) {
3167 changed = mForcedAppStandbyPackages.add(packageName);
3168 } else {
3169 changed = mForcedAppStandbyPackages.remove(packageName);
3170 }
3171 if (changed && mode == AppOpsManager.MODE_ALLOWED) {
3172 sendPendingBackgroundAlarmsLocked(uid, packageName);
3173 }
3174 }
3175 }
3176 }
3177
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003178 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003179 String pkg = pi.getCreatorPackage();
3180 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003181 return getStatsLocked(uid, pkg);
3182 }
3183
3184 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003185 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
3186 if (uidStats == null) {
3187 uidStats = new ArrayMap<String, BroadcastStats>();
3188 mBroadcastStats.put(uid, uidStats);
3189 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003190 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003191 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003192 bs = new BroadcastStats(uid, pkgName);
3193 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003194 }
3195 return bs;
3196 }
Dianne Hackborn81038902012-11-26 17:04:09 -08003197
Christopher Tate21e9f192017-08-08 13:49:11 -07003198 /**
3199 * Canonical count of (operation.send() - onSendFinished()) and
3200 * listener send/complete/timeout invocations.
3201 * Guarded by the usual lock.
3202 */
3203 @GuardedBy("mLock")
3204 private int mSendCount = 0;
3205 @GuardedBy("mLock")
Christopher Tateeabba732017-08-17 17:12:52 -07003206 private int mSendFinishCount = 0;
3207 @GuardedBy("mLock")
Christopher Tate21e9f192017-08-08 13:49:11 -07003208 private int mListenerCount = 0;
Christopher Tateeabba732017-08-17 17:12:52 -07003209 @GuardedBy("mLock")
3210 private int mListenerFinishCount = 0;
Christopher Tate21e9f192017-08-08 13:49:11 -07003211
Christopher Tate14a7bb02015-10-01 10:24:31 -07003212 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
Christopher Tate21e9f192017-08-08 13:49:11 -07003213
Christopher Tate14a7bb02015-10-01 10:24:31 -07003214 private InFlight removeLocked(PendingIntent pi, Intent intent) {
3215 for (int i = 0; i < mInFlight.size(); i++) {
Christopher Tatedb9ae422017-08-21 11:24:30 -07003216 if (mInFlight.get(i).mPendingIntent == pi) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003217 return mInFlight.remove(i);
3218 }
3219 }
3220 mLog.w("No in-flight alarm for " + pi + " " + intent);
3221 return null;
3222 }
3223
3224 private InFlight removeLocked(IBinder listener) {
3225 for (int i = 0; i < mInFlight.size(); i++) {
3226 if (mInFlight.get(i).mListener == listener) {
3227 return mInFlight.remove(i);
3228 }
3229 }
3230 mLog.w("No in-flight alarm for listener " + listener);
3231 return null;
3232 }
3233
3234 private void updateStatsLocked(InFlight inflight) {
3235 final long nowELAPSED = SystemClock.elapsedRealtime();
3236 BroadcastStats bs = inflight.mBroadcastStats;
3237 bs.nesting--;
3238 if (bs.nesting <= 0) {
3239 bs.nesting = 0;
3240 bs.aggregateTime += nowELAPSED - bs.startTime;
3241 }
3242 FilterStats fs = inflight.mFilterStats;
3243 fs.nesting--;
3244 if (fs.nesting <= 0) {
3245 fs.nesting = 0;
3246 fs.aggregateTime += nowELAPSED - fs.startTime;
3247 }
3248 if (RECORD_ALARMS_IN_HISTORY) {
3249 if (inflight.mWorkSource != null && inflight.mWorkSource.size() > 0) {
3250 for (int wi=0; wi<inflight.mWorkSource.size(); wi++) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003251 ActivityManager.noteAlarmFinish(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003252 inflight.mPendingIntent, inflight.mWorkSource.get(wi), inflight.mTag);
3253 }
3254 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003255 ActivityManager.noteAlarmFinish(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003256 inflight.mPendingIntent, inflight.mUid, inflight.mTag);
3257 }
3258 }
3259 }
3260
3261 private void updateTrackingLocked(InFlight inflight) {
3262 if (inflight != null) {
3263 updateStatsLocked(inflight);
3264 }
3265 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08003266 if (DEBUG_WAKELOCK) {
3267 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
3268 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003269 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003270 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003271 mWakeLock.release();
3272 if (mInFlight.size() > 0) {
3273 mLog.w("Finished all dispatches with " + mInFlight.size()
3274 + " remaining inflights");
3275 for (int i=0; i<mInFlight.size(); i++) {
3276 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
3277 }
3278 mInFlight.clear();
3279 }
3280 } else {
3281 // the next of our alarms is now in flight. reattribute the wakelock.
3282 if (mInFlight.size() > 0) {
3283 InFlight inFlight = mInFlight.get(0);
3284 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
3285 inFlight.mAlarmType, inFlight.mTag, -1, false);
3286 } else {
3287 // should never happen
3288 mLog.w("Alarm wakelock still held but sent queue empty");
3289 mWakeLock.setWorkSource(null);
3290 }
3291 }
3292 }
3293
3294 /**
3295 * Callback that arrives when a direct-call alarm reports that delivery has finished
3296 */
3297 @Override
3298 public void alarmComplete(IBinder who) {
3299 if (who == null) {
Christopher Tate21e9f192017-08-08 13:49:11 -07003300 mLog.w("Invalid alarmComplete: uid=" + Binder.getCallingUid()
Christopher Tate14a7bb02015-10-01 10:24:31 -07003301 + " pid=" + Binder.getCallingPid());
3302 return;
3303 }
3304
3305 final long ident = Binder.clearCallingIdentity();
3306 try {
3307 synchronized (mLock) {
3308 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
3309 InFlight inflight = removeLocked(who);
3310 if (inflight != null) {
3311 if (DEBUG_LISTENER_CALLBACK) {
3312 Slog.i(TAG, "alarmComplete() from " + who);
3313 }
3314 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07003315 mListenerFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003316 } else {
3317 // Delivery timed out, and the timeout handling already took care of
3318 // updating our tracking here, so we needn't do anything further.
3319 if (DEBUG_LISTENER_CALLBACK) {
3320 Slog.i(TAG, "Late alarmComplete() from " + who);
3321 }
3322 }
3323 }
3324 } finally {
3325 Binder.restoreCallingIdentity(ident);
3326 }
3327 }
3328
3329 /**
3330 * Callback that arrives when a PendingIntent alarm has finished delivery
3331 */
3332 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003333 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
3334 String resultData, Bundle resultExtras) {
3335 synchronized (mLock) {
Christopher Tateeabba732017-08-17 17:12:52 -07003336 mSendFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003337 updateTrackingLocked(removeLocked(pi, intent));
3338 }
3339 }
3340
3341 /**
3342 * Timeout of a direct-call alarm delivery
3343 */
3344 public void alarmTimedOut(IBinder who) {
3345 synchronized (mLock) {
3346 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08003347 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003348 // TODO: implement ANR policy for the target
3349 if (DEBUG_LISTENER_CALLBACK) {
3350 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003351 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003352 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07003353 mListenerFinishCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08003354 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003355 if (DEBUG_LISTENER_CALLBACK) {
3356 Slog.i(TAG, "Spurious timeout of listener " + who);
3357 }
Christopher Tate21e9f192017-08-08 13:49:11 -07003358 mLog.w("Spurious timeout of listener " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003359 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003360 }
3361 }
3362
3363 /**
3364 * Deliver an alarm and set up the post-delivery handling appropriately
3365 */
3366 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
3367 if (alarm.operation != null) {
3368 // PendingIntent alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07003369 mSendCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003370 try {
3371 alarm.operation.send(getContext(), 0,
3372 mBackgroundIntent.putExtra(
3373 Intent.EXTRA_ALARM_COUNT, alarm.count),
3374 mDeliveryTracker, mHandler, null,
3375 allowWhileIdle ? mIdleOptions : null);
3376 } catch (PendingIntent.CanceledException e) {
3377 if (alarm.repeatInterval > 0) {
3378 // This IntentSender is no longer valid, but this
3379 // is a repeating alarm, so toss it
3380 removeImpl(alarm.operation);
3381 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003382 // No actual delivery was possible, so the delivery tracker's
3383 // 'finished' callback won't be invoked. We also don't need
3384 // to do any wakelock or stats tracking, so we have nothing
3385 // left to do here but go on to the next thing.
Christopher Tateeabba732017-08-17 17:12:52 -07003386 mSendFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08003387 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003388 }
3389 } else {
3390 // Direct listener callback alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07003391 mListenerCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003392 try {
3393 if (DEBUG_LISTENER_CALLBACK) {
3394 Slog.v(TAG, "Alarm to uid=" + alarm.uid
3395 + " listener=" + alarm.listener.asBinder());
3396 }
3397 alarm.listener.doAlarm(this);
3398 mHandler.sendMessageDelayed(
3399 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
3400 alarm.listener.asBinder()),
3401 mConstants.LISTENER_TIMEOUT);
3402 } catch (Exception e) {
3403 if (DEBUG_LISTENER_CALLBACK) {
3404 Slog.i(TAG, "Alarm undeliverable to listener "
3405 + alarm.listener.asBinder(), e);
3406 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003407 // As in the PendingIntent.CanceledException case, delivery of the
3408 // alarm was not possible, so we have no wakelock or timeout or
3409 // stats management to do. It threw before we posted the delayed
3410 // timeout message, so we're done here.
Christopher Tateeabba732017-08-17 17:12:52 -07003411 mListenerFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08003412 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003413 }
3414 }
3415
3416 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08003417 if (DEBUG_WAKELOCK) {
3418 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
3419 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003420 if (mBroadcastRefCount == 0) {
3421 setWakelockWorkSource(alarm.operation, alarm.workSource,
3422 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
3423 true);
3424 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003425 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003426 }
3427 final InFlight inflight = new InFlight(AlarmManagerService.this,
3428 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
3429 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
3430 mInFlight.add(inflight);
3431 mBroadcastRefCount++;
3432
3433 if (allowWhileIdle) {
3434 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
3435 mLastAllowWhileIdleDispatch.put(alarm.uid, nowELAPSED);
3436 if (RECORD_DEVICE_IDLE_ALARMS) {
3437 IdleDispatchEntry ent = new IdleDispatchEntry();
3438 ent.uid = alarm.uid;
3439 ent.pkg = alarm.packageName;
3440 ent.tag = alarm.statsTag;
3441 ent.op = "DELIVER";
3442 ent.elapsedRealtime = nowELAPSED;
3443 mAllowWhileIdleDispatches.add(ent);
3444 }
3445 }
3446
3447 final BroadcastStats bs = inflight.mBroadcastStats;
3448 bs.count++;
3449 if (bs.nesting == 0) {
3450 bs.nesting = 1;
3451 bs.startTime = nowELAPSED;
3452 } else {
3453 bs.nesting++;
3454 }
3455 final FilterStats fs = inflight.mFilterStats;
3456 fs.count++;
3457 if (fs.nesting == 0) {
3458 fs.nesting = 1;
3459 fs.startTime = nowELAPSED;
3460 } else {
3461 fs.nesting++;
3462 }
3463 if (alarm.type == ELAPSED_REALTIME_WAKEUP
3464 || alarm.type == RTC_WAKEUP) {
3465 bs.numWakeup++;
3466 fs.numWakeup++;
3467 if (alarm.workSource != null && alarm.workSource.size() > 0) {
3468 for (int wi=0; wi<alarm.workSource.size(); wi++) {
Christopher Tate0029f572016-06-14 10:16:28 -07003469 final String wsName = alarm.workSource.getName(wi);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003470 ActivityManager.noteWakeupAlarm(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003471 alarm.operation, alarm.workSource.get(wi),
Christopher Tate0029f572016-06-14 10:16:28 -07003472 (wsName != null) ? wsName : alarm.packageName,
3473 alarm.statsTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08003474 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003475 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003476 ActivityManager.noteWakeupAlarm(
Joe Onorato78bcdf92016-05-09 10:10:29 -07003477 alarm.operation, alarm.uid, alarm.packageName, alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003478 }
3479 }
3480 }
3481 }
3482}