blob: 38b9647c15b44ded9c0e67a15fa72de39d364710 [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
Jeff Sharkey9911a282018-02-14 22:29:11 -070019import static android.app.AlarmManager.ELAPSED_REALTIME;
20import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
21import static android.app.AlarmManager.FLAG_ALLOW_WHILE_IDLE;
22import static android.app.AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
23import static android.app.AlarmManager.RTC;
24import static android.app.AlarmManager.RTC_WAKEUP;
25
Suprabh Shukla75edab12018-01-29 14:09:06 -080026import android.annotation.UserIdInt;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080027import android.app.Activity;
Adrian Roosc42a1e12014-07-07 23:35:53 +020028import android.app.ActivityManager;
Christopher Tate57ceaaa2013-07-19 16:30:43 -070029import android.app.AlarmManager;
Christopher Tate14a7bb02015-10-01 10:24:31 -070030import android.app.AppOpsManager;
Dianne Hackborna750a632015-06-16 17:18:23 -070031import android.app.BroadcastOptions;
Christopher Tate14a7bb02015-10-01 10:24:31 -070032import android.app.IAlarmCompleteListener;
33import android.app.IAlarmListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.app.IAlarmManager;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070035import android.app.IUidObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.app.PendingIntent;
Suprabh Shukla75edab12018-01-29 14:09:06 -080037import android.app.usage.UsageStatsManager;
38import android.app.usage.UsageStatsManagerInternal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.content.BroadcastReceiver;
Dianne Hackborna750a632015-06-16 17:18:23 -070040import android.content.ContentResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.Context;
42import android.content.Intent;
43import android.content.IntentFilter;
Christopher Tatebb9cce52017-04-18 14:19:43 -070044import android.content.pm.ApplicationInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.pm.PackageManager;
Christopher Tatebb9cce52017-04-18 14:19:43 -070046import android.content.pm.PackageManager.NameNotFoundException;
47import android.content.pm.PermissionInfo;
Dianne Hackborna750a632015-06-16 17:18:23 -070048import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.net.Uri;
50import android.os.Binder;
51import android.os.Bundle;
Christopher Tate247571462017-04-10 11:45:05 -070052import android.os.Environment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.os.Handler;
Adam Lesinski182f73f2013-12-05 16:48:06 -080054import android.os.IBinder;
Suprabh Shukla6226c2f2018-08-22 18:15:04 -070055import android.os.Looper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.os.Message;
Jeff Sharkey9911a282018-02-14 22:29:11 -070057import android.os.ParcelableException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.os.PowerManager;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070059import android.os.Process;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070060import android.os.RemoteException;
mswest463f4c99d2018-02-01 10:13:10 -080061import android.os.ResultReceiver;
62import android.os.ShellCallback;
63import android.os.ShellCommand;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.os.SystemClock;
65import android.os.SystemProperties;
Tim Murray175c0f92017-11-28 15:01:04 -080066import android.os.Trace;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070067import android.os.UserHandle;
Christopher Tatec4a07d12012-04-06 14:19:13 -070068import android.os.WorkSource;
Adrian Roosc42a1e12014-07-07 23:35:53 +020069import android.provider.Settings;
Christopher Tate8b98ade2018-02-09 11:13:19 -080070import android.system.Os;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.text.TextUtils;
Adrian Roosc42a1e12014-07-07 23:35:53 +020072import android.text.format.DateFormat;
Christopher Tate22e919d2018-02-16 16:16:50 -080073import android.text.format.DateUtils;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080074import android.util.ArrayMap;
Suprabh Shukla92994ab2018-01-31 17:39:30 -080075import android.util.ArraySet;
Dianne Hackborna750a632015-06-16 17:18:23 -070076import android.util.KeyValueListParser;
Adrian Roosc42a1e12014-07-07 23:35:53 +020077import android.util.Log;
Jeff Sharkey9911a282018-02-14 22:29:11 -070078import android.util.NtpTrustedTime;
Suprabh Shukla75edab12018-01-29 14:09:06 -080079import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -080080import android.util.Slog;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080081import android.util.SparseArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +020082import android.util.SparseBooleanArray;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -070083import android.util.SparseLongArray;
Bookatz7948c872018-09-04 12:58:33 -070084import android.util.StatsLog;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070085import android.util.TimeUtils;
Kweku Adams61e03292017-10-19 14:27:12 -070086import android.util.proto.ProtoOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087
Jeff Sharkey9911a282018-02-14 22:29:11 -070088import com.android.internal.annotations.GuardedBy;
89import com.android.internal.annotations.VisibleForTesting;
90import com.android.internal.util.ArrayUtils;
91import com.android.internal.util.DumpUtils;
92import com.android.internal.util.LocalLog;
Makoto Onuki49392d32018-04-11 13:51:02 -070093import com.android.internal.util.StatLogger;
Jeff Sharkey9911a282018-02-14 22:29:11 -070094import com.android.server.AppStateTracker.Listener;
95
Christopher Tate4cb338d2013-07-26 13:11:31 -070096import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097import java.io.FileDescriptor;
98import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070099import java.text.SimpleDateFormat;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700100import java.time.DateTimeException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -0800102import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103import java.util.Calendar;
104import java.util.Collections;
105import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -0500106import java.util.Date;
Christopher Tate1590f1e2014-10-02 17:27:57 -0700107import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -0700108import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200109import java.util.Locale;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700110import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111import java.util.TimeZone;
John Spurlock604a5ee2015-06-01 12:27:22 -0400112import java.util.TreeSet;
Makoto Onuki2206af32017-11-21 16:25:35 -0800113import java.util.function.Predicate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114
Makoto Onuki2206af32017-11-21 16:25:35 -0800115/**
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700116 * Alarm manager implementation.
Makoto Onuki2206af32017-11-21 16:25:35 -0800117 *
118 * Unit test:
119 atest $ANDROID_BUILD_TOP/frameworks/base/services/tests/servicestests/src/com/android/server/AlarmManagerServiceTest.java
120 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800121class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700122 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
123 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800124 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700125 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800126 static final int TIME_CHANGED_MASK = 1 << 16;
127 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -0800128
Christopher Tatee0a22b32013-07-11 14:43:13 -0700129 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -0800130 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -0800131
Adam Lesinski182f73f2013-12-05 16:48:06 -0800132 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -0800133 static final boolean localLOGV = false;
134 static final boolean DEBUG_BATCH = localLOGV || false;
135 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200136 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700137 static final boolean DEBUG_LISTENER_CALLBACK = localLOGV || false;
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800138 static final boolean DEBUG_WAKELOCK = localLOGV || false;
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700139 static final boolean DEBUG_BG_LIMIT = localLOGV || false;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800140 static final boolean DEBUG_STANDBY = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700141 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700142 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800143 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200144
Christopher Tatec8b7f432018-09-28 16:23:10 -0700145 static final int TICK_HISTORY_DEPTH = 10;
146
Christopher Tatef2159712018-03-27 16:04:14 -0700147 // Indices into the APP_STANDBY_MIN_DELAYS and KEYS_APP_STANDBY_DELAY arrays
148 static final int ACTIVE_INDEX = 0;
149 static final int WORKING_INDEX = 1;
150 static final int FREQUENT_INDEX = 2;
151 static final int RARE_INDEX = 3;
152 static final int NEVER_INDEX = 4;
153
Christopher Tate14a7bb02015-10-01 10:24:31 -0700154 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800156 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700157
Adam Lesinski182f73f2013-12-05 16:48:06 -0800158 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700159
Christopher Tate24cd46f2016-02-02 14:28:01 -0800160 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT =
161 new Intent(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED)
Christopher Tate50191db2017-05-09 16:02:25 -0700162 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
163 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Adrian Roosc42a1e12014-07-07 23:35:53 +0200164
Adam Lesinski182f73f2013-12-05 16:48:06 -0800165 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800166
Christopher Tate14a7bb02015-10-01 10:24:31 -0700167 AppOpsManager mAppOps;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800168 DeviceIdleController.LocalService mLocalDeviceIdleController;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800169 private UsageStatsManagerInternal mUsageStatsManagerInternal;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700170
Adam Lesinski182f73f2013-12-05 16:48:06 -0800171 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800172
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700173 // List of alarms per uid deferred due to user applied background restrictions on the source app
174 SparseArray<ArrayList<Alarm>> mPendingBackgroundAlarms = new SparseArray<>();
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800175 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700176 private long mNextNonWakeup;
Suprabh Shukla0e4510d2018-06-20 17:28:26 -0700177 private long mNextWakeUpSetAt;
178 private long mNextNonWakeUpSetAt;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -0700179 private long mLastWakeup;
Christopher Tate8b98ade2018-02-09 11:13:19 -0800180 private long mLastTrigger;
Christopher Tatec8b7f432018-09-28 16:23:10 -0700181
Christopher Tate12cf0b62018-01-05 18:40:14 -0800182 private long mLastTickSet;
Christopher Tate12cf0b62018-01-05 18:40:14 -0800183 private long mLastTickReceived;
Makoto Onuki5d93b832018-01-10 16:12:39 -0800184 private long mLastTickAdded;
185 private long mLastTickRemoved;
Christopher Tatec8b7f432018-09-28 16:23:10 -0700186 // ring buffer of recent TIME_TICK issuance, in the elapsed timebase
187 private final long[] mTickHistory = new long[TICK_HISTORY_DEPTH];
188 private int mNextTickHistory;
189
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700190 private final Injector mInjector;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800191 int mBroadcastRefCount = 0;
192 PowerManager.WakeLock mWakeLock;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700193 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
194 ArrayList<InFlight> mInFlight = new ArrayList<>();
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700195 AlarmHandler mHandler;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800196 ClockReceiver mClockReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700197 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Christopher Tatec8b7f432018-09-28 16:23:10 -0700198 Intent mTimeTickIntent;
199 IAlarmListener mTimeTickTrigger;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800200 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700201 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700202 boolean mInteractive = true;
203 long mNonInteractiveStartTime;
204 long mNonInteractiveTime;
205 long mLastAlarmDeliveryTime;
206 long mStartCurrentDelayTime;
207 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700208 long mLastTimeChangeClockTime;
209 long mLastTimeChangeRealtime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700210 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800211
Christopher Tatebb9cce52017-04-18 14:19:43 -0700212 // Bookkeeping about the identity of the "System UI" package, determined at runtime.
213
214 /**
215 * This permission must be defined by the canonical System UI package,
216 * with protection level "signature".
217 */
218 private static final String SYSTEM_UI_SELF_PERMISSION =
219 "android.permission.systemui.IDENTITY";
220
221 /**
222 * At boot we use SYSTEM_UI_SELF_PERMISSION to look up the definer's uid.
223 */
224 int mSystemUiUid;
225
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700226 /**
227 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
Kweku Adams61e03292017-10-19 14:27:12 -0700228 * used to determine the earliest we can dispatch the next such alarm. Times are in the
229 * 'elapsed' timebase.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700230 */
231 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
232
Suprabh Shuklac25447d2018-01-19 16:43:35 -0800233 /**
234 * For each uid, we store whether the last allow-while-idle alarm was dispatched while
235 * the uid was in foreground or not. We will use the allow_while_idle_short_time in such cases.
236 */
237 final SparseBooleanArray mUseAllowWhileIdleShortTime = new SparseBooleanArray();
238
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700239 final static class IdleDispatchEntry {
240 int uid;
241 String pkg;
242 String tag;
243 String op;
244 long elapsedRealtime;
245 long argRealtime;
246 }
247 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
248
Suprabh Shukla75edab12018-01-29 14:09:06 -0800249 interface Stats {
250 int REBATCH_ALL_ALARMS = 0;
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800251 int REORDER_ALARMS_FOR_STANDBY = 1;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800252 }
253
254 private final StatLogger mStatLogger = new StatLogger(new String[] {
255 "REBATCH_ALL_ALARMS",
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800256 "REORDER_ALARMS_FOR_STANDBY",
Suprabh Shukla75edab12018-01-29 14:09:06 -0800257 });
258
Dianne Hackborna750a632015-06-16 17:18:23 -0700259 /**
260 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
261 */
262 Bundle mIdleOptions;
263
Jose Lima235510e2014-08-13 12:50:01 -0700264 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
265 new SparseArray<>();
266 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
267 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200268 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
269 new SparseBooleanArray();
270 private boolean mNextAlarmClockMayChange;
271
272 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700273 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
274 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200275
Makoto Onukie4918212018-02-06 11:30:15 -0800276 private AppStateTracker mAppStateTracker;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800277 private boolean mAppStandbyParole;
278 private ArrayMap<Pair<String, Integer>, Long> mLastAlarmDeliveredForPackage = new ArrayMap<>();
Makoto Onuki2206af32017-11-21 16:25:35 -0800279
Dianne Hackborna750a632015-06-16 17:18:23 -0700280 /**
281 * All times are in milliseconds. These constants are kept synchronized with the system
282 * global Settings. Any access to this class or its fields should be done while
283 * holding the AlarmManagerService.mLock lock.
284 */
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700285 @VisibleForTesting
286 final class Constants extends ContentObserver {
Dianne Hackborna750a632015-06-16 17:18:23 -0700287 // Key names stored in the settings value.
Suprabh Shuklaadfa6e82018-10-19 17:32:08 -0700288 @VisibleForTesting
289 static final String KEY_MIN_FUTURITY = "min_futurity";
290 @VisibleForTesting
291 static final String KEY_MIN_INTERVAL = "min_interval";
292 @VisibleForTesting
293 static final String KEY_MAX_INTERVAL = "max_interval";
294 @VisibleForTesting
295 static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
296 @VisibleForTesting
297 static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
298 @VisibleForTesting
299 static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
Dianne Hackborna750a632015-06-16 17:18:23 -0700300 = "allow_while_idle_whitelist_duration";
Suprabh Shuklaadfa6e82018-10-19 17:32:08 -0700301 @VisibleForTesting
302 static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Dianne Hackborna750a632015-06-16 17:18:23 -0700303
Suprabh Shukla75edab12018-01-29 14:09:06 -0800304 // Keys for specifying throttling delay based on app standby bucketing
305 private final String[] KEYS_APP_STANDBY_DELAY = {
306 "standby_active_delay",
307 "standby_working_delay",
308 "standby_frequent_delay",
309 "standby_rare_delay",
310 "standby_never_delay",
311 };
312
Dianne Hackborna750a632015-06-16 17:18:23 -0700313 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
314 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tate22e919d2018-02-16 16:16:50 -0800315 private static final long DEFAULT_MAX_INTERVAL = 365 * DateUtils.DAY_IN_MILLIS;
Christopher Tateaa244da2015-08-27 15:57:57 -0700316 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700317 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700318 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700319 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800320 private final long[] DEFAULT_APP_STANDBY_DELAYS = {
321 0, // Active
322 6 * 60_000, // Working
323 30 * 60_000, // Frequent
324 2 * 60 * 60_000, // Rare
325 10 * 24 * 60 * 60_000 // Never
326 };
Christopher Tate14a7bb02015-10-01 10:24:31 -0700327
Dianne Hackborna750a632015-06-16 17:18:23 -0700328 // Minimum futurity of a new alarm
329 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
330
331 // Minimum alarm recurrence interval
332 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
333
Christopher Tate22e919d2018-02-16 16:16:50 -0800334 // Maximum alarm recurrence interval
335 public long MAX_INTERVAL = DEFAULT_MAX_INTERVAL;
336
Dianne Hackborna750a632015-06-16 17:18:23 -0700337 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
338 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
339
340 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
341 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
342
343 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
344 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
345 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
346
Christopher Tate14a7bb02015-10-01 10:24:31 -0700347 // Direct alarm listener callback timeout
348 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
349
Suprabh Shukla75edab12018-01-29 14:09:06 -0800350 public long[] APP_STANDBY_MIN_DELAYS = new long[DEFAULT_APP_STANDBY_DELAYS.length];
351
Dianne Hackborna750a632015-06-16 17:18:23 -0700352 private ContentResolver mResolver;
353 private final KeyValueListParser mParser = new KeyValueListParser(',');
354 private long mLastAllowWhileIdleWhitelistDuration = -1;
355
356 public Constants(Handler handler) {
357 super(handler);
Dianne Hackborna750a632015-06-16 17:18:23 -0700358 updateAllowWhileIdleWhitelistDurationLocked();
359 }
360
361 public void start(ContentResolver resolver) {
362 mResolver = resolver;
363 mResolver.registerContentObserver(Settings.Global.getUriFor(
364 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
365 updateConstants();
366 }
367
Dianne Hackborna750a632015-06-16 17:18:23 -0700368 public void updateAllowWhileIdleWhitelistDurationLocked() {
369 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
370 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
371 BroadcastOptions opts = BroadcastOptions.makeBasic();
372 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
373 mIdleOptions = opts.toBundle();
374 }
375 }
376
377 @Override
378 public void onChange(boolean selfChange, Uri uri) {
379 updateConstants();
380 }
381
382 private void updateConstants() {
383 synchronized (mLock) {
384 try {
385 mParser.setString(Settings.Global.getString(mResolver,
386 Settings.Global.ALARM_MANAGER_CONSTANTS));
387 } catch (IllegalArgumentException e) {
388 // Failed to parse the settings string, log this and move on
389 // with defaults.
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800390 Slog.e(TAG, "Bad alarm manager settings", e);
Dianne Hackborna750a632015-06-16 17:18:23 -0700391 }
392
393 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
394 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
Christopher Tate22e919d2018-02-16 16:16:50 -0800395 MAX_INTERVAL = mParser.getLong(KEY_MAX_INTERVAL, DEFAULT_MAX_INTERVAL);
Dianne Hackborna750a632015-06-16 17:18:23 -0700396 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
397 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
398 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
399 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
400 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
401 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
402 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700403 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
404 DEFAULT_LISTENER_TIMEOUT);
Christopher Tatef2159712018-03-27 16:04:14 -0700405 APP_STANDBY_MIN_DELAYS[ACTIVE_INDEX] = mParser.getDurationMillis(
406 KEYS_APP_STANDBY_DELAY[ACTIVE_INDEX],
407 DEFAULT_APP_STANDBY_DELAYS[ACTIVE_INDEX]);
408 for (int i = WORKING_INDEX; i < KEYS_APP_STANDBY_DELAY.length; i++) {
Suprabh Shukla75edab12018-01-29 14:09:06 -0800409 APP_STANDBY_MIN_DELAYS[i] = mParser.getDurationMillis(KEYS_APP_STANDBY_DELAY[i],
410 Math.max(APP_STANDBY_MIN_DELAYS[i-1], DEFAULT_APP_STANDBY_DELAYS[i]));
411 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700412 updateAllowWhileIdleWhitelistDurationLocked();
413 }
414 }
415
416 void dump(PrintWriter pw) {
417 pw.println(" Settings:");
418
419 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
420 TimeUtils.formatDuration(MIN_FUTURITY, pw);
421 pw.println();
422
423 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
424 TimeUtils.formatDuration(MIN_INTERVAL, pw);
425 pw.println();
426
Christopher Tate22e919d2018-02-16 16:16:50 -0800427 pw.print(" "); pw.print(KEY_MAX_INTERVAL); pw.print("=");
428 TimeUtils.formatDuration(MAX_INTERVAL, pw);
429 pw.println();
430
Christopher Tate14a7bb02015-10-01 10:24:31 -0700431 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
432 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
433 pw.println();
434
Dianne Hackborna750a632015-06-16 17:18:23 -0700435 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
436 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
437 pw.println();
438
439 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
440 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
441 pw.println();
442
443 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
444 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
445 pw.println();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800446
447 for (int i = 0; i < KEYS_APP_STANDBY_DELAY.length; i++) {
448 pw.print(" "); pw.print(KEYS_APP_STANDBY_DELAY[i]); pw.print("=");
449 TimeUtils.formatDuration(APP_STANDBY_MIN_DELAYS[i], pw);
450 pw.println();
451 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700452 }
Kweku Adams61e03292017-10-19 14:27:12 -0700453
454 void dumpProto(ProtoOutputStream proto, long fieldId) {
455 final long token = proto.start(fieldId);
456
457 proto.write(ConstantsProto.MIN_FUTURITY_DURATION_MS, MIN_FUTURITY);
458 proto.write(ConstantsProto.MIN_INTERVAL_DURATION_MS, MIN_INTERVAL);
Christopher Tate22e919d2018-02-16 16:16:50 -0800459 proto.write(ConstantsProto.MAX_INTERVAL_DURATION_MS, MAX_INTERVAL);
Kweku Adams61e03292017-10-19 14:27:12 -0700460 proto.write(ConstantsProto.LISTENER_TIMEOUT_DURATION_MS, LISTENER_TIMEOUT);
461 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_SHORT_DURATION_MS,
462 ALLOW_WHILE_IDLE_SHORT_TIME);
463 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_LONG_DURATION_MS,
464 ALLOW_WHILE_IDLE_LONG_TIME);
465 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_WHITELIST_DURATION_MS,
466 ALLOW_WHILE_IDLE_WHITELIST_DURATION);
467
468 proto.end(token);
469 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700470 }
471
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700472 Constants mConstants;
Dianne Hackborna750a632015-06-16 17:18:23 -0700473
Christopher Tate1590f1e2014-10-02 17:27:57 -0700474 // Alarm delivery ordering bookkeeping
475 static final int PRIO_TICK = 0;
476 static final int PRIO_WAKEUP = 1;
477 static final int PRIO_NORMAL = 2;
478
Dianne Hackborna750a632015-06-16 17:18:23 -0700479 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700480 int seq;
481 int priority;
482
483 PriorityClass() {
484 seq = mCurrentSeq - 1;
485 priority = PRIO_NORMAL;
486 }
487 }
488
Dianne Hackborna750a632015-06-16 17:18:23 -0700489 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700490 int mCurrentSeq = 0;
491
Dianne Hackborna750a632015-06-16 17:18:23 -0700492 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700493 public long when;
494 public int uid;
495 public String action;
496
497 public WakeupEvent(long theTime, int theUid, String theAction) {
498 when = theTime;
499 uid = theUid;
500 action = theAction;
501 }
502 }
503
Adam Lesinski182f73f2013-12-05 16:48:06 -0800504 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
505 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700506
Adrian Roosc42a1e12014-07-07 23:35:53 +0200507 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700508 long start; // These endpoints are always in ELAPSED
509 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700510 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700511
512 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
513
514 Batch() {
515 start = 0;
516 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700517 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700518 }
519
520 Batch(Alarm seed) {
521 start = seed.whenElapsed;
Christopher Tate22e919d2018-02-16 16:16:50 -0800522 end = clampPositive(seed.maxWhenElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700523 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700524 alarms.add(seed);
Christopher Tatec8b7f432018-09-28 16:23:10 -0700525 if (seed.listener == mTimeTickTrigger) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700526 mLastTickAdded = mInjector.getCurrentTimeMillis();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800527 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700528 }
529
530 int size() {
531 return alarms.size();
532 }
533
534 Alarm get(int index) {
535 return alarms.get(index);
536 }
537
538 boolean canHold(long whenElapsed, long maxWhen) {
539 return (end >= whenElapsed) && (start <= maxWhen);
540 }
541
542 boolean add(Alarm alarm) {
543 boolean newStart = false;
544 // narrows the batch if necessary; presumes that canHold(alarm) is true
545 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
546 if (index < 0) {
547 index = 0 - index - 1;
548 }
549 alarms.add(index, alarm);
Christopher Tatec8b7f432018-09-28 16:23:10 -0700550 if (alarm.listener == mTimeTickTrigger) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700551 mLastTickAdded = mInjector.getCurrentTimeMillis();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800552 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700553 if (DEBUG_BATCH) {
554 Slog.v(TAG, "Adding " + alarm + " to " + this);
555 }
556 if (alarm.whenElapsed > start) {
557 start = alarm.whenElapsed;
558 newStart = true;
559 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700560 if (alarm.maxWhenElapsed < end) {
561 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700562 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700563 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700564
565 if (DEBUG_BATCH) {
566 Slog.v(TAG, " => now " + this);
567 }
568 return newStart;
569 }
570
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800571 boolean remove(Alarm alarm) {
572 return remove(a -> (a == alarm));
573 }
574
Christopher Tate1d99c392017-12-07 16:54:04 -0800575 boolean remove(Predicate<Alarm> predicate) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700576 boolean didRemove = false;
577 long newStart = 0; // recalculate endpoints as we go
578 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700579 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700580 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700581 Alarm alarm = alarms.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -0800582 if (predicate.test(alarm)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700583 alarms.remove(i);
584 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200585 if (alarm.alarmClock != null) {
586 mNextAlarmClockMayChange = true;
587 }
Christopher Tatec8b7f432018-09-28 16:23:10 -0700588 if (alarm.listener == mTimeTickTrigger) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700589 mLastTickRemoved = mInjector.getCurrentTimeMillis();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800590 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700591 } else {
592 if (alarm.whenElapsed > newStart) {
593 newStart = alarm.whenElapsed;
594 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700595 if (alarm.maxWhenElapsed < newEnd) {
596 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700597 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700598 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700599 i++;
600 }
601 }
602 if (didRemove) {
603 // commit the new batch bounds
604 start = newStart;
605 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700606 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700607 }
608 return didRemove;
609 }
610
Christopher Tatee0a22b32013-07-11 14:43:13 -0700611 boolean hasPackage(final String packageName) {
612 final int N = alarms.size();
613 for (int i = 0; i < N; i++) {
614 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700615 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700616 return true;
617 }
618 }
619 return false;
620 }
621
622 boolean hasWakeups() {
623 final int N = alarms.size();
624 for (int i = 0; i < N; i++) {
625 Alarm a = alarms.get(i);
626 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
627 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
628 return true;
629 }
630 }
631 return false;
632 }
633
634 @Override
635 public String toString() {
636 StringBuilder b = new StringBuilder(40);
637 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
638 b.append(" num="); b.append(size());
639 b.append(" start="); b.append(start);
640 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700641 if (flags != 0) {
642 b.append(" flgs=0x");
643 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700644 }
645 b.append('}');
646 return b.toString();
647 }
Kweku Adams61e03292017-10-19 14:27:12 -0700648
649 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
650 long nowRTC) {
651 final long token = proto.start(fieldId);
652
653 proto.write(BatchProto.START_REALTIME, start);
654 proto.write(BatchProto.END_REALTIME, end);
655 proto.write(BatchProto.FLAGS, flags);
656 for (Alarm a : alarms) {
657 a.writeToProto(proto, BatchProto.ALARMS, nowElapsed, nowRTC);
658 }
659
660 proto.end(token);
661 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700662 }
663
664 static class BatchTimeOrder implements Comparator<Batch> {
665 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800666 long when1 = b1.start;
667 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800668 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700669 return 1;
670 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800671 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700672 return -1;
673 }
674 return 0;
675 }
676 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800677
678 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
679 @Override
680 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700681 // priority class trumps everything. TICK < WAKEUP < NORMAL
682 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
683 return -1;
684 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
685 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800686 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700687
688 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800689 if (lhs.whenElapsed < rhs.whenElapsed) {
690 return -1;
691 } else if (lhs.whenElapsed > rhs.whenElapsed) {
692 return 1;
693 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700694
695 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800696 return 0;
697 }
698 };
699
Christopher Tate1590f1e2014-10-02 17:27:57 -0700700 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
701 final int N = alarms.size();
702 for (int i = 0; i < N; i++) {
703 Alarm a = alarms.get(i);
704
705 final int alarmPrio;
Christopher Tatec8b7f432018-09-28 16:23:10 -0700706 if (a.listener == mTimeTickTrigger) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700707 alarmPrio = PRIO_TICK;
708 } else if (a.wakeup) {
709 alarmPrio = PRIO_WAKEUP;
710 } else {
711 alarmPrio = PRIO_NORMAL;
712 }
713
714 PriorityClass packagePrio = a.priorityClass;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800715 String alarmPackage = a.sourcePackage;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700716 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700717 if (packagePrio == null) {
718 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700719 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700720 }
721 a.priorityClass = packagePrio;
722
723 if (packagePrio.seq != mCurrentSeq) {
724 // first alarm we've seen in the current delivery generation from this package
725 packagePrio.priority = alarmPrio;
726 packagePrio.seq = mCurrentSeq;
727 } else {
728 // Multiple alarms from this package being delivered in this generation;
729 // bump the package's delivery class if it's warranted.
730 // TICK < WAKEUP < NORMAL
731 if (alarmPrio < packagePrio.priority) {
732 packagePrio.priority = alarmPrio;
733 }
734 }
735 }
736 }
737
Christopher Tatee0a22b32013-07-11 14:43:13 -0700738 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800739 static final long MIN_FUZZABLE_INTERVAL = 10000;
740 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700741 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
742
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700743 // 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 -0700744 // to run during this time are placed in mPendingWhileIdleAlarms
745 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700746 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700747 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700748
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700749 @VisibleForTesting
750 AlarmManagerService(Context context, Injector injector) {
Jeff Brownb880d882014-02-10 19:47:07 -0800751 super(context);
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700752 mInjector = injector;
Jeff Brownb880d882014-02-10 19:47:07 -0800753 }
754
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700755 AlarmManagerService(Context context) {
756 this(context, new Injector(context));
757 }
758
759 private long convertToElapsed(long when, int type) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700760 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
761 if (isRtc) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700762 when -= mInjector.getCurrentTimeMillis() - mInjector.getElapsedRealtime();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700763 }
764 return when;
765 }
766
767 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
768 // calculate the end of our nominal delivery window for the alarm.
769 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
770 // Current heuristic: batchable window is 75% of either the recurrence interval
771 // [for a periodic alarm] or of the time from now to the desired delivery time,
772 // with a minimum delay/interval of 10 seconds, under which we will simply not
773 // defer the alarm.
774 long futurity = (interval == 0)
775 ? (triggerAtTime - now)
776 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700777 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700778 futurity = 0;
779 }
Christopher Tate22e919d2018-02-16 16:16:50 -0800780 return clampPositive(triggerAtTime + (long)(.75 * futurity));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700781 }
782
783 // returns true if the batch was added at the head
784 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
785 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
786 if (index < 0) {
787 index = 0 - index - 1;
788 }
789 list.add(index, newBatch);
790 return (index == 0);
791 }
792
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800793 private void insertAndBatchAlarmLocked(Alarm alarm) {
794 final int whichBatch = ((alarm.flags & AlarmManager.FLAG_STANDALONE) != 0) ? -1
795 : attemptCoalesceLocked(alarm.whenElapsed, alarm.maxWhenElapsed);
796
797 if (whichBatch < 0) {
798 addBatchLocked(mAlarmBatches, new Batch(alarm));
799 } else {
800 final Batch batch = mAlarmBatches.get(whichBatch);
801 if (batch.add(alarm)) {
802 // The start time of this batch advanced, so batch ordering may
803 // have just been broken. Move it to where it now belongs.
804 mAlarmBatches.remove(whichBatch);
805 addBatchLocked(mAlarmBatches, batch);
806 }
807 }
808 }
809
Christopher Tate385e4982013-07-23 18:22:29 -0700810 // Return the index of the matching batch, or -1 if none found.
811 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700812 final int N = mAlarmBatches.size();
813 for (int i = 0; i < N; i++) {
814 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700815 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700816 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700817 }
818 }
Christopher Tate385e4982013-07-23 18:22:29 -0700819 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700820 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800821 /** @return total count of the alarms in a set of alarm batches. */
822 static int getAlarmCount(ArrayList<Batch> batches) {
823 int ret = 0;
824
825 final int size = batches.size();
826 for (int i = 0; i < size; i++) {
827 ret += batches.get(i).size();
828 }
829 return ret;
830 }
831
832 boolean haveAlarmsTimeTickAlarm(ArrayList<Alarm> alarms) {
833 if (alarms.size() == 0) {
834 return false;
835 }
836 final int batchSize = alarms.size();
837 for (int j = 0; j < batchSize; j++) {
Christopher Tatec8b7f432018-09-28 16:23:10 -0700838 if (alarms.get(j).listener == mTimeTickTrigger) {
Makoto Onuki5d93b832018-01-10 16:12:39 -0800839 return true;
840 }
841 }
842 return false;
843 }
844
845 boolean haveBatchesTimeTickAlarm(ArrayList<Batch> batches) {
846 final int numBatches = batches.size();
847 for (int i = 0; i < numBatches; i++) {
848 if (haveAlarmsTimeTickAlarm(batches.get(i).alarms)) {
849 return true;
850 }
851 }
852 return false;
853 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700854
855 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
856 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700857 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700858 rebatchAllAlarmsLocked(true);
859 }
860 }
861
862 void rebatchAllAlarmsLocked(boolean doValidate) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800863 final long start = mStatLogger.getTime();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800864 final int oldCount =
865 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
866 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
867 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
868
Christopher Tate4cb338d2013-07-26 13:11:31 -0700869 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
870 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700871 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700872 final long nowElapsed = mInjector.getElapsedRealtime();
Christopher Tate4cb338d2013-07-26 13:11:31 -0700873 final int oldBatches = oldSet.size();
874 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
875 Batch batch = oldSet.get(batchNum);
876 final int N = batch.size();
877 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700878 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700879 }
880 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700881 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
882 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
883 + " to " + mPendingIdleUntil);
884 if (mPendingIdleUntil == null) {
885 // Somehow we lost this... we need to restore all of the pending alarms.
886 restorePendingWhileIdleAlarmsLocked();
887 }
888 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800889 final int newCount =
890 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
891 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
892 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
893
894 if (oldCount != newCount) {
895 Slog.wtf(TAG, "Rebatching: total count changed from " + oldCount + " to " + newCount);
896 }
897 if (oldHasTick != newHasTick) {
898 Slog.wtf(TAG, "Rebatching: hasTick changed from " + oldHasTick + " to " + newHasTick);
899 }
900
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700901 rescheduleKernelAlarmsLocked();
902 updateNextAlarmClockLocked();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800903 mStatLogger.logDurationStat(Stats.REBATCH_ALL_ALARMS, start);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700904 }
905
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800906 /**
907 * Re-orders the alarm batches based on newly evaluated send times based on the current
908 * app-standby buckets
909 * @param targetPackages [Package, User] pairs for which alarms need to be re-evaluated,
910 * null indicates all
911 * @return True if there was any reordering done to the current list.
912 */
913 boolean reorderAlarmsBasedOnStandbyBuckets(ArraySet<Pair<String, Integer>> targetPackages) {
914 final long start = mStatLogger.getTime();
915 final ArrayList<Alarm> rescheduledAlarms = new ArrayList<>();
916
917 for (int batchIndex = mAlarmBatches.size() - 1; batchIndex >= 0; batchIndex--) {
918 final Batch batch = mAlarmBatches.get(batchIndex);
919 for (int alarmIndex = batch.size() - 1; alarmIndex >= 0; alarmIndex--) {
920 final Alarm alarm = batch.get(alarmIndex);
921 final Pair<String, Integer> packageUser =
922 Pair.create(alarm.sourcePackage, UserHandle.getUserId(alarm.creatorUid));
923 if (targetPackages != null && !targetPackages.contains(packageUser)) {
924 continue;
925 }
926 if (adjustDeliveryTimeBasedOnStandbyBucketLocked(alarm)) {
927 batch.remove(alarm);
928 rescheduledAlarms.add(alarm);
929 }
930 }
931 if (batch.size() == 0) {
932 mAlarmBatches.remove(batchIndex);
933 }
934 }
935 for (int i = 0; i < rescheduledAlarms.size(); i++) {
936 final Alarm a = rescheduledAlarms.get(i);
937 insertAndBatchAlarmLocked(a);
938 }
939
940 mStatLogger.logDurationStat(Stats.REORDER_ALARMS_FOR_STANDBY, start);
941 return rescheduledAlarms.size() > 0;
942 }
943
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700944 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
945 a.when = a.origWhen;
946 long whenElapsed = convertToElapsed(a.when, a.type);
947 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700948 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700949 // Exact
950 maxElapsed = whenElapsed;
951 } else {
952 // Not exact. Preserve any explicit window, otherwise recalculate
953 // the window based on the alarm's new futurity. Note that this
954 // reflects a policy of preferring timely to deferred delivery.
955 maxElapsed = (a.windowLength > 0)
Christopher Tate22e919d2018-02-16 16:16:50 -0800956 ? clampPositive(whenElapsed + a.windowLength)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700957 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
958 }
959 a.whenElapsed = whenElapsed;
960 a.maxWhenElapsed = maxElapsed;
961 setImplLocked(a, true, doValidate);
962 }
963
Christopher Tate22e919d2018-02-16 16:16:50 -0800964 static long clampPositive(long val) {
965 return (val >= 0) ? val : Long.MAX_VALUE;
966 }
967
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700968 /**
969 * Sends alarms that were blocked due to user applied background restrictions - either because
970 * the user lifted those or the uid came to foreground.
971 *
972 * @param uid uid to filter on
973 * @param packageName package to filter on, or null for all packages in uid
974 */
975 void sendPendingBackgroundAlarmsLocked(int uid, String packageName) {
976 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(uid);
977 if (alarmsForUid == null || alarmsForUid.size() == 0) {
978 return;
979 }
980 final ArrayList<Alarm> alarmsToDeliver;
981 if (packageName != null) {
982 if (DEBUG_BG_LIMIT) {
983 Slog.d(TAG, "Sending blocked alarms for uid " + uid + ", package " + packageName);
984 }
985 alarmsToDeliver = new ArrayList<>();
986 for (int i = alarmsForUid.size() - 1; i >= 0; i--) {
987 final Alarm a = alarmsForUid.get(i);
988 if (a.matches(packageName)) {
989 alarmsToDeliver.add(alarmsForUid.remove(i));
990 }
991 }
992 if (alarmsForUid.size() == 0) {
993 mPendingBackgroundAlarms.remove(uid);
994 }
995 } else {
996 if (DEBUG_BG_LIMIT) {
997 Slog.d(TAG, "Sending blocked alarms for uid " + uid);
998 }
999 alarmsToDeliver = alarmsForUid;
1000 mPendingBackgroundAlarms.remove(uid);
1001 }
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001002 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, mInjector.getElapsedRealtime());
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001003 }
1004
Makoto Onuki2206af32017-11-21 16:25:35 -08001005 /**
1006 * Check all alarms in {@link #mPendingBackgroundAlarms} and send the ones that are not
1007 * restricted.
1008 *
1009 * This is only called when the global "force all apps-standby" flag changes or when the
1010 * power save whitelist changes, so it's okay to be slow.
1011 */
1012 void sendAllUnrestrictedPendingBackgroundAlarmsLocked() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001013 final ArrayList<Alarm> alarmsToDeliver = new ArrayList<>();
Makoto Onuki2206af32017-11-21 16:25:35 -08001014
1015 findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
1016 mPendingBackgroundAlarms, alarmsToDeliver, this::isBackgroundRestricted);
1017
1018 if (alarmsToDeliver.size() > 0) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001019 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, mInjector.getElapsedRealtime());
Makoto Onuki2206af32017-11-21 16:25:35 -08001020 }
1021 }
1022
1023 @VisibleForTesting
1024 static void findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
1025 SparseArray<ArrayList<Alarm>> pendingAlarms, ArrayList<Alarm> unrestrictedAlarms,
1026 Predicate<Alarm> isBackgroundRestricted) {
1027
1028 for (int uidIndex = pendingAlarms.size() - 1; uidIndex >= 0; uidIndex--) {
1029 final int uid = pendingAlarms.keyAt(uidIndex);
1030 final ArrayList<Alarm> alarmsForUid = pendingAlarms.valueAt(uidIndex);
1031
1032 for (int alarmIndex = alarmsForUid.size() - 1; alarmIndex >= 0; alarmIndex--) {
1033 final Alarm alarm = alarmsForUid.get(alarmIndex);
1034
1035 if (isBackgroundRestricted.test(alarm)) {
1036 continue;
1037 }
1038
1039 unrestrictedAlarms.add(alarm);
1040 alarmsForUid.remove(alarmIndex);
1041 }
1042
1043 if (alarmsForUid.size() == 0) {
1044 pendingAlarms.removeAt(uidIndex);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001045 }
1046 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001047 }
1048
1049 private void deliverPendingBackgroundAlarmsLocked(ArrayList<Alarm> alarms, long nowELAPSED) {
1050 final int N = alarms.size();
1051 boolean hasWakeup = false;
1052 for (int i = 0; i < N; i++) {
1053 final Alarm alarm = alarms.get(i);
1054 if (alarm.wakeup) {
1055 hasWakeup = true;
1056 }
1057 alarm.count = 1;
1058 // Recurring alarms may have passed several alarm intervals while the
1059 // alarm was kept pending. Send the appropriate trigger count.
1060 if (alarm.repeatInterval > 0) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001061 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001062 // Also schedule its next recurrence
1063 final long delta = alarm.count * alarm.repeatInterval;
1064 final long nextElapsed = alarm.whenElapsed + delta;
1065 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
1066 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
1067 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
1068 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
1069 // Kernel alarms will be rescheduled as needed in setImplLocked
1070 }
1071 }
1072 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
1073 // No need to wakeup for non wakeup alarms
1074 if (mPendingNonWakeupAlarms.size() == 0) {
1075 mStartCurrentDelayTime = nowELAPSED;
1076 mNextNonWakeupDeliveryTime = nowELAPSED
1077 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
1078 }
1079 mPendingNonWakeupAlarms.addAll(alarms);
1080 mNumDelayedAlarms += alarms.size();
1081 } else {
1082 if (DEBUG_BG_LIMIT) {
1083 Slog.d(TAG, "Waking up to deliver pending blocked alarms");
1084 }
1085 // Since we are waking up, also deliver any pending non wakeup alarms we have.
1086 if (mPendingNonWakeupAlarms.size() > 0) {
1087 alarms.addAll(mPendingNonWakeupAlarms);
1088 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1089 mTotalDelayTime += thisDelayTime;
1090 if (mMaxDelayTime < thisDelayTime) {
1091 mMaxDelayTime = thisDelayTime;
1092 }
1093 mPendingNonWakeupAlarms.clear();
1094 }
1095 calculateDeliveryPriorities(alarms);
1096 Collections.sort(alarms, mAlarmDispatchComparator);
1097 deliverAlarmsLocked(alarms, nowELAPSED);
1098 }
1099 }
1100
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001101 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001102 if (RECORD_DEVICE_IDLE_ALARMS) {
1103 IdleDispatchEntry ent = new IdleDispatchEntry();
1104 ent.uid = 0;
1105 ent.pkg = "FINISH IDLE";
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001106 ent.elapsedRealtime = mInjector.getElapsedRealtime();
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001107 mAllowWhileIdleDispatches.add(ent);
1108 }
1109
Dianne Hackborn35d54032015-04-23 10:30:43 -07001110 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001111 if (mPendingWhileIdleAlarms.size() > 0) {
1112 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
1113 mPendingWhileIdleAlarms = new ArrayList<>();
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001114 final long nowElapsed = mInjector.getElapsedRealtime();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001115 for (int i=alarms.size() - 1; i >= 0; i--) {
1116 Alarm a = alarms.get(i);
1117 reAddAlarmLocked(a, nowElapsed, false);
1118 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001119 }
Dianne Hackborn35d54032015-04-23 10:30:43 -07001120
1121 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001122 rescheduleKernelAlarmsLocked();
1123 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -07001124
1125 // And send a TIME_TICK right now, since it is important to get the UI updated.
Christopher Tatec8b7f432018-09-28 16:23:10 -07001126 mHandler.post(() -> getContext().sendBroadcastAsUser(mTimeTickIntent, UserHandle.ALL));
Christopher Tatee0a22b32013-07-11 14:43:13 -07001127 }
1128
Christopher Tate14a7bb02015-10-01 10:24:31 -07001129 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -08001130 final PendingIntent mPendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001131 final long mWhenElapsed;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001132 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -07001133 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001134 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001135 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001136 final BroadcastStats mBroadcastStats;
1137 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001138 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001139
Christopher Tate14a7bb02015-10-01 10:24:31 -07001140 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
1141 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
1142 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001143 mPendingIntent = pendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001144 mWhenElapsed = nowELAPSED;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001145 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -07001146 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001147 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001148 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001149 mBroadcastStats = (pendingIntent != null)
1150 ? service.getStatsLocked(pendingIntent)
1151 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001152 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001153 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001154 fs = new FilterStats(mBroadcastStats, mTag);
1155 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -08001156 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001157 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -08001158 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001159 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001160 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001161
1162 @Override
1163 public String toString() {
1164 return "InFlight{"
1165 + "pendingIntent=" + mPendingIntent
Christopher Tateeabba732017-08-17 17:12:52 -07001166 + ", when=" + mWhenElapsed
Makoto Onuki33955e12017-03-01 18:11:00 -08001167 + ", workSource=" + mWorkSource
1168 + ", uid=" + mUid
1169 + ", tag=" + mTag
1170 + ", broadcastStats=" + mBroadcastStats
1171 + ", filterStats=" + mFilterStats
1172 + ", alarmType=" + mAlarmType
1173 + "}";
1174 }
Kweku Adams61e03292017-10-19 14:27:12 -07001175
1176 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1177 final long token = proto.start(fieldId);
1178
1179 proto.write(InFlightProto.UID, mUid);
1180 proto.write(InFlightProto.TAG, mTag);
1181 proto.write(InFlightProto.WHEN_ELAPSED_MS, mWhenElapsed);
1182 proto.write(InFlightProto.ALARM_TYPE, mAlarmType);
1183 if (mPendingIntent != null) {
1184 mPendingIntent.writeToProto(proto, InFlightProto.PENDING_INTENT);
1185 }
1186 if (mBroadcastStats != null) {
1187 mBroadcastStats.writeToProto(proto, InFlightProto.BROADCAST_STATS);
1188 }
1189 if (mFilterStats != null) {
1190 mFilterStats.writeToProto(proto, InFlightProto.FILTER_STATS);
1191 }
1192 if (mWorkSource != null) {
1193 mWorkSource.writeToProto(proto, InFlightProto.WORK_SOURCE);
1194 }
1195
1196 proto.end(token);
1197 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001199
Adam Lesinski182f73f2013-12-05 16:48:06 -08001200 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -08001201 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001202 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001203
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001204 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -08001206 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001207 int numWakeup;
1208 long startTime;
1209 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -08001210
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001211 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001212 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001213 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001214 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001215
1216 @Override
1217 public String toString() {
1218 return "FilterStats{"
1219 + "tag=" + mTag
1220 + ", lastTime=" + lastTime
1221 + ", aggregateTime=" + aggregateTime
1222 + ", count=" + count
1223 + ", numWakeup=" + numWakeup
1224 + ", startTime=" + startTime
1225 + ", nesting=" + nesting
1226 + "}";
1227 }
Kweku Adams61e03292017-10-19 14:27:12 -07001228
1229 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1230 final long token = proto.start(fieldId);
1231
1232 proto.write(FilterStatsProto.TAG, mTag);
1233 proto.write(FilterStatsProto.LAST_FLIGHT_TIME_REALTIME, lastTime);
1234 proto.write(FilterStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1235 proto.write(FilterStatsProto.COUNT, count);
1236 proto.write(FilterStatsProto.WAKEUP_COUNT, numWakeup);
1237 proto.write(FilterStatsProto.START_TIME_REALTIME, startTime);
1238 proto.write(FilterStatsProto.NESTING, nesting);
1239
1240 proto.end(token);
1241 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001242 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001243
Adam Lesinski182f73f2013-12-05 16:48:06 -08001244 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001245 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001246 final String mPackageName;
1247
1248 long aggregateTime;
1249 int count;
1250 int numWakeup;
1251 long startTime;
1252 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001253 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -08001254
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001255 BroadcastStats(int uid, String packageName) {
1256 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001257 mPackageName = packageName;
1258 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001259
1260 @Override
1261 public String toString() {
1262 return "BroadcastStats{"
1263 + "uid=" + mUid
1264 + ", packageName=" + mPackageName
1265 + ", aggregateTime=" + aggregateTime
1266 + ", count=" + count
1267 + ", numWakeup=" + numWakeup
1268 + ", startTime=" + startTime
1269 + ", nesting=" + nesting
1270 + "}";
1271 }
Kweku Adams61e03292017-10-19 14:27:12 -07001272
1273 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1274 final long token = proto.start(fieldId);
1275
1276 proto.write(BroadcastStatsProto.UID, mUid);
1277 proto.write(BroadcastStatsProto.PACKAGE_NAME, mPackageName);
1278 proto.write(BroadcastStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1279 proto.write(BroadcastStatsProto.COUNT, count);
1280 proto.write(BroadcastStatsProto.WAKEUP_COUNT, numWakeup);
1281 proto.write(BroadcastStatsProto.START_TIME_REALTIME, startTime);
1282 proto.write(BroadcastStatsProto.NESTING, nesting);
1283
1284 proto.end(token);
1285 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001287
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001288 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
1289 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001290
1291 int mNumDelayedAlarms = 0;
1292 long mTotalDelayTime = 0;
1293 long mMaxDelayTime = 0;
1294
Adam Lesinski182f73f2013-12-05 16:48:06 -08001295 @Override
1296 public void onStart() {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001297 mInjector.init();
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001298
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001299 synchronized (mLock) {
1300 mHandler = new AlarmHandler(Looper.myLooper());
1301 mConstants = new Constants(mHandler);
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001302
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001303 mNextWakeup = mNextNonWakeup = 0;
1304
1305 // We have to set current TimeZone info to kernel
1306 // because kernel doesn't keep this after reboot
1307 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
1308
1309 // Also sure that we're booting with a halfway sensible current time
Christopher Tate247571462017-04-10 11:45:05 -07001310 final long systemBuildTime = Environment.getRootDirectory().lastModified();
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001311 if (mInjector.getCurrentTimeMillis() < systemBuildTime) {
1312 Slog.i(TAG, "Current time only " + mInjector.getCurrentTimeMillis()
Christopher Tate247571462017-04-10 11:45:05 -07001313 + ", advancing to build time " + systemBuildTime);
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001314 mInjector.setKernelTime(systemBuildTime);
Christopher Tate247571462017-04-10 11:45:05 -07001315 }
Christopher Tate247571462017-04-10 11:45:05 -07001316
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001317 // Determine SysUI's uid
1318 mSystemUiUid = mInjector.getSystemUiUid();
1319 if (mSystemUiUid <= 0) {
1320 Slog.wtf(TAG, "SysUI package not found!");
1321 }
1322 mWakeLock = mInjector.getAlarmWakeLock();
1323
Christopher Tatec8b7f432018-09-28 16:23:10 -07001324 mTimeTickIntent = new Intent(Intent.ACTION_TIME_TICK).addFlags(
1325 Intent.FLAG_RECEIVER_REGISTERED_ONLY
1326 | Intent.FLAG_RECEIVER_FOREGROUND
1327 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
1328
1329 mTimeTickTrigger = new IAlarmListener.Stub() {
1330 @Override
1331 public void doAlarm(final IAlarmCompleteListener callback) throws RemoteException {
1332 if (DEBUG_BATCH) {
1333 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
1334 }
1335
1336 // Via handler because dispatch invokes this within its lock. OnAlarmListener
1337 // takes care of this automatically, but we're using the direct internal
1338 // interface here rather than that client-side wrapper infrastructure.
1339 mHandler.post(() -> {
1340 getContext().sendBroadcastAsUser(mTimeTickIntent, UserHandle.ALL);
1341
1342 try {
1343 callback.alarmComplete(this);
1344 } catch (RemoteException e) { /* local method call */ }
1345 });
1346
1347 synchronized (mLock) {
1348 mLastTickReceived = mInjector.getCurrentTimeMillis();
1349 }
1350 mClockReceiver.scheduleTimeTickEvent();
1351 }
1352 };
1353
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001354 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
1355 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1356 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
1357 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
1358 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
1359
1360 mClockReceiver = mInjector.getClockReceiver(this);
1361 new InteractiveStateReceiver();
1362 new UninstallReceiver();
1363
1364 if (mInjector.isAlarmDriverPresent()) {
1365 AlarmThread waitThread = new AlarmThread();
1366 waitThread.start();
Christopher Tatebb9cce52017-04-18 14:19:43 -07001367 } else {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001368 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
Christopher Tatebb9cce52017-04-18 14:19:43 -07001369 }
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001370
1371 try {
1372 ActivityManager.getService().registerUidObserver(new UidObserver(),
1373 ActivityManager.UID_OBSERVER_GONE | ActivityManager.UID_OBSERVER_IDLE
1374 | ActivityManager.UID_OBSERVER_ACTIVE,
1375 ActivityManager.PROCESS_STATE_UNKNOWN, null);
1376 } catch (RemoteException e) {
1377 // ignored; both services live in system_server
1378 }
Christopher Tatebb9cce52017-04-18 14:19:43 -07001379 }
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001380 publishLocalService(AlarmManagerInternal.class, new LocalService());
Adam Lesinski182f73f2013-12-05 16:48:06 -08001381 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001383
1384 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001385 public void onBootPhase(int phase) {
1386 if (phase == PHASE_SYSTEM_SERVICES_READY) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001387 synchronized (mLock) {
1388 mConstants.start(getContext().getContentResolver());
1389 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
1390 mLocalDeviceIdleController =
1391 LocalServices.getService(DeviceIdleController.LocalService.class);
1392 mUsageStatsManagerInternal =
1393 LocalServices.getService(UsageStatsManagerInternal.class);
1394 mUsageStatsManagerInternal.addAppIdleStateChangeListener(new AppStandbyTracker());
Makoto Onukie4918212018-02-06 11:30:15 -08001395
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001396 mAppStateTracker = LocalServices.getService(AppStateTracker.class);
1397 mAppStateTracker.addListener(mForceAppStandbyListener);
1398
1399 mClockReceiver.scheduleTimeTickEvent();
1400 mClockReceiver.scheduleDateChangedEvent();
1401 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001402 }
1403 }
1404
1405 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406 protected void finalize() throws Throwable {
1407 try {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001408 mInjector.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 } finally {
1410 super.finalize();
1411 }
1412 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001413
mswest463f4c99d2018-02-01 10:13:10 -08001414 boolean setTimeImpl(long millis) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001415 if (!mInjector.isAlarmDriverPresent()) {
mswest463f4c99d2018-02-01 10:13:10 -08001416 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1417 return false;
1418 }
1419
1420 synchronized (mLock) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001421 final long currentTimeMillis = mInjector.getCurrentTimeMillis();
1422 mInjector.setKernelTime(millis);
Christine Hallstromf5d585a2018-05-21 14:27:23 -07001423 final TimeZone timeZone = TimeZone.getDefault();
1424 final int currentTzOffset = timeZone.getOffset(currentTimeMillis);
1425 final int newTzOffset = timeZone.getOffset(millis);
1426 if (currentTzOffset != newTzOffset) {
1427 Slog.i(TAG, "Timezone offset has changed, updating kernel timezone");
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001428 mInjector.setKernelTimezone(-(newTzOffset / 60000));
Christine Hallstromf5d585a2018-05-21 14:27:23 -07001429 }
1430 // The native implementation of setKernelTime can return -1 even when the kernel
1431 // time was set correctly, so assume setting kernel time was successful and always
1432 // return true.
1433 return true;
mswest463f4c99d2018-02-01 10:13:10 -08001434 }
1435 }
1436
Adam Lesinski182f73f2013-12-05 16:48:06 -08001437 void setTimeZoneImpl(String tz) {
1438 if (TextUtils.isEmpty(tz)) {
1439 return;
David Christieebe51fc2013-07-26 13:23:29 -07001440 }
1441
Adam Lesinski182f73f2013-12-05 16:48:06 -08001442 TimeZone zone = TimeZone.getTimeZone(tz);
1443 // Prevent reentrant calls from stepping on each other when writing
1444 // the time zone property
1445 boolean timeZoneWasChanged = false;
1446 synchronized (this) {
1447 String current = SystemProperties.get(TIMEZONE_PROPERTY);
1448 if (current == null || !current.equals(zone.getID())) {
1449 if (localLOGV) {
1450 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
1451 }
1452 timeZoneWasChanged = true;
1453 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
1454 }
1455
1456 // Update the kernel timezone information
1457 // Kernel tracks time offsets as 'minutes west of GMT'
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001458 int gmtOffset = zone.getOffset(mInjector.getCurrentTimeMillis());
1459 mInjector.setKernelTimezone(-(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001460 }
1461
1462 TimeZone.setDefault(null);
1463
1464 if (timeZoneWasChanged) {
1465 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001466 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate5cdf9f82017-05-03 18:10:39 -07001467 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
Chad Brubaker291df4f2017-03-14 10:23:02 -07001468 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001469 intent.putExtra("time-zone", zone.getID());
1470 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1471 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001473
Christopher Tatec8b7f432018-09-28 16:23:10 -07001474 void removeImpl(PendingIntent operation, IAlarmListener listener) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001475 synchronized (mLock) {
Christopher Tatec8b7f432018-09-28 16:23:10 -07001476 removeLocked(operation, listener);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001477 }
1478 }
1479
1480 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001481 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1482 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1483 int callingUid, String callingPackage) {
1484 // must be *either* PendingIntent or AlarmReceiver, but not both
1485 if ((operation == null && directReceiver == null)
1486 || (operation != null && directReceiver != null)) {
1487 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1488 // NB: previous releases failed silently here, so we are continuing to do the same
1489 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 return;
1491 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001492
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001493 // Sanity check the window length. This will catch people mistakenly
1494 // trying to pass an end-of-window timestamp rather than a duration.
1495 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1496 Slog.w(TAG, "Window length " + windowLength
1497 + "ms suspiciously long; limiting to 1 hour");
1498 windowLength = AlarmManager.INTERVAL_HOUR;
1499 }
1500
Christopher Tate498c6cb2014-11-17 16:09:27 -08001501 // Sanity check the recurrence interval. This will catch people who supply
Christopher Tate22e919d2018-02-16 16:16:50 -08001502 // seconds when the API expects milliseconds, or apps trying shenanigans
1503 // around intentional period overflow, etc.
Dianne Hackborna750a632015-06-16 17:18:23 -07001504 final long minInterval = mConstants.MIN_INTERVAL;
1505 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001506 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001507 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001508 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001509 interval = minInterval;
Christopher Tate22e919d2018-02-16 16:16:50 -08001510 } else if (interval > mConstants.MAX_INTERVAL) {
1511 Slog.w(TAG, "Suspiciously long interval " + interval
1512 + " millis; clamping");
1513 interval = mConstants.MAX_INTERVAL;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001514 }
1515
Christopher Tatee0a22b32013-07-11 14:43:13 -07001516 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1517 throw new IllegalArgumentException("Invalid alarm type " + type);
1518 }
1519
Christopher Tate5f221e82013-07-30 17:13:15 -07001520 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001521 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001522 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001523 + " pid=" + what);
1524 triggerAtTime = 0;
1525 }
1526
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001527 final long nowElapsed = mInjector.getElapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001528 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1529 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001530 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001531 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1532
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001533 final long maxElapsed;
1534 if (windowLength == AlarmManager.WINDOW_EXACT) {
1535 maxElapsed = triggerElapsed;
1536 } else if (windowLength < 0) {
1537 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001538 // Fix this window in place, so that as time approaches we don't collapse it.
1539 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001540 } else {
1541 maxElapsed = triggerElapsed + windowLength;
1542 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001545 if (DEBUG_BATCH) {
1546 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001547 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001548 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001549 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001551 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001552 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1553 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001554 }
1555 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556
Christopher Tate3e04b472013-10-21 17:51:31 -07001557 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001558 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1559 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1560 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001561 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001562 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1563 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001564 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001565 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001566 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1567 + " -- package not allowed to start");
1568 return;
1569 }
1570 } catch (RemoteException e) {
1571 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001572 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001573 setImplLocked(a, false, doValidate);
1574 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001575
Christopher Tatef2159712018-03-27 16:04:14 -07001576 /**
1577 * Return the minimum time that should elapse before an app in the specified bucket
1578 * can receive alarms again
1579 */
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001580 @VisibleForTesting
1581 long getMinDelayForBucketLocked(int bucket) {
Christopher Tatef2159712018-03-27 16:04:14 -07001582 // UsageStats bucket values are treated as floors of their behavioral range.
1583 // In other words, a bucket value between WORKING and ACTIVE is treated as
1584 // WORKING, not as ACTIVE. The ACTIVE and NEVER bucket apply only at specific
1585 // values.
1586 final int index;
1587
1588 if (bucket == UsageStatsManager.STANDBY_BUCKET_NEVER) index = NEVER_INDEX;
1589 else if (bucket > UsageStatsManager.STANDBY_BUCKET_FREQUENT) index = RARE_INDEX;
1590 else if (bucket > UsageStatsManager.STANDBY_BUCKET_WORKING_SET) index = FREQUENT_INDEX;
1591 else if (bucket > UsageStatsManager.STANDBY_BUCKET_ACTIVE) index = WORKING_INDEX;
1592 else index = ACTIVE_INDEX;
1593
1594 return mConstants.APP_STANDBY_MIN_DELAYS[index];
Suprabh Shukla75edab12018-01-29 14:09:06 -08001595 }
1596
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001597 /**
1598 * Adjusts the alarm delivery time based on the current app standby bucket.
1599 * @param alarm The alarm to adjust
1600 * @return true if the alarm delivery time was updated.
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001601 */
1602 private boolean adjustDeliveryTimeBasedOnStandbyBucketLocked(Alarm alarm) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001603 if (isExemptFromAppStandby(alarm)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001604 return false;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001605 }
1606 if (mAppStandbyParole) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001607 if (alarm.whenElapsed > alarm.expectedWhenElapsed) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001608 // We did defer this alarm earlier, restore original requirements
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001609 alarm.whenElapsed = alarm.expectedWhenElapsed;
1610 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
1611 return true;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001612 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001613 return false;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001614 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001615 final long oldWhenElapsed = alarm.whenElapsed;
1616 final long oldMaxWhenElapsed = alarm.maxWhenElapsed;
1617
Suprabh Shukla75edab12018-01-29 14:09:06 -08001618 final String sourcePackage = alarm.sourcePackage;
1619 final int sourceUserId = UserHandle.getUserId(alarm.creatorUid);
1620 final int standbyBucket = mUsageStatsManagerInternal.getAppStandbyBucket(
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001621 sourcePackage, sourceUserId, mInjector.getElapsedRealtime());
Suprabh Shukla75edab12018-01-29 14:09:06 -08001622
1623 final Pair<String, Integer> packageUser = Pair.create(sourcePackage, sourceUserId);
1624 final long lastElapsed = mLastAlarmDeliveredForPackage.getOrDefault(packageUser, 0L);
1625 if (lastElapsed > 0) {
1626 final long minElapsed = lastElapsed + getMinDelayForBucketLocked(standbyBucket);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001627 if (alarm.expectedWhenElapsed < minElapsed) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08001628 alarm.whenElapsed = alarm.maxWhenElapsed = minElapsed;
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001629 } else {
1630 // app is now eligible to run alarms at the originally requested window.
1631 // Restore original requirements in case they were changed earlier.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001632 alarm.whenElapsed = alarm.expectedWhenElapsed;
1633 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001634 }
1635 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001636 return (oldWhenElapsed != alarm.whenElapsed || oldMaxWhenElapsed != alarm.maxWhenElapsed);
Suprabh Shukla75edab12018-01-29 14:09:06 -08001637 }
1638
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001639 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1640 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001641 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001642 // The caller has given the time they want this to happen at, however we need
1643 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001644 // bring us out of idle at an earlier time.
1645 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001646 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001647 }
1648 // Add fuzz to make the alarm go off some time before the actual desired time.
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001649 final long nowElapsed = mInjector.getElapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001650 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001651 if (fuzz > 0) {
1652 if (mRandom == null) {
1653 mRandom = new Random();
1654 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001655 final int delta = mRandom.nextInt(fuzz);
1656 a.whenElapsed -= delta;
1657 if (false) {
1658 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1659 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1660 Slog.d(TAG, "Applied fuzz: " + fuzz);
1661 Slog.d(TAG, "Final delta: " + delta);
1662 Slog.d(TAG, "Final when: " + a.whenElapsed);
1663 }
1664 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001665 }
1666
1667 } else if (mPendingIdleUntil != null) {
1668 // We currently have an idle until alarm scheduled; if the new alarm has
1669 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001670 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1671 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1672 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001673 == 0) {
1674 mPendingWhileIdleAlarms.add(a);
1675 return;
1676 }
1677 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001678 if (RECORD_DEVICE_IDLE_ALARMS) {
1679 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1680 IdleDispatchEntry ent = new IdleDispatchEntry();
1681 ent.uid = a.uid;
1682 ent.pkg = a.operation.getCreatorPackage();
1683 ent.tag = a.operation.getTag("");
1684 ent.op = "SET";
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001685 ent.elapsedRealtime = mInjector.getElapsedRealtime();
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001686 ent.argRealtime = a.whenElapsed;
1687 mAllowWhileIdleDispatches.add(ent);
1688 }
1689 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08001690 adjustDeliveryTimeBasedOnStandbyBucketLocked(a);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001691 insertAndBatchAlarmLocked(a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001693 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001694 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001695 }
1696
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001697 boolean needRebatch = false;
1698
1699 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001700 if (RECORD_DEVICE_IDLE_ALARMS) {
1701 if (mPendingIdleUntil == null) {
1702 IdleDispatchEntry ent = new IdleDispatchEntry();
1703 ent.uid = 0;
1704 ent.pkg = "START IDLE";
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001705 ent.elapsedRealtime = mInjector.getElapsedRealtime();
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001706 mAllowWhileIdleDispatches.add(ent);
1707 }
1708 }
Makoto Onuki4274a6d2017-04-21 12:21:25 -07001709 if ((mPendingIdleUntil != a) && (mPendingIdleUntil != null)) {
1710 Slog.wtfStack(TAG, "setImplLocked: idle until changed from " + mPendingIdleUntil
1711 + " to " + a);
1712 }
1713
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001714 mPendingIdleUntil = a;
1715 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001716 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1717 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1718 mNextWakeFromIdle = a;
1719 // If this wake from idle is earlier than whatever was previously scheduled,
1720 // and we are currently idling, then we need to rebatch alarms in case the idle
1721 // until time needs to be updated.
1722 if (mPendingIdleUntil != null) {
1723 needRebatch = true;
1724 }
1725 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001726 }
1727
1728 if (!rebatching) {
1729 if (DEBUG_VALIDATE) {
1730 if (doValidate && !validateConsistencyLocked()) {
1731 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1732 + " when(hex)=" + Long.toHexString(a.when)
1733 + " whenElapsed=" + a.whenElapsed
1734 + " maxWhenElapsed=" + a.maxWhenElapsed
1735 + " interval=" + a.repeatInterval + " op=" + a.operation
1736 + " flags=0x" + Integer.toHexString(a.flags));
1737 rebatchAllAlarmsLocked(false);
1738 needRebatch = false;
1739 }
1740 }
1741
1742 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001743 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001744 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001745
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001746 rescheduleKernelAlarmsLocked();
1747 updateNextAlarmClockLocked();
1748 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001749 }
1750
Christopher Tate1d99c392017-12-07 16:54:04 -08001751 /**
1752 * System-process internal API
1753 */
1754 private final class LocalService implements AlarmManagerInternal {
1755 @Override
1756 public void removeAlarmsForUid(int uid) {
1757 synchronized (mLock) {
1758 removeLocked(uid);
1759 }
1760 }
1761 }
1762
1763 /**
1764 * Public-facing binder interface
1765 */
Adam Lesinski182f73f2013-12-05 16:48:06 -08001766 private final IBinder mService = new IAlarmManager.Stub() {
1767 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001768 public void set(String callingPackage,
1769 int type, long triggerAtTime, long windowLength, long interval, int flags,
1770 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1771 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001772 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001773
1774 // make sure the caller is not lying about which package should be blamed for
1775 // wakelock time spent in alarm delivery
1776 mAppOps.checkPackage(callingUid, callingPackage);
1777
1778 // Repeating alarms must use PendingIntent, not direct listener
1779 if (interval != 0) {
1780 if (directReceiver != null) {
1781 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1782 }
1783 }
1784
Adam Lesinski182f73f2013-12-05 16:48:06 -08001785 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001786 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001787 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001788 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001789 }
1790
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001791 // No incoming callers can request either WAKE_FROM_IDLE or
1792 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1793 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1794 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1795
1796 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1797 // manager when to come out of idle mode, which is only for DeviceIdleController.
1798 if (callingUid != Process.SYSTEM_UID) {
1799 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1800 }
1801
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001802 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001803 if (windowLength == AlarmManager.WINDOW_EXACT) {
1804 flags |= AlarmManager.FLAG_STANDALONE;
1805 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001806
1807 // If this alarm is for an alarm clock, then it must be standalone and we will
1808 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001809 if (alarmClock != null) {
1810 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001811
1812 // If the caller is a core system component or on the user's whitelist, and not calling
1813 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1814 // This means we will allow these alarms to go off as normal even while idle, with no
1815 // timing restrictions.
1816 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001817 || UserHandle.isSameApp(callingUid, mSystemUiUid)
Makoto Onukie4918212018-02-06 11:30:15 -08001818 || ((mAppStateTracker != null)
Suprabh Shukla5bf49812018-05-24 18:38:50 -07001819 && mAppStateTracker.isUidPowerSaveUserWhitelisted(callingUid)))) {
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001820 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1821 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001822 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001823
Christopher Tate14a7bb02015-10-01 10:24:31 -07001824 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1825 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001826 }
Christopher Tate89779822012-08-31 14:40:03 -07001827
Adam Lesinski182f73f2013-12-05 16:48:06 -08001828 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001829 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001830 getContext().enforceCallingOrSelfPermission(
1831 "android.permission.SET_TIME",
1832 "setTime");
1833
mswest463f4c99d2018-02-01 10:13:10 -08001834 return setTimeImpl(millis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001835 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001836
1837 @Override
1838 public void setTimeZone(String tz) {
1839 getContext().enforceCallingOrSelfPermission(
1840 "android.permission.SET_TIME_ZONE",
1841 "setTimeZone");
1842
1843 final long oldId = Binder.clearCallingIdentity();
1844 try {
1845 setTimeZoneImpl(tz);
1846 } finally {
1847 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001848 }
1849 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001850
Adam Lesinski182f73f2013-12-05 16:48:06 -08001851 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001852 public void remove(PendingIntent operation, IAlarmListener listener) {
1853 if (operation == null && listener == null) {
1854 Slog.w(TAG, "remove() with no intent or listener");
1855 return;
1856 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001857
Christopher Tate14a7bb02015-10-01 10:24:31 -07001858 synchronized (mLock) {
1859 removeLocked(operation, listener);
1860 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001861 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001862
Adam Lesinski182f73f2013-12-05 16:48:06 -08001863 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001864 public long getNextWakeFromIdleTime() {
1865 return getNextWakeFromIdleTimeImpl();
1866 }
1867
1868 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001869 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001870 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1871 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1872 "getNextAlarmClock", null);
1873
1874 return getNextAlarmClockImpl(userId);
1875 }
1876
1877 @Override
Jeff Sharkey9911a282018-02-14 22:29:11 -07001878 public long currentNetworkTimeMillis() {
1879 final NtpTrustedTime time = NtpTrustedTime.getInstance(getContext());
1880 if (time.hasCache()) {
1881 return time.currentTimeMillis();
1882 } else {
1883 throw new ParcelableException(new DateTimeException("Missing NTP fix"));
1884 }
1885 }
1886
1887 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001888 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06001889 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Kweku Adams61e03292017-10-19 14:27:12 -07001890
1891 if (args.length > 0 && "--proto".equals(args[0])) {
1892 dumpProto(fd);
1893 } else {
1894 dumpImpl(pw);
1895 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001896 }
mswest463f4c99d2018-02-01 10:13:10 -08001897
1898 @Override
1899 public void onShellCommand(FileDescriptor in, FileDescriptor out,
1900 FileDescriptor err, String[] args, ShellCallback callback,
1901 ResultReceiver resultReceiver) {
1902 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
1903 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001904 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001905
Adam Lesinski182f73f2013-12-05 16:48:06 -08001906 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 synchronized (mLock) {
1908 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001909 mConstants.dump(pw);
1910 pw.println();
1911
Makoto Onukie4918212018-02-06 11:30:15 -08001912 if (mAppStateTracker != null) {
1913 mAppStateTracker.dump(pw, " ");
1914 pw.println();
1915 }
Makoto Onuki2206af32017-11-21 16:25:35 -08001916
Suprabh Shukla75edab12018-01-29 14:09:06 -08001917 pw.println(" App Standby Parole: " + mAppStandbyParole);
1918 pw.println();
1919
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001920 final long nowELAPSED = mInjector.getElapsedRealtime();
Makoto Onukie8edbcf2018-03-02 16:49:29 -08001921 final long nowUPTIME = SystemClock.uptimeMillis();
Christopher Tatec8b7f432018-09-28 16:23:10 -07001922 final long nowRTC = mInjector.getCurrentTimeMillis();
Makoto Onuki5d93b832018-01-10 16:12:39 -08001923 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001924
Dianne Hackborna750a632015-06-16 17:18:23 -07001925 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001926 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001927 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001928 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001929 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001930 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001931 pw.print(" mLastTimeChangeRealtime="); pw.println(mLastTimeChangeRealtime);
Christopher Tate12cf0b62018-01-05 18:40:14 -08001932 pw.print(" mLastTickReceived="); pw.println(sdf.format(new Date(mLastTickReceived)));
1933 pw.print(" mLastTickSet="); pw.println(sdf.format(new Date(mLastTickSet)));
Makoto Onuki5d93b832018-01-10 16:12:39 -08001934 pw.print(" mLastTickAdded="); pw.println(sdf.format(new Date(mLastTickAdded)));
1935 pw.print(" mLastTickRemoved="); pw.println(sdf.format(new Date(mLastTickRemoved)));
Makoto Onukie8edbcf2018-03-02 16:49:29 -08001936
Christopher Tatec8b7f432018-09-28 16:23:10 -07001937 if (RECORD_ALARMS_IN_HISTORY) {
1938 pw.println();
1939 pw.println(" Recent TIME_TICK history:");
1940 int i = mNextTickHistory;
1941 do {
1942 i--;
1943 if (i < 0) i = TICK_HISTORY_DEPTH - 1;
1944 final long time = mTickHistory[i];
1945 pw.print(" ");
1946 pw.println((time > 0)
1947 ? sdf.format(new Date(nowRTC - (nowELAPSED - time)))
1948 : "-");
1949 } while (i != mNextTickHistory);
1950 pw.println();
1951 }
1952
Makoto Onukie8edbcf2018-03-02 16:49:29 -08001953 SystemServiceManager ssm = LocalServices.getService(SystemServiceManager.class);
1954 if (ssm != null) {
1955 pw.println();
1956 pw.print(" RuntimeStarted=");
1957 pw.print(sdf.format(
1958 new Date(nowRTC - nowELAPSED + ssm.getRuntimeStartElapsedTime())));
1959 if (ssm.isRuntimeRestarted()) {
1960 pw.print(" (Runtime restarted)");
1961 }
1962 pw.println();
1963 pw.print(" Runtime uptime (elapsed): ");
1964 TimeUtils.formatDuration(nowELAPSED, ssm.getRuntimeStartElapsedTime(), pw);
1965 pw.println();
1966 pw.print(" Runtime uptime (uptime): ");
1967 TimeUtils.formatDuration(nowUPTIME, ssm.getRuntimeStartUptime(), pw);
1968 pw.println();
1969 }
1970
Dianne Hackbornc3527222015-05-13 14:03:20 -07001971 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001972 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001973 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001974 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1975 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001976 }
Makoto Onuki0b05aa62018-02-09 16:14:26 -08001977 pw.print(" Max wakeup delay: ");
1978 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1979 pw.println();
1980 pw.print(" Time since last dispatch: ");
1981 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1982 pw.println();
1983 pw.print(" Next non-wakeup delivery time: ");
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07001984 TimeUtils.formatDuration(mNextNonWakeupDeliveryTime, nowELAPSED, pw);
Makoto Onuki0b05aa62018-02-09 16:14:26 -08001985 pw.println();
Christopher Tatee0a22b32013-07-11 14:43:13 -07001986
1987 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1988 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001989 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001990 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08001991 pw.print(" = "); pw.print(mNextNonWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001992 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07001993 pw.print(" set at "); TimeUtils.formatDuration(mNextNonWakeUpSetAt, nowELAPSED, pw);
1994 pw.println();
Christopher Tate8b98ade2018-02-09 11:13:19 -08001995 pw.print(" Next wakeup alarm: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
1996 pw.print(" = "); pw.print(mNextWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001997 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07001998 pw.print(" set at "); TimeUtils.formatDuration(mNextWakeUpSetAt, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08001999 pw.println();
Suprabh Shukla2324e982018-06-05 21:06:22 -07002000
2001 pw.print(" Next kernel non-wakeup alarm: ");
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002002 TimeUtils.formatDuration(mInjector.getNextAlarm(ELAPSED_REALTIME), pw);
Suprabh Shukla2324e982018-06-05 21:06:22 -07002003 pw.println();
2004 pw.print(" Next kernel wakeup alarm: ");
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002005 TimeUtils.formatDuration(mInjector.getNextAlarm(ELAPSED_REALTIME_WAKEUP), pw);
Suprabh Shukla2324e982018-06-05 21:06:22 -07002006 pw.println();
2007
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002008 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08002009 pw.print(" = "); pw.println(mLastWakeup);
2010 pw.print(" Last trigger: "); TimeUtils.formatDuration(mLastTrigger, nowELAPSED, pw);
2011 pw.print(" = "); pw.println(mLastTrigger);
Dianne Hackborna750a632015-06-16 17:18:23 -07002012 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002013
John Spurlock604a5ee2015-06-01 12:27:22 -04002014 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002015 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04002016 final TreeSet<Integer> users = new TreeSet<>();
2017 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
2018 users.add(mNextAlarmClockForUser.keyAt(i));
2019 }
2020 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
2021 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2022 }
2023 for (int user : users) {
2024 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2025 final long time = next != null ? next.getTriggerTime() : 0;
2026 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07002027 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04002028 pw.print(" pendingSend:"); pw.print(pendingSend);
2029 pw.print(" time:"); pw.print(time);
2030 if (time > 0) {
2031 pw.print(" = "); pw.print(sdf.format(new Date(time)));
2032 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
2033 }
2034 pw.println();
2035 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002036 if (mAlarmBatches.size() > 0) {
2037 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002038 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07002039 pw.println(mAlarmBatches.size());
2040 for (Batch b : mAlarmBatches) {
2041 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07002042 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002043 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002045 pw.println();
2046 pw.println(" Pending user blocked background alarms: ");
2047 boolean blocked = false;
2048 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2049 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2050 if (blockedAlarms != null && blockedAlarms.size() > 0) {
2051 blocked = true;
2052 dumpAlarmList(pw, blockedAlarms, " ", nowELAPSED, nowRTC, sdf);
2053 }
2054 }
2055 if (!blocked) {
2056 pw.println(" none");
2057 }
Suprabh Shuklac25447d2018-01-19 16:43:35 -08002058
Suprabh Shukla75edab12018-01-29 14:09:06 -08002059 pw.println(" mLastAlarmDeliveredForPackage:");
2060 for (int i = 0; i < mLastAlarmDeliveredForPackage.size(); i++) {
2061 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
2062 pw.print(" Package " + packageUser.first + ", User " + packageUser.second + ":");
2063 TimeUtils.formatDuration(mLastAlarmDeliveredForPackage.valueAt(i), nowELAPSED, pw);
2064 pw.println();
2065 }
2066 pw.println();
2067
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002068 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002069 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002070 pw.println(" Idle mode state:");
2071 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002072 if (mPendingIdleUntil != null) {
2073 pw.println(mPendingIdleUntil);
Kweku Adams61e03292017-10-19 14:27:12 -07002074 mPendingIdleUntil.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002075 } else {
2076 pw.println("null");
2077 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002078 pw.println(" Pending alarms:");
2079 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002080 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002081 if (mNextWakeFromIdle != null) {
2082 pw.println();
2083 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
Kweku Adams61e03292017-10-19 14:27:12 -07002084 mNextWakeFromIdle.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002085 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002086
2087 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002088 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002089 if (mPendingNonWakeupAlarms.size() > 0) {
2090 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07002091 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002092 } else {
2093 pw.println("(none)");
2094 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002095 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002096 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
2097 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002098 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002099 pw.print(", max non-interactive time: ");
2100 TimeUtils.formatDuration(mNonInteractiveTime, pw);
2101 pw.println();
2102
2103 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002104 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Christopher Tateeabba732017-08-17 17:12:52 -07002105 pw.print(" PendingIntent send count: "); pw.println(mSendCount);
2106 pw.print(" PendingIntent finish count: "); pw.println(mSendFinishCount);
2107 pw.print(" Listener send count: "); pw.println(mListenerCount);
2108 pw.print(" Listener finish count: "); pw.println(mListenerFinishCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08002109 pw.println();
2110
Christopher Tate7f2a0352015-12-08 10:24:33 -08002111 if (mInFlight.size() > 0) {
2112 pw.println("Outstanding deliveries:");
2113 for (int i = 0; i < mInFlight.size(); i++) {
2114 pw.print(" #"); pw.print(i); pw.print(": ");
2115 pw.println(mInFlight.get(i));
2116 }
2117 pw.println();
2118 }
2119
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002120 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002121 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002122 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
Makoto Onukiadb50d82018-01-29 16:20:30 -08002123 pw.print(" UID ");
2124 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2125 UserHandle.formatUid(pw, uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002126 pw.print(": ");
Makoto Onukiadb50d82018-01-29 16:20:30 -08002127 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2128 TimeUtils.formatDuration(lastTime, nowELAPSED, pw);
2129
2130 final long minInterval = getWhileIdleMinIntervalLocked(uid);
2131 pw.print(" Next allowed:");
2132 TimeUtils.formatDuration(lastTime + minInterval, nowELAPSED, pw);
2133 pw.print(" (");
2134 TimeUtils.formatDuration(minInterval, 0, pw);
2135 pw.print(")");
2136
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002137 pw.println();
2138 }
2139 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08002140
2141 pw.print(" mUseAllowWhileIdleShortTime: [");
2142 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2143 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
2144 UserHandle.formatUid(pw, mUseAllowWhileIdleShortTime.keyAt(i));
2145 pw.print(" ");
2146 }
2147 }
2148 pw.println("]");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002149 pw.println();
2150
Dianne Hackborn81038902012-11-26 17:04:09 -08002151 if (mLog.dump(pw, " Recent problems", " ")) {
2152 pw.println();
2153 }
2154
2155 final FilterStats[] topFilters = new FilterStats[10];
2156 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2157 @Override
2158 public int compare(FilterStats lhs, FilterStats rhs) {
2159 if (lhs.aggregateTime < rhs.aggregateTime) {
2160 return 1;
2161 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2162 return -1;
2163 }
2164 return 0;
2165 }
2166 };
2167 int len = 0;
Kweku Adams61e03292017-10-19 14:27:12 -07002168 // Get the top 10 FilterStats, ordered by aggregateTime.
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002169 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2170 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2171 for (int ip=0; ip<uidStats.size(); ip++) {
2172 BroadcastStats bs = uidStats.valueAt(ip);
2173 for (int is=0; is<bs.filterStats.size(); is++) {
2174 FilterStats fs = bs.filterStats.valueAt(is);
2175 int pos = len > 0
2176 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2177 if (pos < 0) {
2178 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08002179 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002180 if (pos < topFilters.length) {
2181 int copylen = topFilters.length - pos - 1;
2182 if (copylen > 0) {
2183 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2184 }
2185 topFilters[pos] = fs;
2186 if (len < topFilters.length) {
2187 len++;
2188 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002189 }
2190 }
2191 }
2192 }
2193 if (len > 0) {
2194 pw.println(" Top Alarms:");
2195 for (int i=0; i<len; i++) {
2196 FilterStats fs = topFilters[i];
2197 pw.print(" ");
2198 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2199 TimeUtils.formatDuration(fs.aggregateTime, pw);
2200 pw.print(" running, "); pw.print(fs.numWakeup);
2201 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002202 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
2203 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08002204 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002205 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08002206 pw.println();
2207 }
2208 }
2209
2210 pw.println(" ");
2211 pw.println(" Alarm Stats:");
2212 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002213 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2214 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2215 for (int ip=0; ip<uidStats.size(); ip++) {
2216 BroadcastStats bs = uidStats.valueAt(ip);
2217 pw.print(" ");
2218 if (bs.nesting > 0) pw.print("*ACTIVE* ");
2219 UserHandle.formatUid(pw, bs.mUid);
2220 pw.print(":");
2221 pw.print(bs.mPackageName);
2222 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
2223 pw.print(" running, "); pw.print(bs.numWakeup);
2224 pw.println(" wakeups:");
2225 tmpFilters.clear();
2226 for (int is=0; is<bs.filterStats.size(); is++) {
2227 tmpFilters.add(bs.filterStats.valueAt(is));
2228 }
2229 Collections.sort(tmpFilters, comparator);
2230 for (int i=0; i<tmpFilters.size(); i++) {
2231 FilterStats fs = tmpFilters.get(i);
2232 pw.print(" ");
2233 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2234 TimeUtils.formatDuration(fs.aggregateTime, pw);
2235 pw.print(" "); pw.print(fs.numWakeup);
2236 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002237 pw.print(" alarms, last ");
2238 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
2239 pw.println(":");
2240 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002241 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002242 pw.println();
2243 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002244 }
2245 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08002246 pw.println();
2247 mStatLogger.dump(pw, " ");
Christopher Tate18a75f12013-07-01 18:18:59 -07002248
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002249 if (RECORD_DEVICE_IDLE_ALARMS) {
2250 pw.println();
2251 pw.println(" Allow while idle dispatches:");
2252 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2253 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2254 pw.print(" ");
2255 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
2256 pw.print(": ");
2257 UserHandle.formatUid(pw, ent.uid);
2258 pw.print(":");
2259 pw.println(ent.pkg);
2260 if (ent.op != null) {
2261 pw.print(" ");
2262 pw.print(ent.op);
2263 pw.print(" / ");
2264 pw.print(ent.tag);
2265 if (ent.argRealtime != 0) {
2266 pw.print(" (");
2267 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
2268 pw.print(")");
2269 }
2270 pw.println();
2271 }
2272 }
2273 }
2274
Christopher Tate18a75f12013-07-01 18:18:59 -07002275 if (WAKEUP_STATS) {
2276 pw.println();
2277 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07002278 long last = -1;
2279 for (WakeupEvent event : mRecentWakeups) {
2280 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
2281 pw.print('|');
2282 if (last < 0) {
2283 pw.print('0');
2284 } else {
2285 pw.print(event.when - last);
2286 }
2287 last = event.when;
2288 pw.print('|'); pw.print(event.uid);
2289 pw.print('|'); pw.print(event.action);
2290 pw.println();
2291 }
2292 pw.println();
2293 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002294 }
2295 }
2296
Kweku Adams61e03292017-10-19 14:27:12 -07002297 void dumpProto(FileDescriptor fd) {
2298 final ProtoOutputStream proto = new ProtoOutputStream(fd);
2299
2300 synchronized (mLock) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002301 final long nowRTC = mInjector.getCurrentTimeMillis();
2302 final long nowElapsed = mInjector.getElapsedRealtime();
Yi Jin2b30f322018-02-20 15:41:47 -08002303 proto.write(AlarmManagerServiceDumpProto.CURRENT_TIME, nowRTC);
2304 proto.write(AlarmManagerServiceDumpProto.ELAPSED_REALTIME, nowElapsed);
2305 proto.write(AlarmManagerServiceDumpProto.LAST_TIME_CHANGE_CLOCK_TIME,
Kweku Adams61e03292017-10-19 14:27:12 -07002306 mLastTimeChangeClockTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002307 proto.write(AlarmManagerServiceDumpProto.LAST_TIME_CHANGE_REALTIME,
Kweku Adams61e03292017-10-19 14:27:12 -07002308 mLastTimeChangeRealtime);
2309
Yi Jin2b30f322018-02-20 15:41:47 -08002310 mConstants.dumpProto(proto, AlarmManagerServiceDumpProto.SETTINGS);
Kweku Adams61e03292017-10-19 14:27:12 -07002311
Makoto Onukie4918212018-02-06 11:30:15 -08002312 if (mAppStateTracker != null) {
2313 mAppStateTracker.dumpProto(proto,
Yi Jin2b30f322018-02-20 15:41:47 -08002314 AlarmManagerServiceDumpProto.FORCE_APP_STANDBY_TRACKER);
Makoto Onukie4918212018-02-06 11:30:15 -08002315 }
Kweku Adams61e03292017-10-19 14:27:12 -07002316
Yi Jin2b30f322018-02-20 15:41:47 -08002317 proto.write(AlarmManagerServiceDumpProto.IS_INTERACTIVE, mInteractive);
Kweku Adams61e03292017-10-19 14:27:12 -07002318 if (!mInteractive) {
2319 // Durations
Yi Jin2b30f322018-02-20 15:41:47 -08002320 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_NON_INTERACTIVE_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002321 nowElapsed - mNonInteractiveStartTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002322 proto.write(AlarmManagerServiceDumpProto.MAX_WAKEUP_DELAY_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002323 currentNonWakeupFuzzLocked(nowElapsed));
Yi Jin2b30f322018-02-20 15:41:47 -08002324 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_DISPATCH_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002325 nowElapsed - mLastAlarmDeliveryTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002326 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_NON_WAKEUP_DELIVERY_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002327 nowElapsed - mNextNonWakeupDeliveryTime);
2328 }
2329
Yi Jin2b30f322018-02-20 15:41:47 -08002330 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_NON_WAKEUP_ALARM_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002331 mNextNonWakeup - nowElapsed);
Yi Jin2b30f322018-02-20 15:41:47 -08002332 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_WAKEUP_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002333 mNextWakeup - nowElapsed);
Yi Jin2b30f322018-02-20 15:41:47 -08002334 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_WAKEUP_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002335 nowElapsed - mLastWakeup);
Yi Jin2b30f322018-02-20 15:41:47 -08002336 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_WAKEUP_SET_MS,
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002337 nowElapsed - mNextWakeUpSetAt);
Yi Jin2b30f322018-02-20 15:41:47 -08002338 proto.write(AlarmManagerServiceDumpProto.TIME_CHANGE_EVENT_COUNT, mNumTimeChanged);
Kweku Adams61e03292017-10-19 14:27:12 -07002339
2340 final TreeSet<Integer> users = new TreeSet<>();
2341 final int nextAlarmClockForUserSize = mNextAlarmClockForUser.size();
2342 for (int i = 0; i < nextAlarmClockForUserSize; i++) {
2343 users.add(mNextAlarmClockForUser.keyAt(i));
2344 }
2345 final int pendingSendNextAlarmClockChangedForUserSize =
2346 mPendingSendNextAlarmClockChangedForUser.size();
2347 for (int i = 0; i < pendingSendNextAlarmClockChangedForUserSize; i++) {
2348 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2349 }
2350 for (int user : users) {
2351 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2352 final long time = next != null ? next.getTriggerTime() : 0;
2353 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Yi Jin2b30f322018-02-20 15:41:47 -08002354 final long aToken = proto.start(AlarmManagerServiceDumpProto.NEXT_ALARM_CLOCK_METADATA);
Kweku Adams61e03292017-10-19 14:27:12 -07002355 proto.write(AlarmClockMetadataProto.USER, user);
2356 proto.write(AlarmClockMetadataProto.IS_PENDING_SEND, pendingSend);
2357 proto.write(AlarmClockMetadataProto.TRIGGER_TIME_MS, time);
2358 proto.end(aToken);
2359 }
2360 for (Batch b : mAlarmBatches) {
Yi Jin2b30f322018-02-20 15:41:47 -08002361 b.writeToProto(proto, AlarmManagerServiceDumpProto.PENDING_ALARM_BATCHES,
Kweku Adams61e03292017-10-19 14:27:12 -07002362 nowElapsed, nowRTC);
2363 }
2364 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2365 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2366 if (blockedAlarms != null) {
2367 for (Alarm a : blockedAlarms) {
2368 a.writeToProto(proto,
Yi Jin2b30f322018-02-20 15:41:47 -08002369 AlarmManagerServiceDumpProto.PENDING_USER_BLOCKED_BACKGROUND_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002370 nowElapsed, nowRTC);
2371 }
2372 }
2373 }
2374 if (mPendingIdleUntil != null) {
2375 mPendingIdleUntil.writeToProto(
Yi Jin2b30f322018-02-20 15:41:47 -08002376 proto, AlarmManagerServiceDumpProto.PENDING_IDLE_UNTIL, nowElapsed, nowRTC);
Kweku Adams61e03292017-10-19 14:27:12 -07002377 }
2378 for (Alarm a : mPendingWhileIdleAlarms) {
Yi Jin2b30f322018-02-20 15:41:47 -08002379 a.writeToProto(proto, AlarmManagerServiceDumpProto.PENDING_WHILE_IDLE_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002380 nowElapsed, nowRTC);
2381 }
2382 if (mNextWakeFromIdle != null) {
Yi Jin2b30f322018-02-20 15:41:47 -08002383 mNextWakeFromIdle.writeToProto(proto, AlarmManagerServiceDumpProto.NEXT_WAKE_FROM_IDLE,
Kweku Adams61e03292017-10-19 14:27:12 -07002384 nowElapsed, nowRTC);
2385 }
2386
2387 for (Alarm a : mPendingNonWakeupAlarms) {
Yi Jin2b30f322018-02-20 15:41:47 -08002388 a.writeToProto(proto, AlarmManagerServiceDumpProto.PAST_DUE_NON_WAKEUP_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002389 nowElapsed, nowRTC);
2390 }
2391
Yi Jin2b30f322018-02-20 15:41:47 -08002392 proto.write(AlarmManagerServiceDumpProto.DELAYED_ALARM_COUNT, mNumDelayedAlarms);
2393 proto.write(AlarmManagerServiceDumpProto.TOTAL_DELAY_TIME_MS, mTotalDelayTime);
2394 proto.write(AlarmManagerServiceDumpProto.MAX_DELAY_DURATION_MS, mMaxDelayTime);
2395 proto.write(AlarmManagerServiceDumpProto.MAX_NON_INTERACTIVE_DURATION_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002396 mNonInteractiveTime);
2397
Yi Jin2b30f322018-02-20 15:41:47 -08002398 proto.write(AlarmManagerServiceDumpProto.BROADCAST_REF_COUNT, mBroadcastRefCount);
2399 proto.write(AlarmManagerServiceDumpProto.PENDING_INTENT_SEND_COUNT, mSendCount);
2400 proto.write(AlarmManagerServiceDumpProto.PENDING_INTENT_FINISH_COUNT, mSendFinishCount);
2401 proto.write(AlarmManagerServiceDumpProto.LISTENER_SEND_COUNT, mListenerCount);
2402 proto.write(AlarmManagerServiceDumpProto.LISTENER_FINISH_COUNT, mListenerFinishCount);
Kweku Adams61e03292017-10-19 14:27:12 -07002403
2404 for (InFlight f : mInFlight) {
Yi Jin2b30f322018-02-20 15:41:47 -08002405 f.writeToProto(proto, AlarmManagerServiceDumpProto.OUTSTANDING_DELIVERIES);
Kweku Adams61e03292017-10-19 14:27:12 -07002406 }
2407
Kweku Adams61e03292017-10-19 14:27:12 -07002408 for (int i = 0; i < mLastAllowWhileIdleDispatch.size(); ++i) {
2409 final long token = proto.start(
Yi Jin2b30f322018-02-20 15:41:47 -08002410 AlarmManagerServiceDumpProto.LAST_ALLOW_WHILE_IDLE_DISPATCH_TIMES);
Makoto Onukiadb50d82018-01-29 16:20:30 -08002411 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2412 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2413
Yi Jin2b30f322018-02-20 15:41:47 -08002414 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.UID, uid);
2415 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.TIME_MS, lastTime);
2416 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.NEXT_ALLOWED_MS,
Makoto Onukiadb50d82018-01-29 16:20:30 -08002417 lastTime + getWhileIdleMinIntervalLocked(uid));
Kweku Adams61e03292017-10-19 14:27:12 -07002418 proto.end(token);
2419 }
2420
Makoto Onukiadb50d82018-01-29 16:20:30 -08002421 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2422 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
Yi Jin2b30f322018-02-20 15:41:47 -08002423 proto.write(AlarmManagerServiceDumpProto.USE_ALLOW_WHILE_IDLE_SHORT_TIME,
Makoto Onukiadb50d82018-01-29 16:20:30 -08002424 mUseAllowWhileIdleShortTime.keyAt(i));
2425 }
2426 }
2427
Yi Jin2b30f322018-02-20 15:41:47 -08002428 mLog.writeToProto(proto, AlarmManagerServiceDumpProto.RECENT_PROBLEMS);
Kweku Adams61e03292017-10-19 14:27:12 -07002429
2430 final FilterStats[] topFilters = new FilterStats[10];
2431 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2432 @Override
2433 public int compare(FilterStats lhs, FilterStats rhs) {
2434 if (lhs.aggregateTime < rhs.aggregateTime) {
2435 return 1;
2436 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2437 return -1;
2438 }
2439 return 0;
2440 }
2441 };
2442 int len = 0;
2443 // Get the top 10 FilterStats, ordered by aggregateTime.
2444 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2445 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2446 for (int ip = 0; ip < uidStats.size(); ++ip) {
2447 BroadcastStats bs = uidStats.valueAt(ip);
2448 for (int is = 0; is < bs.filterStats.size(); ++is) {
2449 FilterStats fs = bs.filterStats.valueAt(is);
2450 int pos = len > 0
2451 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2452 if (pos < 0) {
2453 pos = -pos - 1;
2454 }
2455 if (pos < topFilters.length) {
2456 int copylen = topFilters.length - pos - 1;
2457 if (copylen > 0) {
2458 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2459 }
2460 topFilters[pos] = fs;
2461 if (len < topFilters.length) {
2462 len++;
2463 }
2464 }
2465 }
2466 }
2467 }
2468 for (int i = 0; i < len; ++i) {
Yi Jin2b30f322018-02-20 15:41:47 -08002469 final long token = proto.start(AlarmManagerServiceDumpProto.TOP_ALARMS);
Kweku Adams61e03292017-10-19 14:27:12 -07002470 FilterStats fs = topFilters[i];
2471
Yi Jin2b30f322018-02-20 15:41:47 -08002472 proto.write(AlarmManagerServiceDumpProto.TopAlarm.UID, fs.mBroadcastStats.mUid);
2473 proto.write(AlarmManagerServiceDumpProto.TopAlarm.PACKAGE_NAME,
Kweku Adams61e03292017-10-19 14:27:12 -07002474 fs.mBroadcastStats.mPackageName);
Yi Jin2b30f322018-02-20 15:41:47 -08002475 fs.writeToProto(proto, AlarmManagerServiceDumpProto.TopAlarm.FILTER);
Kweku Adams61e03292017-10-19 14:27:12 -07002476
2477 proto.end(token);
2478 }
2479
2480 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
2481 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2482 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2483 for (int ip = 0; ip < uidStats.size(); ++ip) {
Yi Jin2b30f322018-02-20 15:41:47 -08002484 final long token = proto.start(AlarmManagerServiceDumpProto.ALARM_STATS);
Kweku Adams61e03292017-10-19 14:27:12 -07002485
2486 BroadcastStats bs = uidStats.valueAt(ip);
Yi Jin2b30f322018-02-20 15:41:47 -08002487 bs.writeToProto(proto, AlarmManagerServiceDumpProto.AlarmStat.BROADCAST);
Kweku Adams61e03292017-10-19 14:27:12 -07002488
2489 // uidStats is an ArrayMap, which we can't sort.
2490 tmpFilters.clear();
2491 for (int is = 0; is < bs.filterStats.size(); ++is) {
2492 tmpFilters.add(bs.filterStats.valueAt(is));
2493 }
2494 Collections.sort(tmpFilters, comparator);
2495 for (FilterStats fs : tmpFilters) {
Yi Jin2b30f322018-02-20 15:41:47 -08002496 fs.writeToProto(proto, AlarmManagerServiceDumpProto.AlarmStat.FILTERS);
Kweku Adams61e03292017-10-19 14:27:12 -07002497 }
2498
2499 proto.end(token);
2500 }
2501 }
2502
2503 if (RECORD_DEVICE_IDLE_ALARMS) {
2504 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2505 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2506 final long token = proto.start(
Yi Jin2b30f322018-02-20 15:41:47 -08002507 AlarmManagerServiceDumpProto.ALLOW_WHILE_IDLE_DISPATCHES);
Kweku Adams61e03292017-10-19 14:27:12 -07002508
2509 proto.write(IdleDispatchEntryProto.UID, ent.uid);
2510 proto.write(IdleDispatchEntryProto.PKG, ent.pkg);
2511 proto.write(IdleDispatchEntryProto.TAG, ent.tag);
2512 proto.write(IdleDispatchEntryProto.OP, ent.op);
2513 proto.write(IdleDispatchEntryProto.ENTRY_CREATION_REALTIME,
2514 ent.elapsedRealtime);
2515 proto.write(IdleDispatchEntryProto.ARG_REALTIME, ent.argRealtime);
2516
2517 proto.end(token);
2518 }
2519 }
2520
2521 if (WAKEUP_STATS) {
2522 for (WakeupEvent event : mRecentWakeups) {
Yi Jin2b30f322018-02-20 15:41:47 -08002523 final long token = proto.start(AlarmManagerServiceDumpProto.RECENT_WAKEUP_HISTORY);
Kweku Adams61e03292017-10-19 14:27:12 -07002524 proto.write(WakeupEventProto.UID, event.uid);
2525 proto.write(WakeupEventProto.ACTION, event.action);
2526 proto.write(WakeupEventProto.WHEN, event.when);
2527 proto.end(token);
2528 }
2529 }
2530 }
2531
2532 proto.flush();
2533 }
2534
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002535 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002536 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
2537 PrintWriter pw = new PrintWriter(bs);
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002538 final long nowRTC = mInjector.getCurrentTimeMillis();
2539 final long nowELAPSED = mInjector.getElapsedRealtime();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002540 final int NZ = mAlarmBatches.size();
2541 for (int iz = 0; iz < NZ; iz++) {
2542 Batch bz = mAlarmBatches.get(iz);
2543 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002544 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002545 pw.flush();
2546 Slog.v(TAG, bs.toString());
2547 bs.reset();
2548 }
2549 }
2550
2551 private boolean validateConsistencyLocked() {
2552 if (DEBUG_VALIDATE) {
2553 long lastTime = Long.MIN_VALUE;
2554 final int N = mAlarmBatches.size();
2555 for (int i = 0; i < N; i++) {
2556 Batch b = mAlarmBatches.get(i);
2557 if (b.start >= lastTime) {
2558 // duplicate start times are okay because of standalone batches
2559 lastTime = b.start;
2560 } else {
2561 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002562 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2563 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002564 return false;
2565 }
2566 }
2567 }
2568 return true;
2569 }
2570
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002571 private Batch findFirstWakeupBatchLocked() {
2572 final int N = mAlarmBatches.size();
2573 for (int i = 0; i < N; i++) {
2574 Batch b = mAlarmBatches.get(i);
2575 if (b.hasWakeups()) {
2576 return b;
2577 }
2578 }
2579 return null;
2580 }
2581
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002582 long getNextWakeFromIdleTimeImpl() {
2583 synchronized (mLock) {
2584 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
2585 }
2586 }
2587
2588 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002589 synchronized (mLock) {
2590 return mNextAlarmClockForUser.get(userId);
2591 }
2592 }
2593
2594 /**
2595 * Recomputes the next alarm clock for all users.
2596 */
2597 private void updateNextAlarmClockLocked() {
2598 if (!mNextAlarmClockMayChange) {
2599 return;
2600 }
2601 mNextAlarmClockMayChange = false;
2602
Jose Lima235510e2014-08-13 12:50:01 -07002603 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002604 nextForUser.clear();
2605
2606 final int N = mAlarmBatches.size();
2607 for (int i = 0; i < N; i++) {
2608 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
2609 final int M = alarms.size();
2610
2611 for (int j = 0; j < M; j++) {
2612 Alarm a = alarms.get(j);
2613 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002614 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07002615 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002616
2617 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07002618 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002619 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02002620 " for user " + userId);
2621 }
2622
2623 // Alarms and batches are sorted by time, no need to compare times here.
2624 if (nextForUser.get(userId) == null) {
2625 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07002626 } else if (a.alarmClock.equals(current)
2627 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
2628 // same/earlier time and it's the one we cited before, so stick with it
2629 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002630 }
2631 }
2632 }
2633 }
2634
2635 // Update mNextAlarmForUser with new values.
2636 final int NN = nextForUser.size();
2637 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07002638 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002639 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002640 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002641 if (!newAlarm.equals(currentAlarm)) {
2642 updateNextAlarmInfoForUserLocked(userId, newAlarm);
2643 }
2644 }
2645
2646 // Remove users without any alarm clocks scheduled.
2647 final int NNN = mNextAlarmClockForUser.size();
2648 for (int i = NNN - 1; i >= 0; i--) {
2649 int userId = mNextAlarmClockForUser.keyAt(i);
2650 if (nextForUser.get(userId) == null) {
2651 updateNextAlarmInfoForUserLocked(userId, null);
2652 }
2653 }
2654 }
2655
Jose Lima235510e2014-08-13 12:50:01 -07002656 private void updateNextAlarmInfoForUserLocked(int userId,
2657 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002658 if (alarmClock != null) {
2659 if (DEBUG_ALARM_CLOCK) {
2660 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002661 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02002662 }
2663 mNextAlarmClockForUser.put(userId, alarmClock);
2664 } else {
2665 if (DEBUG_ALARM_CLOCK) {
2666 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
2667 }
2668 mNextAlarmClockForUser.remove(userId);
2669 }
2670
2671 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
2672 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2673 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2674 }
2675
2676 /**
2677 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
2678 * for which alarm clocks have changed since the last call to this.
2679 *
2680 * Do not call with a lock held. Only call from mHandler's thread.
2681 *
2682 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
2683 */
2684 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07002685 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002686 pendingUsers.clear();
2687
2688 synchronized (mLock) {
2689 final int N = mPendingSendNextAlarmClockChangedForUser.size();
2690 for (int i = 0; i < N; i++) {
2691 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
2692 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
2693 }
2694 mPendingSendNextAlarmClockChangedForUser.clear();
2695 }
2696
2697 final int N = pendingUsers.size();
2698 for (int i = 0; i < N; i++) {
2699 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002700 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002701 Settings.System.putStringForUser(getContext().getContentResolver(),
2702 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01002703 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02002704 userId);
2705
2706 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
2707 new UserHandle(userId));
2708 }
2709 }
2710
2711 /**
2712 * Formats an alarm like platform/packages/apps/DeskClock used to.
2713 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01002714 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
2715 int userId) {
2716 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02002717 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
2718 return (info == null) ? "" :
2719 DateFormat.format(pattern, info.getTriggerTime()).toString();
2720 }
2721
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002722 /**
2723 * If the last time AlarmThread woke up precedes any due wakeup or non-wakeup alarm that we set
2724 * by more than half a minute, log a wtf.
2725 */
2726 private void validateLastAlarmExpiredLocked(long nowElapsed) {
2727 final StringBuilder errorMsg = new StringBuilder();
2728 boolean stuck = false;
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002729 if (mNextNonWakeup < (nowElapsed - 10_000) && mLastWakeup < mNextNonWakeup) {
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002730 stuck = true;
2731 errorMsg.append("[mNextNonWakeup=");
2732 TimeUtils.formatDuration(mNextNonWakeup - nowElapsed, errorMsg);
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002733 errorMsg.append(" set at ");
Suprabh Shukla673d34b2018-07-03 14:00:29 -07002734 TimeUtils.formatDuration(mNextNonWakeUpSetAt - nowElapsed, errorMsg);
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002735 errorMsg.append(", mLastWakeup=");
2736 TimeUtils.formatDuration(mLastWakeup - nowElapsed, errorMsg);
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002737 errorMsg.append(", timerfd_gettime=" + mInjector.getNextAlarm(ELAPSED_REALTIME));
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002738 errorMsg.append("];");
2739 }
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002740 if (mNextWakeup < (nowElapsed - 10_000) && mLastWakeup < mNextWakeup) {
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002741 stuck = true;
2742 errorMsg.append("[mNextWakeup=");
2743 TimeUtils.formatDuration(mNextWakeup - nowElapsed, errorMsg);
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002744 errorMsg.append(" set at ");
Suprabh Shukla673d34b2018-07-03 14:00:29 -07002745 TimeUtils.formatDuration(mNextWakeUpSetAt - nowElapsed, errorMsg);
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002746 errorMsg.append(", mLastWakeup=");
2747 TimeUtils.formatDuration(mLastWakeup - nowElapsed, errorMsg);
2748 errorMsg.append(", timerfd_gettime="
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002749 + mInjector.getNextAlarm(ELAPSED_REALTIME_WAKEUP));
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002750 errorMsg.append("];");
2751 }
2752 if (stuck) {
2753 Slog.wtf(TAG, "Alarm delivery stuck: " + errorMsg.toString());
2754 }
2755 }
2756
Adam Lesinski182f73f2013-12-05 16:48:06 -08002757 void rescheduleKernelAlarmsLocked() {
2758 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
2759 // prior to that which contains no wakeups, we schedule that as well.
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002760 final long nowElapsed = mInjector.getElapsedRealtime();
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002761 validateLastAlarmExpiredLocked(nowElapsed);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002762 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002763 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002764 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002765 final Batch firstBatch = mAlarmBatches.get(0);
Suprabh Shukla2fa95452018-02-12 12:53:23 -08002766 if (firstWakeup != null) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002767 mNextWakeup = firstWakeup.start;
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002768 mNextWakeUpSetAt = nowElapsed;
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002769 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002770 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002771 if (firstBatch != firstWakeup) {
2772 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002773 }
2774 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002775 if (mPendingNonWakeupAlarms.size() > 0) {
2776 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
2777 nextNonWakeup = mNextNonWakeupDeliveryTime;
2778 }
2779 }
Suprabh Shukla2fa95452018-02-12 12:53:23 -08002780 if (nextNonWakeup != 0) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002781 mNextNonWakeup = nextNonWakeup;
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002782 mNextNonWakeUpSetAt = nowElapsed;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002783 setLocked(ELAPSED_REALTIME, nextNonWakeup);
2784 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002785 }
2786
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002787 void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Christopher Tate1d99c392017-12-07 16:54:04 -08002788 if (operation == null && directReceiver == null) {
2789 if (localLOGV) {
2790 Slog.w(TAG, "requested remove() of null operation",
2791 new RuntimeException("here"));
2792 }
2793 return;
2794 }
2795
Adam Lesinski182f73f2013-12-05 16:48:06 -08002796 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002797 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002798 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2799 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002800 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002801 if (b.size() == 0) {
2802 mAlarmBatches.remove(i);
2803 }
2804 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002805 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002806 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002807 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2808 mPendingWhileIdleAlarms.remove(i);
2809 }
2810 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002811 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2812 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2813 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2814 if (alarmsForUid.get(j).matches(operation, directReceiver)) {
2815 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2816 alarmsForUid.remove(j);
2817 }
2818 }
2819 if (alarmsForUid.size() == 0) {
2820 mPendingBackgroundAlarms.removeAt(i);
2821 }
2822 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002823 if (didRemove) {
2824 if (DEBUG_BATCH) {
2825 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
2826 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002827 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002828 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002829 mPendingIdleUntil = null;
2830 restorePending = true;
2831 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002832 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002833 mNextWakeFromIdle = null;
2834 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002835 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002836 if (restorePending) {
2837 restorePendingWhileIdleAlarmsLocked();
2838 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002839 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002840 }
2841 }
2842
Christopher Tate1d99c392017-12-07 16:54:04 -08002843 void removeLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002844 if (uid == Process.SYSTEM_UID) {
2845 Slog.wtf(TAG, "removeLocked: Shouldn't for UID=" + uid);
2846 return;
2847 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002848 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002849 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.uid == uid;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002850 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2851 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002852 didRemove |= b.remove(whichAlarms);
2853 if (b.size() == 0) {
2854 mAlarmBatches.remove(i);
2855 }
2856 }
2857 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2858 final Alarm a = mPendingWhileIdleAlarms.get(i);
2859 if (a.uid == uid) {
2860 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2861 mPendingWhileIdleAlarms.remove(i);
2862 }
2863 }
2864 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2865 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2866 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2867 if (alarmsForUid.get(j).uid == uid) {
2868 alarmsForUid.remove(j);
2869 }
2870 }
2871 if (alarmsForUid.size() == 0) {
2872 mPendingBackgroundAlarms.removeAt(i);
2873 }
2874 }
2875 if (didRemove) {
2876 if (DEBUG_BATCH) {
2877 Slog.v(TAG, "remove(uid) changed bounds; rebatching");
2878 }
2879 rebatchAllAlarmsLocked(true);
2880 rescheduleKernelAlarmsLocked();
2881 updateNextAlarmClockLocked();
2882 }
2883 }
2884
2885 void removeLocked(final String packageName) {
2886 if (packageName == null) {
2887 if (localLOGV) {
2888 Slog.w(TAG, "requested remove() of null packageName",
2889 new RuntimeException("here"));
2890 }
2891 return;
2892 }
2893
2894 boolean didRemove = false;
2895 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(packageName);
Makoto Onuki5d93b832018-01-10 16:12:39 -08002896 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
Christopher Tate1d99c392017-12-07 16:54:04 -08002897 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2898 Batch b = mAlarmBatches.get(i);
2899 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002900 if (b.size() == 0) {
2901 mAlarmBatches.remove(i);
2902 }
2903 }
Makoto Onuki5d93b832018-01-10 16:12:39 -08002904 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
2905 if (oldHasTick != newHasTick) {
2906 Slog.wtf(TAG, "removeLocked: hasTick changed from " + oldHasTick + " to " + newHasTick);
2907 }
2908
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002909 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002910 final Alarm a = mPendingWhileIdleAlarms.get(i);
2911 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002912 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2913 mPendingWhileIdleAlarms.remove(i);
2914 }
2915 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002916 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2917 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2918 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2919 if (alarmsForUid.get(j).matches(packageName)) {
2920 alarmsForUid.remove(j);
2921 }
2922 }
2923 if (alarmsForUid.size() == 0) {
2924 mPendingBackgroundAlarms.removeAt(i);
2925 }
2926 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002927 if (didRemove) {
2928 if (DEBUG_BATCH) {
2929 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2930 }
2931 rebatchAllAlarmsLocked(true);
2932 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002933 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002934 }
2935 }
2936
Christopher Tate1d99c392017-12-07 16:54:04 -08002937 void removeForStoppedLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002938 if (uid == Process.SYSTEM_UID) {
2939 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for UID=" + uid);
2940 return;
2941 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002942 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002943 final Predicate<Alarm> whichAlarms = (Alarm a) -> {
2944 try {
2945 if (a.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
2946 uid, a.packageName)) {
2947 return true;
2948 }
2949 } catch (RemoteException e) { /* fall through */}
2950 return false;
2951 };
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002952 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2953 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002954 didRemove |= b.remove(whichAlarms);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002955 if (b.size() == 0) {
2956 mAlarmBatches.remove(i);
2957 }
2958 }
2959 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2960 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08002961 if (a.uid == uid) {
2962 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2963 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002964 }
2965 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002966 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2967 if (mPendingBackgroundAlarms.keyAt(i) == uid) {
2968 mPendingBackgroundAlarms.removeAt(i);
2969 }
2970 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002971 if (didRemove) {
2972 if (DEBUG_BATCH) {
2973 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2974 }
2975 rebatchAllAlarmsLocked(true);
2976 rescheduleKernelAlarmsLocked();
2977 updateNextAlarmClockLocked();
2978 }
2979 }
2980
Adam Lesinski182f73f2013-12-05 16:48:06 -08002981 void removeUserLocked(int userHandle) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002982 if (userHandle == UserHandle.USER_SYSTEM) {
2983 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for user=" + userHandle);
2984 return;
2985 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002986 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002987 final Predicate<Alarm> whichAlarms =
2988 (Alarm a) -> UserHandle.getUserId(a.creatorUid) == userHandle;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002989 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2990 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002991 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002992 if (b.size() == 0) {
2993 mAlarmBatches.remove(i);
2994 }
2995 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002996 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002997 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002998 == userHandle) {
2999 // Don't set didRemove, since this doesn't impact the scheduled alarms.
3000 mPendingWhileIdleAlarms.remove(i);
3001 }
3002 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003003 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
3004 if (UserHandle.getUserId(mPendingBackgroundAlarms.keyAt(i)) == userHandle) {
3005 mPendingBackgroundAlarms.removeAt(i);
3006 }
3007 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003008 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
3009 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
3010 mLastAllowWhileIdleDispatch.removeAt(i);
3011 }
3012 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003013
3014 if (didRemove) {
3015 if (DEBUG_BATCH) {
3016 Slog.v(TAG, "remove(user) changed bounds; rebatching");
3017 }
3018 rebatchAllAlarmsLocked(true);
3019 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02003020 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08003021 }
3022 }
3023
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003024 void interactiveStateChangedLocked(boolean interactive) {
3025 if (mInteractive != interactive) {
3026 mInteractive = interactive;
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003027 final long nowELAPSED = mInjector.getElapsedRealtime();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003028 if (interactive) {
3029 if (mPendingNonWakeupAlarms.size() > 0) {
3030 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3031 mTotalDelayTime += thisDelayTime;
3032 if (mMaxDelayTime < thisDelayTime) {
3033 mMaxDelayTime = thisDelayTime;
3034 }
3035 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
3036 mPendingNonWakeupAlarms.clear();
3037 }
3038 if (mNonInteractiveStartTime > 0) {
3039 long dur = nowELAPSED - mNonInteractiveStartTime;
3040 if (dur > mNonInteractiveTime) {
3041 mNonInteractiveTime = dur;
3042 }
3043 }
3044 } else {
3045 mNonInteractiveStartTime = nowELAPSED;
3046 }
3047 }
3048 }
3049
Adam Lesinski182f73f2013-12-05 16:48:06 -08003050 boolean lookForPackageLocked(String packageName) {
3051 for (int i = 0; i < mAlarmBatches.size(); i++) {
3052 Batch b = mAlarmBatches.get(i);
3053 if (b.hasPackage(packageName)) {
3054 return true;
3055 }
3056 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003057 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003058 final Alarm a = mPendingWhileIdleAlarms.get(i);
3059 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003060 return true;
3061 }
3062 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003063 return false;
3064 }
3065
3066 private void setLocked(int type, long when) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003067 if (mInjector.isAlarmDriverPresent()) {
3068 mInjector.setAlarm(type, when);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003069 } else {
3070 Message msg = Message.obtain();
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003071 msg.what = AlarmHandler.ALARM_EVENT;
Kweku Adams61e03292017-10-19 14:27:12 -07003072
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003073 mHandler.removeMessages(msg.what);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003074 mHandler.sendMessageAtTime(msg, when);
3075 }
3076 }
3077
Dianne Hackborn043fcd92010-10-06 14:27:34 -07003078 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Kweku Adams61e03292017-10-19 14:27:12 -07003079 String prefix, String label, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003080 for (int i=list.size()-1; i>=0; i--) {
3081 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003082 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
3083 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07003084 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003085 }
3086 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003087
3088 private static final String labelForType(int type) {
3089 switch (type) {
3090 case RTC: return "RTC";
3091 case RTC_WAKEUP : return "RTC_WAKEUP";
3092 case ELAPSED_REALTIME : return "ELAPSED";
3093 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
Christopher Tatee0a22b32013-07-11 14:43:13 -07003094 }
3095 return "--unknown--";
3096 }
3097
3098 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003099 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003100 for (int i=list.size()-1; i>=0; i--) {
3101 Alarm a = list.get(i);
3102 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003103 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
3104 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07003105 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003106 }
3107 }
3108
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003109 private boolean isBackgroundRestricted(Alarm alarm) {
Christopher Tateda3dc922018-05-09 13:49:41 -07003110 boolean exemptOnBatterySaver = (alarm.flags & FLAG_ALLOW_WHILE_IDLE) != 0;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003111 if (alarm.alarmClock != null) {
Christopher Tateda3dc922018-05-09 13:49:41 -07003112 // Don't defer alarm clocks
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003113 return false;
3114 }
Christopher Tateda3dc922018-05-09 13:49:41 -07003115 if (alarm.operation != null) {
3116 if (alarm.operation.isActivity()) {
3117 // Don't defer starting actual UI
3118 return false;
3119 }
3120 if (alarm.operation.isForegroundService()) {
3121 // FG service alarms are nearly as important; consult AST policy
3122 exemptOnBatterySaver = true;
3123 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003124 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003125 final String sourcePackage = alarm.sourcePackage;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003126 final int sourceUid = alarm.creatorUid;
Makoto Onukie4918212018-02-06 11:30:15 -08003127 return (mAppStateTracker != null) &&
Christopher Tateda3dc922018-05-09 13:49:41 -07003128 mAppStateTracker.areAlarmsRestricted(sourceUid, sourcePackage,
3129 exemptOnBatterySaver);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003130 }
3131
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003132 private static native long init();
3133 private static native void close(long nativeData);
3134 private static native int set(long nativeData, int type, long seconds, long nanoseconds);
3135 private static native int waitForAlarm(long nativeData);
3136 private static native int setKernelTime(long nativeData, long millis);
3137 private static native int setKernelTimezone(long nativeData, int minuteswest);
3138 private static native long getNextAlarm(long nativeData, int type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003139
Makoto Onukiadb50d82018-01-29 16:20:30 -08003140 private long getWhileIdleMinIntervalLocked(int uid) {
3141 final boolean dozing = mPendingIdleUntil != null;
Makoto Onukie4918212018-02-06 11:30:15 -08003142 final boolean ebs = (mAppStateTracker != null)
3143 && mAppStateTracker.isForceAllAppsStandbyEnabled();
Makoto Onukiadb50d82018-01-29 16:20:30 -08003144 if (!dozing && !ebs) {
3145 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
3146 }
3147 if (dozing) {
3148 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
3149 }
3150 if (mUseAllowWhileIdleShortTime.get(uid)) {
3151 // if the last allow-while-idle went off while uid was fg, or the uid
3152 // recently came into fg, don't block the alarm for long.
3153 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
3154 }
3155 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
3156 }
3157
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003158 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003159 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003160 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003161 // batches are temporally sorted, so we need only pull from the
3162 // start of the list until we either empty it or hit a batch
3163 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07003164 while (mAlarmBatches.size() > 0) {
3165 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003166 if (batch.start > nowELAPSED) {
3167 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003168 break;
3169 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003170
Christopher Tatee0a22b32013-07-11 14:43:13 -07003171 // We will (re)schedule some alarms now; don't let that interfere
3172 // with delivery of this current batch
3173 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07003174
Christopher Tatee0a22b32013-07-11 14:43:13 -07003175 final int N = batch.size();
3176 for (int i = 0; i < N; i++) {
3177 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003178
3179 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
3180 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
Christopher Tateddd1da142018-04-13 13:41:51 -07003181 // schedule such alarms. The first such alarm from an app is always delivered.
3182 final long lastTime = mLastAllowWhileIdleDispatch.get(alarm.creatorUid, -1);
Makoto Onukiadb50d82018-01-29 16:20:30 -08003183 final long minTime = lastTime + getWhileIdleMinIntervalLocked(alarm.creatorUid);
Christopher Tateddd1da142018-04-13 13:41:51 -07003184 if (lastTime >= 0 && nowELAPSED < minTime) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003185 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
3186 // alarm went off for this app. Reschedule the alarm to be in the
3187 // correct time period.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003188 alarm.expectedWhenElapsed = alarm.whenElapsed = minTime;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003189 if (alarm.maxWhenElapsed < minTime) {
3190 alarm.maxWhenElapsed = minTime;
3191 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003192 alarm.expectedMaxWhenElapsed = alarm.maxWhenElapsed;
Dianne Hackbornae78bf82015-10-26 13:33:20 -07003193 if (RECORD_DEVICE_IDLE_ALARMS) {
3194 IdleDispatchEntry ent = new IdleDispatchEntry();
3195 ent.uid = alarm.uid;
3196 ent.pkg = alarm.operation.getCreatorPackage();
3197 ent.tag = alarm.operation.getTag("");
3198 ent.op = "RESCHEDULE";
3199 ent.elapsedRealtime = nowELAPSED;
3200 ent.argRealtime = lastTime;
3201 mAllowWhileIdleDispatches.add(ent);
3202 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003203 setImplLocked(alarm, true, false);
3204 continue;
3205 }
3206 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003207 if (isBackgroundRestricted(alarm)) {
3208 // Alarms with FLAG_WAKE_FROM_IDLE or mPendingIdleUntil alarm are not deferred
3209 if (DEBUG_BG_LIMIT) {
3210 Slog.d(TAG, "Deferring alarm " + alarm + " due to user forced app standby");
3211 }
3212 ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(alarm.creatorUid);
3213 if (alarmsForUid == null) {
3214 alarmsForUid = new ArrayList<>();
3215 mPendingBackgroundAlarms.put(alarm.creatorUid, alarmsForUid);
3216 }
3217 alarmsForUid.add(alarm);
3218 continue;
3219 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003220
Christopher Tatee0a22b32013-07-11 14:43:13 -07003221 alarm.count = 1;
3222 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003223 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
3224 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003225 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003226 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003227 if (mPendingIdleUntil == alarm) {
3228 mPendingIdleUntil = null;
3229 rebatchAllAlarmsLocked(false);
3230 restorePendingWhileIdleAlarmsLocked();
3231 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003232 if (mNextWakeFromIdle == alarm) {
3233 mNextWakeFromIdle = null;
3234 rebatchAllAlarmsLocked(false);
3235 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003236
3237 // Recurring alarms may have passed several alarm intervals while the
3238 // phone was asleep or off, so pass a trigger count when sending them.
3239 if (alarm.repeatInterval > 0) {
3240 // this adjustment will be zero if we're late by
3241 // less than one full repeat interval
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003242 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003243
3244 // Also schedule its next recurrence
3245 final long delta = alarm.count * alarm.repeatInterval;
3246 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07003247 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07003248 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07003249 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
3250 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08003251 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003252
Christopher Tate864d42e2014-12-02 11:48:53 -08003253 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003254 hasWakeup = true;
3255 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003256
3257 // We removed an alarm clock. Let the caller recompute the next alarm clock.
3258 if (alarm.alarmClock != null) {
3259 mNextAlarmClockMayChange = true;
3260 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003262 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003263
Christopher Tate1590f1e2014-10-02 17:27:57 -07003264 // This is a new alarm delivery set; bump the sequence number to indicate that
3265 // all apps' alarm delivery classes should be recalculated.
3266 mCurrentSeq++;
3267 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003268 Collections.sort(triggerList, mAlarmDispatchComparator);
3269
3270 if (localLOGV) {
3271 for (int i=0; i<triggerList.size(); i++) {
3272 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
3273 }
3274 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003275
3276 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003277 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003279 /**
3280 * This Comparator sorts Alarms into increasing time order.
3281 */
3282 public static class IncreasingTimeOrder implements Comparator<Alarm> {
3283 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09003284 long when1 = a1.whenElapsed;
3285 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003286 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003287 return 1;
3288 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003289 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003290 return -1;
3291 }
3292 return 0;
3293 }
3294 }
Kweku Adams61e03292017-10-19 14:27:12 -07003295
Makoto Onuki2206af32017-11-21 16:25:35 -08003296 @VisibleForTesting
3297 static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003298 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003299 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003300 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003301 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003302 public final IAlarmListener listener;
3303 public final String listenerTag;
3304 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003305 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003306 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003307 public final AlarmManager.AlarmClockInfo alarmClock;
3308 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003309 public final int creatorUid;
3310 public final String packageName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003311 public final String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312 public int count;
3313 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07003314 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003315 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003316 public long maxWhenElapsed; // also in the elapsed time base
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003317 // Expected alarm expiry time before app standby deferring is applied.
3318 public long expectedWhenElapsed;
3319 public long expectedMaxWhenElapsed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003320 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07003321 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003322
Christopher Tate3e04b472013-10-21 17:51:31 -07003323 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003324 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
3325 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
3326 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003327 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003328 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003329 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
3330 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003331 when = _when;
3332 whenElapsed = _whenElapsed;
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003333 expectedWhenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07003334 windowLength = _windowLength;
Christopher Tate22e919d2018-02-16 16:16:50 -08003335 maxWhenElapsed = expectedMaxWhenElapsed = clampPositive(_maxWhen);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003336 repeatInterval = _interval;
3337 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003338 listener = _rec;
3339 listenerTag = _listenerTag;
3340 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07003341 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003342 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02003343 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003344 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003345 packageName = _pkgName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003346 sourcePackage = (operation != null) ? operation.getCreatorPackage() : packageName;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003347 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003348 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003349
Christopher Tate14a7bb02015-10-01 10:24:31 -07003350 public static String makeTag(PendingIntent pi, String tag, int type) {
3351 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
3352 ? "*walarm*:" : "*alarm*:";
3353 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
3354 }
3355
3356 public WakeupEvent makeWakeupEvent(long nowRTC) {
3357 return new WakeupEvent(nowRTC, creatorUid,
3358 (operation != null)
3359 ? operation.getIntent().getAction()
3360 : ("<listener>:" + listenerTag));
3361 }
3362
3363 // Returns true if either matches
3364 public boolean matches(PendingIntent pi, IAlarmListener rec) {
3365 return (operation != null)
3366 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09003367 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07003368 }
3369
3370 public boolean matches(String packageName) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003371 return packageName.equals(sourcePackage);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003372 }
3373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003374 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003375 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003376 StringBuilder sb = new StringBuilder(128);
3377 sb.append("Alarm{");
3378 sb.append(Integer.toHexString(System.identityHashCode(this)));
3379 sb.append(" type ");
3380 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003381 sb.append(" when ");
3382 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003383 sb.append(" ");
Suprabh Shukla75edab12018-01-29 14:09:06 -08003384 sb.append(sourcePackage);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003385 sb.append('}');
3386 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003387 }
3388
Kweku Adams61e03292017-10-19 14:27:12 -07003389 public void dump(PrintWriter pw, String prefix, long nowELAPSED, long nowRTC,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003390 SimpleDateFormat sdf) {
3391 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003392 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003393 pw.print(prefix); pw.print("type="); pw.print(type);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003394 pw.print(" expectedWhenElapsed="); TimeUtils.formatDuration(
3395 expectedWhenElapsed, nowELAPSED, pw);
3396 pw.print(" expectedMaxWhenElapsed="); TimeUtils.formatDuration(
3397 expectedMaxWhenElapsed, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003398 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
3399 nowELAPSED, pw);
Suprabh Shukla2fa95452018-02-12 12:53:23 -08003400 pw.print(" maxWhenElapsed="); TimeUtils.formatDuration(maxWhenElapsed,
3401 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003402 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003403 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003404 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003405 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003406 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003407 }
3408 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003409 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003410 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003411 pw.print(" count="); pw.print(count);
3412 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003413 if (alarmClock != null) {
3414 pw.print(prefix); pw.println("Alarm clock:");
3415 pw.print(prefix); pw.print(" triggerTime=");
3416 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
3417 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
3418 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003419 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003420 if (listener != null) {
3421 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
3422 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003423 }
Kweku Adams61e03292017-10-19 14:27:12 -07003424
3425 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
3426 long nowRTC) {
3427 final long token = proto.start(fieldId);
3428
3429 proto.write(AlarmProto.TAG, statsTag);
3430 proto.write(AlarmProto.TYPE, type);
Kweku Adams923ec432017-12-11 18:05:38 -08003431 proto.write(AlarmProto.TIME_UNTIL_WHEN_ELAPSED_MS, whenElapsed - nowElapsed);
Kweku Adams61e03292017-10-19 14:27:12 -07003432 proto.write(AlarmProto.WINDOW_LENGTH_MS, windowLength);
3433 proto.write(AlarmProto.REPEAT_INTERVAL_MS, repeatInterval);
3434 proto.write(AlarmProto.COUNT, count);
3435 proto.write(AlarmProto.FLAGS, flags);
3436 if (alarmClock != null) {
3437 alarmClock.writeToProto(proto, AlarmProto.ALARM_CLOCK);
3438 }
3439 if (operation != null) {
3440 operation.writeToProto(proto, AlarmProto.OPERATION);
3441 }
3442 if (listener != null) {
3443 proto.write(AlarmProto.LISTENER, listener.asBinder().toString());
3444 }
3445
3446 proto.end(token);
3447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003448 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003449
Christopher Tatee0a22b32013-07-11 14:43:13 -07003450 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
3451 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003452 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
3453 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003454 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07003455 break;
3456 }
3457
Christopher Tatee0a22b32013-07-11 14:43:13 -07003458 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003459 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
3460 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003461 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07003462 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003463 }
3464 }
3465
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003466 long currentNonWakeupFuzzLocked(long nowELAPSED) {
3467 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
3468 if (timeSinceOn < 5*60*1000) {
3469 // If the screen has been off for 5 minutes, only delay by at most two minutes.
3470 return 2*60*1000;
3471 } else if (timeSinceOn < 30*60*1000) {
3472 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
3473 return 15*60*1000;
3474 } else {
3475 // Otherwise, we will delay by at most an hour.
3476 return 60*60*1000;
3477 }
3478 }
3479
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003480 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003481 if (duration < 15*60*1000) {
3482 // If the duration until the time is less than 15 minutes, the maximum fuzz
3483 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003484 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003485 } else if (duration < 90*60*1000) {
3486 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
3487 return 15*60*1000;
3488 } else {
3489 // Otherwise, we will fuzz by at most half an hour.
3490 return 30*60*1000;
3491 }
3492 }
3493
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003494 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
3495 if (mInteractive) {
3496 return false;
3497 }
3498 if (mLastAlarmDeliveryTime <= 0) {
3499 return false;
3500 }
minho.choo649acab2014-12-12 16:13:55 +09003501 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003502 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
3503 // and the next delivery time is in the past, then just deliver them all. This
3504 // avoids bugs where we get stuck in a loop trying to poll for alarms.
3505 return false;
3506 }
3507 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
3508 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
3509 }
3510
3511 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
3512 mLastAlarmDeliveryTime = nowELAPSED;
3513 for (int i=0; i<triggerList.size(); i++) {
3514 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07003515 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Tim Murray175c0f92017-11-28 15:01:04 -08003516 if (alarm.wakeup) {
3517 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch wakeup alarm to " + alarm.packageName);
3518 } else {
3519 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch non-wakeup alarm to " + alarm.packageName);
3520 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003521 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07003522 if (localLOGV) {
3523 Slog.v(TAG, "sending alarm " + alarm);
3524 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07003525 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003526 ActivityManager.noteAlarmStart(alarm.operation, alarm.workSource, alarm.uid,
3527 alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003528 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003529 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003530 } catch (RuntimeException e) {
3531 Slog.w(TAG, "Failure sending alarm.", e);
3532 }
Tim Murray175c0f92017-11-28 15:01:04 -08003533 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003534 }
3535 }
3536
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003537 private boolean isExemptFromAppStandby(Alarm a) {
3538 return a.alarmClock != null || UserHandle.isCore(a.creatorUid)
3539 || (a.flags & FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED) != 0;
3540 }
3541
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003542 @VisibleForTesting
3543 static class Injector {
3544 private long mNativeData;
3545 private Context mContext;
3546
3547 Injector(Context context) {
3548 mContext = context;
3549 }
3550
3551 void init() {
3552 mNativeData = AlarmManagerService.init();
3553 }
3554
3555 int waitForAlarm() {
3556 return AlarmManagerService.waitForAlarm(mNativeData);
3557 }
3558
3559 boolean isAlarmDriverPresent() {
3560 return mNativeData != 0;
3561 }
3562
3563 void setAlarm(int type, long millis) {
3564 // The kernel never triggers alarms with negative wakeup times
3565 // so we ensure they are positive.
3566 final long alarmSeconds, alarmNanoseconds;
3567 if (millis < 0) {
3568 alarmSeconds = 0;
3569 alarmNanoseconds = 0;
3570 } else {
3571 alarmSeconds = millis / 1000;
3572 alarmNanoseconds = (millis % 1000) * 1000 * 1000;
3573 }
3574
3575 final int result = AlarmManagerService.set(mNativeData, type, alarmSeconds,
3576 alarmNanoseconds);
3577 if (result != 0) {
3578 final long nowElapsed = SystemClock.elapsedRealtime();
3579 Slog.wtf(TAG, "Unable to set kernel alarm, now=" + nowElapsed
3580 + " type=" + type + " @ (" + alarmSeconds + "," + alarmNanoseconds
3581 + "), ret = " + result + " = " + Os.strerror(result));
3582 }
3583 }
3584
3585 long getNextAlarm(int type) {
3586 return AlarmManagerService.getNextAlarm(mNativeData, type);
3587 }
3588
3589 void setKernelTimezone(int minutesWest) {
3590 AlarmManagerService.setKernelTimezone(mNativeData, minutesWest);
3591 }
3592
3593 void setKernelTime(long millis) {
3594 if (mNativeData != 0) {
3595 AlarmManagerService.setKernelTime(mNativeData, millis);
3596 }
3597 }
3598
3599 void close() {
3600 AlarmManagerService.close(mNativeData);
3601 }
3602
3603 long getElapsedRealtime() {
3604 return SystemClock.elapsedRealtime();
3605 }
3606
3607 long getCurrentTimeMillis() {
3608 return System.currentTimeMillis();
3609 }
3610
3611 PowerManager.WakeLock getAlarmWakeLock() {
3612 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
3613 return pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
3614 }
3615
3616 int getSystemUiUid() {
3617 int sysUiUid = -1;
3618 final PackageManager pm = mContext.getPackageManager();
3619 try {
3620 PermissionInfo sysUiPerm = pm.getPermissionInfo(SYSTEM_UI_SELF_PERMISSION, 0);
3621 ApplicationInfo sysUi = pm.getApplicationInfo(sysUiPerm.packageName, 0);
3622 if ((sysUi.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
3623 sysUiUid = sysUi.uid;
3624 } else {
3625 Slog.e(TAG, "SysUI permission " + SYSTEM_UI_SELF_PERMISSION
3626 + " defined by non-privileged app " + sysUi.packageName
3627 + " - ignoring");
3628 }
3629 } catch (NameNotFoundException e) {
3630 }
3631 return sysUiUid;
3632 }
3633
3634 ClockReceiver getClockReceiver(AlarmManagerService service) {
3635 return service.new ClockReceiver();
3636 }
3637 }
3638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003639 private class AlarmThread extends Thread
3640 {
Suprabh Shukla1d6a4032018-07-09 16:59:27 -07003641 private int mFalseWakeups;
3642 private int mWtfThreshold;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003643 public AlarmThread()
3644 {
3645 super("AlarmManager");
Suprabh Shukla1d6a4032018-07-09 16:59:27 -07003646 mFalseWakeups = 0;
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003647 mWtfThreshold = 100;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003648 }
Kweku Adams61e03292017-10-19 14:27:12 -07003649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003650 public void run()
3651 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003652 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003654 while (true)
3655 {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003656 int result = mInjector.waitForAlarm();
3657 final long nowRTC = mInjector.getCurrentTimeMillis();
3658 final long nowELAPSED = mInjector.getElapsedRealtime();
Christopher Tate8b98ade2018-02-09 11:13:19 -08003659 synchronized (mLock) {
3660 mLastWakeup = nowELAPSED;
3661 }
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003662 if (result == 0) {
3663 Slog.wtf(TAG, "waitForAlarm returned 0, nowRTC = " + nowRTC
3664 + ", nowElapsed = " + nowELAPSED);
3665 }
Christopher Tate8b98ade2018-02-09 11:13:19 -08003666 triggerList.clear();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003668 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003669 // The kernel can give us spurious time change notifications due to
3670 // small adjustments it makes internally; we want to filter those out.
3671 final long lastTimeChangeClockTime;
3672 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07003673 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003674 lastTimeChangeClockTime = mLastTimeChangeClockTime;
3675 expectedClockTime = lastTimeChangeClockTime
3676 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07003677 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003678 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
3679 || nowRTC > (expectedClockTime+1000)) {
3680 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07003681 // let's do it!
3682 if (DEBUG_BATCH) {
3683 Slog.v(TAG, "Time changed notification from kernel; rebatching");
3684 }
Bookatz7948c872018-09-04 12:58:33 -07003685 // StatsLog requires currentTimeMillis(), which == nowRTC to within usecs.
3686 StatsLog.write(StatsLog.WALL_CLOCK_TIME_SHIFTED, nowRTC);
Christopher Tatec8b7f432018-09-28 16:23:10 -07003687 removeImpl(null, mTimeTickTrigger);
3688 removeImpl(mDateChangeSender, null);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003689 rebatchAllAlarms();
3690 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07003691 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003692 synchronized (mLock) {
3693 mNumTimeChanged++;
3694 mLastTimeChangeClockTime = nowRTC;
3695 mLastTimeChangeRealtime = nowELAPSED;
3696 }
3697 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
3698 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003699 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07003700 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
3701 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003702 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
3703
3704 // The world has changed on us, so we need to re-evaluate alarms
3705 // regardless of whether the kernel has told us one went off.
3706 result |= IS_WAKEUP_MASK;
3707 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003708 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003709
Dianne Hackbornc3527222015-05-13 14:03:20 -07003710 if (result != TIME_CHANGED_MASK) {
3711 // If this was anything besides just a time change, then figure what if
3712 // anything to do about alarms.
3713 synchronized (mLock) {
3714 if (localLOGV) Slog.v(
3715 TAG, "Checking for alarms... rtc=" + nowRTC
3716 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07003717
Dianne Hackbornc3527222015-05-13 14:03:20 -07003718 if (WAKEUP_STATS) {
3719 if ((result & IS_WAKEUP_MASK) != 0) {
3720 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
3721 int n = 0;
3722 for (WakeupEvent event : mRecentWakeups) {
3723 if (event.when > newEarliest) break;
3724 n++; // number of now-stale entries at the list head
3725 }
3726 for (int i = 0; i < n; i++) {
3727 mRecentWakeups.remove();
3728 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003729
Dianne Hackbornc3527222015-05-13 14:03:20 -07003730 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003731 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003732 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003733
Christopher Tate8b98ade2018-02-09 11:13:19 -08003734 mLastTrigger = nowELAPSED;
Dianne Hackbornc3527222015-05-13 14:03:20 -07003735 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3736 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
3737 // if there are no wakeup alarms and the screen is off, we can
3738 // delay what we have so far until the future.
3739 if (mPendingNonWakeupAlarms.size() == 0) {
3740 mStartCurrentDelayTime = nowELAPSED;
3741 mNextNonWakeupDeliveryTime = nowELAPSED
3742 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
3743 }
3744 mPendingNonWakeupAlarms.addAll(triggerList);
3745 mNumDelayedAlarms += triggerList.size();
3746 rescheduleKernelAlarmsLocked();
3747 updateNextAlarmClockLocked();
3748 } else {
3749 // now deliver the alarm intents; if there are pending non-wakeup
3750 // alarms, we need to merge them in to the list. note we don't
3751 // just deliver them first because we generally want non-wakeup
3752 // alarms delivered after wakeup alarms.
Dianne Hackbornc3527222015-05-13 14:03:20 -07003753 if (mPendingNonWakeupAlarms.size() > 0) {
3754 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
3755 triggerList.addAll(mPendingNonWakeupAlarms);
3756 Collections.sort(triggerList, mAlarmDispatchComparator);
3757 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3758 mTotalDelayTime += thisDelayTime;
3759 if (mMaxDelayTime < thisDelayTime) {
3760 mMaxDelayTime = thisDelayTime;
3761 }
3762 mPendingNonWakeupAlarms.clear();
3763 }
Suprabh Shukla1d6a4032018-07-09 16:59:27 -07003764 if (mLastTimeChangeRealtime != nowELAPSED && triggerList.isEmpty()) {
3765 if (++mFalseWakeups >= mWtfThreshold) {
3766 Slog.wtf(TAG, "Too many (" + mFalseWakeups
3767 + ") false wakeups, nowElapsed=" + nowELAPSED);
3768 if (mWtfThreshold < 100_000) {
3769 mWtfThreshold *= 10;
3770 } else {
3771 mFalseWakeups = 0;
3772 }
3773 }
3774 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003775 final ArraySet<Pair<String, Integer>> triggerPackages =
3776 new ArraySet<>();
3777 for (int i = 0; i < triggerList.size(); i++) {
3778 final Alarm a = triggerList.get(i);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003779 if (!isExemptFromAppStandby(a)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003780 triggerPackages.add(Pair.create(
3781 a.sourcePackage, UserHandle.getUserId(a.creatorUid)));
Suprabh Shukla75edab12018-01-29 14:09:06 -08003782 }
3783 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003784 deliverAlarmsLocked(triggerList, nowELAPSED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003785 reorderAlarmsBasedOnStandbyBuckets(triggerPackages);
3786 rescheduleKernelAlarmsLocked();
3787 updateNextAlarmClockLocked();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003788 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003789 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003790
3791 } else {
3792 // Just in case -- even though no wakeup flag was set, make sure
3793 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07003794 synchronized (mLock) {
3795 rescheduleKernelAlarmsLocked();
3796 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003797 }
3798 }
3799 }
3800 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003801
David Christieebe51fc2013-07-26 13:23:29 -07003802 /**
3803 * Attribute blame for a WakeLock.
3804 * @param pi PendingIntent to attribute blame to if ws is null.
3805 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003806 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07003807 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003808 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003809 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07003810 try {
Christopher Tatec8b7f432018-09-28 16:23:10 -07003811 mWakeLock.setHistoryTag(first ? tag : null);
3812
David Christieebe51fc2013-07-26 13:23:29 -07003813 if (ws != null) {
3814 mWakeLock.setWorkSource(ws);
3815 return;
3816 }
3817
Christopher Tate14a7bb02015-10-01 10:24:31 -07003818 final int uid = (knownUid >= 0)
3819 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003820 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07003821 if (uid >= 0) {
3822 mWakeLock.setWorkSource(new WorkSource(uid));
3823 return;
3824 }
3825 } catch (Exception e) {
3826 }
3827
3828 // Something went wrong; fall back to attributing the lock to the OS
3829 mWakeLock.setWorkSource(null);
3830 }
3831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003832 private class AlarmHandler extends Handler {
3833 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003834 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
3835 public static final int LISTENER_TIMEOUT = 3;
3836 public static final int REPORT_ALARMS_ACTIVE = 4;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003837 public static final int APP_STANDBY_BUCKET_CHANGED = 5;
3838 public static final int APP_STANDBY_PAROLE_CHANGED = 6;
Makoto Onuki4d298b52018-02-05 10:54:58 -08003839 public static final int REMOVE_FOR_STOPPED = 7;
Kweku Adams61e03292017-10-19 14:27:12 -07003840
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003841 AlarmHandler(Looper looper) {
3842 super(looper);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003843 }
Kweku Adams61e03292017-10-19 14:27:12 -07003844
Makoto Onuki4d298b52018-02-05 10:54:58 -08003845 public void postRemoveForStopped(int uid) {
3846 obtainMessage(REMOVE_FOR_STOPPED, uid, 0).sendToTarget();
3847 }
3848
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003849 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003850 switch (msg.what) {
3851 case ALARM_EVENT: {
3852 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3853 synchronized (mLock) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003854 final long nowRTC = mInjector.getCurrentTimeMillis();
3855 final long nowELAPSED = mInjector.getElapsedRealtime();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003856 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3857 updateNextAlarmClockLocked();
3858 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003859
Christopher Tate14a7bb02015-10-01 10:24:31 -07003860 // now trigger the alarms without the lock held
3861 for (int i=0; i<triggerList.size(); i++) {
3862 Alarm alarm = triggerList.get(i);
3863 try {
3864 alarm.operation.send();
3865 } catch (PendingIntent.CanceledException e) {
3866 if (alarm.repeatInterval > 0) {
3867 // This IntentSender is no longer valid, but this
3868 // is a repeating alarm, so toss the hoser.
Christopher Tatec8b7f432018-09-28 16:23:10 -07003869 removeImpl(alarm.operation, null);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003870 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003871 }
3872 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003873 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003874 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003875
3876 case SEND_NEXT_ALARM_CLOCK_CHANGED:
3877 sendNextAlarmClockChanged();
3878 break;
3879
3880 case LISTENER_TIMEOUT:
3881 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
3882 break;
3883
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003884 case REPORT_ALARMS_ACTIVE:
3885 if (mLocalDeviceIdleController != null) {
3886 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
3887 }
3888 break;
3889
Suprabh Shukla75edab12018-01-29 14:09:06 -08003890 case APP_STANDBY_PAROLE_CHANGED:
3891 synchronized (mLock) {
3892 mAppStandbyParole = (Boolean) msg.obj;
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003893 if (reorderAlarmsBasedOnStandbyBuckets(null)) {
3894 rescheduleKernelAlarmsLocked();
3895 updateNextAlarmClockLocked();
3896 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003897 }
3898 break;
3899
3900 case APP_STANDBY_BUCKET_CHANGED:
3901 synchronized (mLock) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003902 final ArraySet<Pair<String, Integer>> filterPackages = new ArraySet<>();
3903 filterPackages.add(Pair.create((String) msg.obj, msg.arg1));
3904 if (reorderAlarmsBasedOnStandbyBuckets(filterPackages)) {
3905 rescheduleKernelAlarmsLocked();
3906 updateNextAlarmClockLocked();
3907 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003908 }
3909 break;
3910
Makoto Onuki4d298b52018-02-05 10:54:58 -08003911 case REMOVE_FOR_STOPPED:
3912 synchronized (mLock) {
3913 removeForStoppedLocked(msg.arg1);
3914 }
3915 break;
3916
Christopher Tate14a7bb02015-10-01 10:24:31 -07003917 default:
3918 // nope, just ignore it
3919 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003920 }
3921 }
3922 }
Kweku Adams61e03292017-10-19 14:27:12 -07003923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003924 class ClockReceiver extends BroadcastReceiver {
3925 public ClockReceiver() {
3926 IntentFilter filter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003927 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003928 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003929 }
Kweku Adams61e03292017-10-19 14:27:12 -07003930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003931 @Override
3932 public void onReceive(Context context, Intent intent) {
Christopher Tatec8b7f432018-09-28 16:23:10 -07003933 if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003934 // Since the kernel does not keep track of DST, we need to
3935 // reset the TZ information at the beginning of each day
3936 // based off of the current Zone gmt offset + userspace tracked
3937 // daylight savings information.
3938 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003939 int gmtOffset = zone.getOffset(mInjector.getCurrentTimeMillis());
3940 mInjector.setKernelTimezone(-(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07003941 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003942 }
3943 }
Kweku Adams61e03292017-10-19 14:27:12 -07003944
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003945 public void scheduleTimeTickEvent() {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003946 final long currentTime = mInjector.getCurrentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09003947 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07003948
3949 // Schedule this event for the amount of time that it would take to get to
3950 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09003951 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07003952
David Christieebe51fc2013-07-26 13:23:29 -07003953 final WorkSource workSource = null; // Let system take blame for time tick events.
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003954 setImpl(ELAPSED_REALTIME, mInjector.getElapsedRealtime() + tickEventDelay, 0,
Christopher Tatec8b7f432018-09-28 16:23:10 -07003955 0, null, mTimeTickTrigger, null, AlarmManager.FLAG_STANDALONE, workSource,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003956 null, Process.myUid(), "android");
Christopher Tate12cf0b62018-01-05 18:40:14 -08003957
3958 // Finally, remember when we set the tick alarm
3959 synchronized (mLock) {
3960 mLastTickSet = currentTime;
3961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003962 }
Christopher Tate385e4982013-07-23 18:22:29 -07003963
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003964 public void scheduleDateChangedEvent() {
3965 Calendar calendar = Calendar.getInstance();
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003966 calendar.setTimeInMillis(mInjector.getCurrentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07003967 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003968 calendar.set(Calendar.MINUTE, 0);
3969 calendar.set(Calendar.SECOND, 0);
3970 calendar.set(Calendar.MILLISECOND, 0);
3971 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07003972
3973 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003974 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
3975 AlarmManager.FLAG_STANDALONE, workSource, null,
3976 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003977 }
3978 }
Kweku Adams61e03292017-10-19 14:27:12 -07003979
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003980 class InteractiveStateReceiver extends BroadcastReceiver {
3981 public InteractiveStateReceiver() {
3982 IntentFilter filter = new IntentFilter();
3983 filter.addAction(Intent.ACTION_SCREEN_OFF);
3984 filter.addAction(Intent.ACTION_SCREEN_ON);
3985 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
3986 getContext().registerReceiver(this, filter);
3987 }
3988
3989 @Override
3990 public void onReceive(Context context, Intent intent) {
3991 synchronized (mLock) {
3992 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
3993 }
3994 }
3995 }
3996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003997 class UninstallReceiver extends BroadcastReceiver {
3998 public UninstallReceiver() {
3999 IntentFilter filter = new IntentFilter();
4000 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
4001 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004002 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004003 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08004004 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004005 // Register for events related to sdcard installation.
4006 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08004007 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004008 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07004009 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08004010 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004011 }
Kweku Adams61e03292017-10-19 14:27:12 -07004012
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004013 @Override
4014 public void onReceive(Context context, Intent intent) {
Christopher Tate1d99c392017-12-07 16:54:04 -08004015 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004016 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004017 String action = intent.getAction();
4018 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004019 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
4020 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4021 for (String packageName : pkgList) {
4022 if (lookForPackageLocked(packageName)) {
4023 setResultCode(Activity.RESULT_OK);
4024 return;
4025 }
4026 }
4027 return;
4028 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004029 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004030 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
4031 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
4032 if (userHandle >= 0) {
4033 removeUserLocked(userHandle);
Suprabh Shukla75edab12018-01-29 14:09:06 -08004034 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
4035 final Pair<String, Integer> packageUser =
4036 mLastAlarmDeliveredForPackage.keyAt(i);
4037 if (packageUser.second == userHandle) {
4038 mLastAlarmDeliveredForPackage.removeAt(i);
4039 }
4040 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004041 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07004042 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07004043 if (uid >= 0) {
4044 mLastAllowWhileIdleDispatch.delete(uid);
Makoto Onukiadb50d82018-01-29 16:20:30 -08004045 mUseAllowWhileIdleShortTime.delete(uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07004046 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004047 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08004048 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
4049 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
4050 // This package is being updated; don't kill its alarms.
4051 return;
4052 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004053 Uri data = intent.getData();
4054 if (data != null) {
4055 String pkg = data.getSchemeSpecificPart();
4056 if (pkg != null) {
4057 pkgList = new String[]{pkg};
4058 }
4059 }
4060 }
4061 if (pkgList != null && (pkgList.length > 0)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004062 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
4063 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
4064 if (ArrayUtils.contains(pkgList, packageUser.first)
4065 && packageUser.second == UserHandle.getUserId(uid)) {
4066 mLastAlarmDeliveredForPackage.removeAt(i);
4067 }
4068 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004069 for (String pkg : pkgList) {
Christopher Tate1d99c392017-12-07 16:54:04 -08004070 if (uid >= 0) {
4071 // package-removed case
4072 removeLocked(uid);
4073 } else {
4074 // external-applications-unavailable etc case
4075 removeLocked(pkg);
4076 }
Christopher Tate1590f1e2014-10-02 17:27:57 -07004077 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004078 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
4079 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
4080 if (uidStats.remove(pkg) != null) {
4081 if (uidStats.size() <= 0) {
4082 mBroadcastStats.removeAt(i);
4083 }
4084 }
4085 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004086 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004087 }
4088 }
4089 }
4090 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004091
4092 final class UidObserver extends IUidObserver.Stub {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004093 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004094 }
4095
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004096 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08004097 if (disabled) {
4098 mHandler.postRemoveForStopped(uid);
Dianne Hackborne07641d2016-11-09 15:07:23 -08004099 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004100 }
4101
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004102 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004103 }
4104
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004105 @Override public void onUidIdle(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08004106 if (disabled) {
4107 mHandler.postRemoveForStopped(uid);
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08004108 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004109 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004110
4111 @Override public void onUidCachedChanged(int uid, boolean cached) {
4112 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004113 };
4114
Suprabh Shukla75edab12018-01-29 14:09:06 -08004115 /**
4116 * Tracking of app assignments to standby buckets
4117 */
4118 final class AppStandbyTracker extends UsageStatsManagerInternal.AppIdleStateChangeListener {
4119 @Override
4120 public void onAppIdleStateChanged(final String packageName, final @UserIdInt int userId,
Amith Yamasani119be9a2018-02-18 22:23:00 -08004121 boolean idle, int bucket, int reason) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004122 if (DEBUG_STANDBY) {
4123 Slog.d(TAG, "Package " + packageName + " for user " + userId + " now in bucket " +
4124 bucket);
4125 }
4126 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08004127 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_BUCKET_CHANGED, userId, -1, packageName)
4128 .sendToTarget();
Suprabh Shukla75edab12018-01-29 14:09:06 -08004129 }
4130
4131 @Override
4132 public void onParoleStateChanged(boolean isParoleOn) {
4133 if (DEBUG_STANDBY) {
4134 Slog.d(TAG, "Global parole state now " + (isParoleOn ? "ON" : "OFF"));
4135 }
4136 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
4137 mHandler.removeMessages(AlarmHandler.APP_STANDBY_PAROLE_CHANGED);
4138 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_PAROLE_CHANGED,
4139 Boolean.valueOf(isParoleOn)).sendToTarget();
4140 }
4141 };
4142
Makoto Onuki2206af32017-11-21 16:25:35 -08004143 private final Listener mForceAppStandbyListener = new Listener() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004144 @Override
Makoto Onuki2206af32017-11-21 16:25:35 -08004145 public void unblockAllUnrestrictedAlarms() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004146 synchronized (mLock) {
Makoto Onuki2206af32017-11-21 16:25:35 -08004147 sendAllUnrestrictedPendingBackgroundAlarmsLocked();
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004148 }
4149 }
Makoto Onuki2206af32017-11-21 16:25:35 -08004150
4151 @Override
4152 public void unblockAlarmsForUid(int uid) {
4153 synchronized (mLock) {
4154 sendPendingBackgroundAlarmsLocked(uid, null);
4155 }
4156 }
4157
4158 @Override
4159 public void unblockAlarmsForUidPackage(int uid, String packageName) {
4160 synchronized (mLock) {
4161 sendPendingBackgroundAlarmsLocked(uid, packageName);
4162 }
4163 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08004164
4165 @Override
4166 public void onUidForeground(int uid, boolean foreground) {
4167 synchronized (mLock) {
4168 if (foreground) {
4169 mUseAllowWhileIdleShortTime.put(uid, true);
4170
4171 // Note we don't have to drain the pending while-idle alarms here, because
4172 // this event should coincide with unblockAlarmsForUid().
4173 }
4174 }
4175 }
Makoto Onuki2206af32017-11-21 16:25:35 -08004176 };
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004177
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004178 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004179 String pkg = pi.getCreatorPackage();
4180 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004181 return getStatsLocked(uid, pkg);
4182 }
4183
4184 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004185 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
4186 if (uidStats == null) {
4187 uidStats = new ArrayMap<String, BroadcastStats>();
4188 mBroadcastStats.put(uid, uidStats);
4189 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004190 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004191 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004192 bs = new BroadcastStats(uid, pkgName);
4193 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004194 }
4195 return bs;
4196 }
Dianne Hackborn81038902012-11-26 17:04:09 -08004197
Christopher Tate21e9f192017-08-08 13:49:11 -07004198 /**
4199 * Canonical count of (operation.send() - onSendFinished()) and
4200 * listener send/complete/timeout invocations.
4201 * Guarded by the usual lock.
4202 */
4203 @GuardedBy("mLock")
4204 private int mSendCount = 0;
4205 @GuardedBy("mLock")
Christopher Tateeabba732017-08-17 17:12:52 -07004206 private int mSendFinishCount = 0;
4207 @GuardedBy("mLock")
Christopher Tate21e9f192017-08-08 13:49:11 -07004208 private int mListenerCount = 0;
Christopher Tateeabba732017-08-17 17:12:52 -07004209 @GuardedBy("mLock")
4210 private int mListenerFinishCount = 0;
Christopher Tate21e9f192017-08-08 13:49:11 -07004211
Christopher Tate14a7bb02015-10-01 10:24:31 -07004212 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
Christopher Tate21e9f192017-08-08 13:49:11 -07004213
Christopher Tate14a7bb02015-10-01 10:24:31 -07004214 private InFlight removeLocked(PendingIntent pi, Intent intent) {
4215 for (int i = 0; i < mInFlight.size(); i++) {
Christopher Tatedb9ae422017-08-21 11:24:30 -07004216 if (mInFlight.get(i).mPendingIntent == pi) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004217 return mInFlight.remove(i);
4218 }
4219 }
4220 mLog.w("No in-flight alarm for " + pi + " " + intent);
4221 return null;
4222 }
4223
4224 private InFlight removeLocked(IBinder listener) {
4225 for (int i = 0; i < mInFlight.size(); i++) {
4226 if (mInFlight.get(i).mListener == listener) {
4227 return mInFlight.remove(i);
4228 }
4229 }
4230 mLog.w("No in-flight alarm for listener " + listener);
4231 return null;
4232 }
4233
4234 private void updateStatsLocked(InFlight inflight) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07004235 final long nowELAPSED = mInjector.getElapsedRealtime();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004236 BroadcastStats bs = inflight.mBroadcastStats;
4237 bs.nesting--;
4238 if (bs.nesting <= 0) {
4239 bs.nesting = 0;
4240 bs.aggregateTime += nowELAPSED - bs.startTime;
4241 }
4242 FilterStats fs = inflight.mFilterStats;
4243 fs.nesting--;
4244 if (fs.nesting <= 0) {
4245 fs.nesting = 0;
4246 fs.aggregateTime += nowELAPSED - fs.startTime;
4247 }
4248 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00004249 ActivityManager.noteAlarmFinish(inflight.mPendingIntent, inflight.mWorkSource,
4250 inflight.mUid, inflight.mTag);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004251 }
4252 }
4253
4254 private void updateTrackingLocked(InFlight inflight) {
4255 if (inflight != null) {
4256 updateStatsLocked(inflight);
4257 }
4258 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004259 if (DEBUG_WAKELOCK) {
4260 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
4261 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004262 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004263 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004264 mWakeLock.release();
4265 if (mInFlight.size() > 0) {
4266 mLog.w("Finished all dispatches with " + mInFlight.size()
4267 + " remaining inflights");
4268 for (int i=0; i<mInFlight.size(); i++) {
4269 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
4270 }
4271 mInFlight.clear();
4272 }
4273 } else {
4274 // the next of our alarms is now in flight. reattribute the wakelock.
4275 if (mInFlight.size() > 0) {
4276 InFlight inFlight = mInFlight.get(0);
4277 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
4278 inFlight.mAlarmType, inFlight.mTag, -1, false);
4279 } else {
4280 // should never happen
4281 mLog.w("Alarm wakelock still held but sent queue empty");
4282 mWakeLock.setWorkSource(null);
4283 }
4284 }
4285 }
4286
4287 /**
4288 * Callback that arrives when a direct-call alarm reports that delivery has finished
4289 */
4290 @Override
4291 public void alarmComplete(IBinder who) {
4292 if (who == null) {
Christopher Tate21e9f192017-08-08 13:49:11 -07004293 mLog.w("Invalid alarmComplete: uid=" + Binder.getCallingUid()
Christopher Tate14a7bb02015-10-01 10:24:31 -07004294 + " pid=" + Binder.getCallingPid());
4295 return;
4296 }
4297
4298 final long ident = Binder.clearCallingIdentity();
4299 try {
4300 synchronized (mLock) {
4301 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
4302 InFlight inflight = removeLocked(who);
4303 if (inflight != null) {
4304 if (DEBUG_LISTENER_CALLBACK) {
4305 Slog.i(TAG, "alarmComplete() from " + who);
4306 }
4307 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004308 mListenerFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004309 } else {
4310 // Delivery timed out, and the timeout handling already took care of
4311 // updating our tracking here, so we needn't do anything further.
4312 if (DEBUG_LISTENER_CALLBACK) {
4313 Slog.i(TAG, "Late alarmComplete() from " + who);
4314 }
4315 }
4316 }
4317 } finally {
4318 Binder.restoreCallingIdentity(ident);
4319 }
4320 }
4321
4322 /**
4323 * Callback that arrives when a PendingIntent alarm has finished delivery
4324 */
4325 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004326 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
4327 String resultData, Bundle resultExtras) {
4328 synchronized (mLock) {
Christopher Tateeabba732017-08-17 17:12:52 -07004329 mSendFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004330 updateTrackingLocked(removeLocked(pi, intent));
4331 }
4332 }
4333
4334 /**
4335 * Timeout of a direct-call alarm delivery
4336 */
4337 public void alarmTimedOut(IBinder who) {
4338 synchronized (mLock) {
4339 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08004340 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004341 // TODO: implement ANR policy for the target
4342 if (DEBUG_LISTENER_CALLBACK) {
4343 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004344 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004345 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004346 mListenerFinishCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08004347 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004348 if (DEBUG_LISTENER_CALLBACK) {
4349 Slog.i(TAG, "Spurious timeout of listener " + who);
4350 }
Christopher Tate21e9f192017-08-08 13:49:11 -07004351 mLog.w("Spurious timeout of listener " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004352 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004353 }
4354 }
4355
4356 /**
4357 * Deliver an alarm and set up the post-delivery handling appropriately
4358 */
Andreas Gampea36dc622018-02-05 17:19:22 -08004359 @GuardedBy("mLock")
Christopher Tate14a7bb02015-10-01 10:24:31 -07004360 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
4361 if (alarm.operation != null) {
4362 // PendingIntent alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004363 mSendCount++;
Christopher Tate12cf0b62018-01-05 18:40:14 -08004364
Christopher Tate14a7bb02015-10-01 10:24:31 -07004365 try {
4366 alarm.operation.send(getContext(), 0,
4367 mBackgroundIntent.putExtra(
4368 Intent.EXTRA_ALARM_COUNT, alarm.count),
4369 mDeliveryTracker, mHandler, null,
4370 allowWhileIdle ? mIdleOptions : null);
4371 } catch (PendingIntent.CanceledException e) {
4372 if (alarm.repeatInterval > 0) {
4373 // This IntentSender is no longer valid, but this
4374 // is a repeating alarm, so toss it
Christopher Tatec8b7f432018-09-28 16:23:10 -07004375 removeImpl(alarm.operation, null);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004376 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004377 // No actual delivery was possible, so the delivery tracker's
4378 // 'finished' callback won't be invoked. We also don't need
4379 // to do any wakelock or stats tracking, so we have nothing
4380 // left to do here but go on to the next thing.
Christopher Tateeabba732017-08-17 17:12:52 -07004381 mSendFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004382 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004383 }
4384 } else {
4385 // Direct listener callback alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004386 mListenerCount++;
Christopher Tatec8b7f432018-09-28 16:23:10 -07004387
4388 if (RECORD_ALARMS_IN_HISTORY) {
4389 if (alarm.listener == mTimeTickTrigger) {
4390 mTickHistory[mNextTickHistory++] = nowELAPSED;
4391 if (mNextTickHistory >= TICK_HISTORY_DEPTH) {
4392 mNextTickHistory = 0;
4393 }
4394 }
4395 }
4396
Christopher Tate14a7bb02015-10-01 10:24:31 -07004397 try {
4398 if (DEBUG_LISTENER_CALLBACK) {
4399 Slog.v(TAG, "Alarm to uid=" + alarm.uid
4400 + " listener=" + alarm.listener.asBinder());
4401 }
4402 alarm.listener.doAlarm(this);
4403 mHandler.sendMessageDelayed(
4404 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
4405 alarm.listener.asBinder()),
4406 mConstants.LISTENER_TIMEOUT);
4407 } catch (Exception e) {
4408 if (DEBUG_LISTENER_CALLBACK) {
4409 Slog.i(TAG, "Alarm undeliverable to listener "
4410 + alarm.listener.asBinder(), e);
4411 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004412 // As in the PendingIntent.CanceledException case, delivery of the
4413 // alarm was not possible, so we have no wakelock or timeout or
4414 // stats management to do. It threw before we posted the delayed
4415 // timeout message, so we're done here.
Christopher Tateeabba732017-08-17 17:12:52 -07004416 mListenerFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004417 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004418 }
4419 }
4420
4421 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004422 if (DEBUG_WAKELOCK) {
4423 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
4424 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004425 if (mBroadcastRefCount == 0) {
4426 setWakelockWorkSource(alarm.operation, alarm.workSource,
4427 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
4428 true);
4429 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004430 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004431 }
4432 final InFlight inflight = new InFlight(AlarmManagerService.this,
4433 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
4434 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
4435 mInFlight.add(inflight);
4436 mBroadcastRefCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004437 if (allowWhileIdle) {
4438 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004439 mLastAllowWhileIdleDispatch.put(alarm.creatorUid, nowELAPSED);
Makoto Onukie4918212018-02-06 11:30:15 -08004440 if ((mAppStateTracker == null)
4441 || mAppStateTracker.isUidInForeground(alarm.creatorUid)) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004442 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, true);
4443 } else {
4444 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, false);
4445 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004446 if (RECORD_DEVICE_IDLE_ALARMS) {
4447 IdleDispatchEntry ent = new IdleDispatchEntry();
4448 ent.uid = alarm.uid;
4449 ent.pkg = alarm.packageName;
4450 ent.tag = alarm.statsTag;
4451 ent.op = "DELIVER";
4452 ent.elapsedRealtime = nowELAPSED;
4453 mAllowWhileIdleDispatches.add(ent);
4454 }
4455 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08004456 if (!isExemptFromAppStandby(alarm)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004457 final Pair<String, Integer> packageUser = Pair.create(alarm.sourcePackage,
4458 UserHandle.getUserId(alarm.creatorUid));
4459 mLastAlarmDeliveredForPackage.put(packageUser, nowELAPSED);
4460 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004461
4462 final BroadcastStats bs = inflight.mBroadcastStats;
4463 bs.count++;
4464 if (bs.nesting == 0) {
4465 bs.nesting = 1;
4466 bs.startTime = nowELAPSED;
4467 } else {
4468 bs.nesting++;
4469 }
4470 final FilterStats fs = inflight.mFilterStats;
4471 fs.count++;
4472 if (fs.nesting == 0) {
4473 fs.nesting = 1;
4474 fs.startTime = nowELAPSED;
4475 } else {
4476 fs.nesting++;
4477 }
4478 if (alarm.type == ELAPSED_REALTIME_WAKEUP
4479 || alarm.type == RTC_WAKEUP) {
4480 bs.numWakeup++;
4481 fs.numWakeup++;
Narayan Kamath695cf722017-12-21 18:32:47 +00004482 ActivityManager.noteWakeupAlarm(
4483 alarm.operation, alarm.workSource, alarm.uid, alarm.packageName,
4484 alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004485 }
4486 }
4487 }
mswest463f4c99d2018-02-01 10:13:10 -08004488
4489 private class ShellCmd extends ShellCommand {
4490
4491 IAlarmManager getBinderService() {
4492 return IAlarmManager.Stub.asInterface(mService);
4493 }
4494
4495 @Override
4496 public int onCommand(String cmd) {
4497 if (cmd == null) {
4498 return handleDefaultCommands(cmd);
4499 }
4500
4501 final PrintWriter pw = getOutPrintWriter();
4502 try {
4503 switch (cmd) {
4504 case "set-time":
4505 final long millis = Long.parseLong(getNextArgRequired());
4506 return (getBinderService().setTime(millis)) ? 0 : -1;
4507 case "set-timezone":
4508 final String tz = getNextArgRequired();
4509 getBinderService().setTimeZone(tz);
4510 return 0;
4511 default:
4512 return handleDefaultCommands(cmd);
4513 }
4514 } catch (Exception e) {
4515 pw.println(e);
4516 }
4517 return -1;
4518 }
4519
4520 @Override
4521 public void onHelp() {
4522 PrintWriter pw = getOutPrintWriter();
4523 pw.println("Alarm manager service (alarm) commands:");
4524 pw.println(" help");
4525 pw.println(" Print this help text.");
4526 pw.println(" set-time TIME");
4527 pw.println(" Set the system clock time to TIME where TIME is milliseconds");
4528 pw.println(" since the Epoch.");
4529 pw.println(" set-timezone TZ");
4530 pw.println(" Set the system timezone to TZ where TZ is an Olson id.");
4531 }
4532 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004533}